// pages/generateReport/generateReport.ts
import { informationList } from "../../apis/information";
import { list } from "../../apis/report";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: <any>{},
    current: 0,
    pageMap: ['基础信息', '学历教育', '非学历教育', '职业经历', '社会活动经历'],
    ids: [],
    checkList: <any>{
      基础信息: {
        checked: false,
        checkAll: false,
        indeterminate: false,
        // 手机号码: {
        //   checked: false,
        //   checkAll: false,
        //   indeterminate: false,
        //   value: []
        // },
        // 座机号码: {
        //   checked: false,
        //   checkAll: false,
        //   indeterminate: false,
        //   value: []
        // },
        // 通信地址: {
        //   checked: false,
        //   checkAll: false,
        //   indeterminate: false,
        //   value: []
        // },
        // 电子邮箱: {
        //   checked: false,
        //   checkAll: false,
        //   indeterminate: false,
        //   value: []
        // }
      },
      // 学历教育: [],
      // 非学历教育: [],
      // 职业经历: [],
      // 社会活动经历: []
    },
    toggles: <any>{
      学历教育: [],
      非学历教育: [],
      职业经历: [],
      社会活动经历: []
    }
    // eduToggles
  },
  dataFormat(data: any) {
    // console.log('##',data);

    let tempData = data
    let { checkList } = this.data

    Object.keys(tempData).forEach((listKey: any) => {
      if (Array.isArray(tempData[listKey])) {

        checkList[listKey] = {
          checkAll: false,
          indeterminate: false,
          value: []
        };
        let { toggles } = this.data
        tempData[listKey].map((item: any, itemIndex: any) => {
          if (
            listKey === "学历教育" ||
            listKey === "非学历教育" ||
            listKey === "职业经历" ||
            listKey === "社会活动经历"
          ) {
            toggles[listKey].push(true);
            this.setData({
              toggles
            })
            let tempObj = <any>{};
            // if (item['时间'] && !item['时间'].deleteTag) {
            Object.keys(item).forEach(eduKey => {
              if (eduKey !== "上级Id") {
                tempObj.checkAll = false;
                tempObj.indeterminate = false;
                if (item[eduKey].length > 0) {
                  tempObj[eduKey] = {
                    checked: false,
                    checkAll: false,
                    indeterminate: false,
                    keys: [],
                    value: []
                  };
                  item[eduKey].map((eventItem: {}, eventItemIndex: string | number) => {
                    // console.log('eventItem', eventItem);

                    let eventItemKeys: any[] = [];
                    Object.keys(eventItem).forEach(eventKey => {
                      if (eventKey !== "上级Id") {
                        eventItemKeys.push(
                          item[eduKey][eventItemIndex][eventKey].dataId
                        );
                      }
                    });
                    // console.log(eduKey,eventItemKeys.toString());

                    tempObj[eduKey].keys.push(eventItemKeys.toString())

                    tempObj[eduKey].value.push({
                      [eventItemKeys.toString()]: false
                    });

                    // console.log(tempObj[eduKey].value);
                  });
                } else {
                  tempObj[eduKey] = {
                    [item[eduKey].dataId]: false
                  };
                }
              }
            });
            checkList[listKey].value.push(tempObj);
            // }
          }
        });

      } else {
        Object.keys(tempData[listKey]).forEach(item => {
          // console.log('###', tempData);

          if (item !== "上级Id") {
            if (Array.isArray(tempData[listKey][item])) {   
              checkList[listKey][item] = {
                checked: false,
                checkAll: false,
                indeterminate: false,
                value: []
              }
              tempData[listKey][item].map((arr: { [x: string]: { dataId: any; }; }) => {
                checkList[listKey][item].value.push({
                  [arr["值"].dataId]: false
                });
              });
            } else {
              checkList[listKey][item] = {
                checked: false,
                checkAll: false,
                indeterminate: false,
                [tempData[listKey][item].dataId]: false
              };
            }
          }
        });
        this.setData({
          checkList
        })
      }
    });
  },
  previewImg(e: WechatMiniprogram.CustomEvent) {
    const { url } = e.currentTarget.dataset
    wx.previewMedia({ sources: [{ url }], current: 0 })
  },

  handleToggle(e: WechatMiniprogram.CustomEvent) {
    const { key, index } = e.currentTarget.dataset
    let { toggles } = this.data
    toggles[key][index] = !toggles[key][index]
    this.setData({
      toggles
    })
  },

  getInformation() {
    informationList().then((res: any) => {
      if (res.c === 200) {
        let tempData = res.d.jsonObject;
        Object.keys(tempData).forEach((key1: string) => {
          if (key1 === '基础信息') {
            Object.keys(tempData[key1]).forEach((key2: string) => {
              if (key2 !== '上级Id') {
                if (Array.isArray(tempData[key1][key2])) {
                  let deleteIdx: any[] = []
                  tempData[key1][key2].map((item: any, index: number) => {
                    if (key2 === '手机号码') {
                      if (item['值'].phoneExpireTag) {
                        deleteIdx.push(index)
                      }
                    } else {
                      if (item['值'].deleteTag) {
                        deleteIdx.push(index)
                      }
                    }
                  })
                  deleteIdx.reverse().map(idx => {
                    tempData[key1][key2].splice(idx, 1)
                  })
                }
              }
            })
          } else {

          }
        })

        let keyArr = ['学历教育', '非学历教育', '职业经历', '社会活动经历']

        keyArr.map((key: string) => {
          let deleteIdx: any[] = []
          let eDeleteIdx: any[] = []
          // let temp = tempData[key]
          tempData[key] && tempData[key].map((item: any, index: number) => {
            if (key !== '社会活动经历') {
              if (!item['时间'].deleteTag) {
                if (item['附件']) {
                  let temps = this.strToArr(item['附件'].dataValue)
                  let fileArr: { name: string[]; url: string }[] = []
                  temps.map((item: any) => {
                    fileArr.push({
                      name: item.split(':')[2],
                      url: item
                    })
                  })
                  item['附件'].dataValue = fileArr
                }
                if (item['事件/活动记录']) {
                  item['事件/活动记录'].map((eventItem: any, eventIndex: any) => {
                    if (eventItem['附件']) {
                      let temps = this.strToArr(eventItem['附件'].dataValue || '')
                      let fileArr: { name: string[]; url: string }[] = []
                      temps.map((tempItem: any) => {
                        fileArr.push({
                          name: tempItem.split(':')[2],
                          url: tempItem
                        })
                      })
                      item['事件/活动记录'][eventIndex]['附件'].dataValue = fileArr
                    }
                  })
                }
                if (item['岗位记录']) {
                  item['岗位记录'].map((eventItem: any, eventIndex: any) => {
                    if (!eventItem['时间'].deleteTag) {
                      if (eventItem['附件']) {
                        let temps = this.strToArr(eventItem['附件'].dataValue || '')
                        let fileArr: { name: string[]; url: string }[] = []
                        temps.map((tempItem: any) => {
                          fileArr.push({
                            name: tempItem.split(':')[2],
                            url: tempItem
                          })
                        })
                        item['岗位记录'][eventIndex]['附件'].dataValue = fileArr
                      }
                    } else {
                      // console.log(eventItem,key);
                      eDeleteIdx.push(eventIndex)
                    }

                  })
                  // console.log('delete',eDeleteIdx);

                  eDeleteIdx.reverse().map(idx => {
                    tempData[key][index]['岗位记录'].splice(idx, 1)
                  })
                }
              } else {
                // console.log('删除',key,index,tempData[key][index]['教育机构'].dataValue)
                // tempData[key].splice(index, 1)
                deleteIdx.push(index)
              }
            } else {
              if (item['事件/活动记录']) {
                item['事件/活动记录'].map((eventItem: any, eventIndex: any) => {
                  if (!eventItem['时间'].deleteTag) {
                    if (eventItem['附件']) {
                      let temps = this.strToArr(eventItem['附件'].dataValue || '')
                      let fileArr: { name: string[]; url: string }[] = []
                      temps.map((tempItem: any) => {
                        fileArr.push({
                          name: tempItem.split(':')[2],
                          url: tempItem
                        })
                      })
                      item['事件/活动记录'][eventIndex]['附件'].dataValue = fileArr
                    }
                  } else {
                    eDeleteIdx.push(eventIndex)
                  }

                })
                eDeleteIdx.reverse().map(idx => {
                  tempData[key][index]['事件/活动记录'].splice(idx, 1)
                })
              }
            }
          })
          deleteIdx.reverse().map(idx => {
            tempData[key].splice(idx, 1)
          })
        })



        this.setData({
          list: tempData
        })
        this.dataFormat(tempData)
      }
    })
  },

  checkboxChange(e: any) {
    console.log(e);
  },

  preStep() {
    let { current } = this.data
    this.setData({
      current: current--
    })
  },

  nextStep() {
    let { current } = this.data
    this.setData({
      current: current + 1
    })
  },

  preview() {
    let ids = this.getCheckListIds()
  },

  complate() {
    let ids = this.getCheckListIds()
    wx.setStorageSync('reportIds', ids)
    wx.navigateTo({
      url: '/pages/createReport/createReport'
    })
  },

  previewReport() {
    let ids = this.getCheckListIds()
    wx.setStorageSync('reportIds', ids)
    if (ids.length > 0) {
      wx.navigateTo({
        url: `/pages/reportPreview/reportPreview?type=0&active=1`
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '请勾选最少一条数据'
      })
    }
  },

  getCheckListIds() {
    let filterMap = ["checkAll", "indeterminate", "checked", "keys"];
    let ids: any[] = [];
    const { checkList } = this.data
    Object.keys(checkList).forEach(key1 => {
      Object.keys(checkList[key1]).forEach(key2 => {
        if (filterMap.indexOf(key2) === -1) {
          if (Array.isArray(checkList[key1][key2])) {
            // 2-5
            checkList[key1][key2].map((item: any) => {
              Object.keys(item).forEach(key => {
                if (filterMap.indexOf(key) === -1) {
                  if (item[key].value !== undefined) {
                    item[key].value.map((ite: any) => {
                      if (ite[Object.keys(ite)]) {
                        // console.log(Object.keys(ite));
                        Object.keys(ite)
                          .toString()
                          .split(",")
                          .map(v => {
                            ids.push(v);
                          });
                      }
                    });
                  } else {
                    if (item[key][Object.keys(item[key])]) {
                      // console.log("######", Object.keys(item[key]));
                      ids.push(Object.keys(item[key]).toString());
                    }
                  }
                }
              });
            });
          } else {
            // 1 基础信息
            console.log("1 基础信息");
            Object.keys(checkList[key1][key2]).forEach(biKey => {
              if (filterMap.indexOf(biKey) === -1) {
                if (Array.isArray(checkList[key1][key2][biKey])) {
                  checkList[key1][key2][biKey].map((item: any) => {
                    if (item[Object.keys(item)] === true) {
                      ids.push(Object.keys(item).toString());
                    }
                  });
                } else {
                  if (checkList[key1][key2][biKey]) {
                    ids.push(biKey);
                  }
                }
              }
            });
          }
        }
      });
    });
    return ids;
  },

  strToArr(str: string) {
    // console.log(str);

    return (str || '').split(',')
  },

  handleTabChange(e: WechatMiniprogram.CustomEvent) {
    console.log(e);

    this.setData({
      current: e.currentTarget.dataset.index
    })
  },

  handleChecked(e: WechatMiniprogram.CustomEvent) {
    console.log(e);

    const { dataid, key1, key2, index, eindex } = e.currentTarget.dataset
    let { checkList, list } = this.data
    console.log(dataid, key1, key2, index, eindex);

    let filterMap = ["checkAll", "indeterminate", "checked"];

    if (key1 === '基础信息') {
      let tempList = list[key1][key2];
      if (index === undefined) {
        checkList[key1][key2][dataid] = !checkList[key1][key2][dataid]
      } else {
        console.log(checkList[key1][key2].value[index][dataid]);

        checkList[key1][key2].value[index][dataid] = !checkList[key1][key2].value[index][dataid]
        tempList = tempList.filter((item: any) => !item["值"].deleteTag);

      }
    } else {
      if (key2 === '事件/活动记录' || key2 === '岗位记录') {
        Object.keys(checkList[key1].value[index][key2].value[eindex]).forEach((ekey: string) => {
          checkList[key1].value[index][key2].value[eindex][ekey] = !checkList[key1].value[index][key2].value[eindex][ekey]
        })
      } else {
        checkList[key1].value[index][key2][list[key1][index][key2].dataId] = !checkList[key1].value[index][key2][list[key1][index][key2].dataId]
      }
    }



    this.setData({
      checkList,
    })
    this.checkHalf(key1, key2, index)
  },

  checkHalf(key1: string, key2: string, index: number) {
    const { checkList } = this.data;
    let max = 0;
    let checkedCount = 0;
    let filterMap = ['checked', 'checkAll', 'indeterminate']
    let listMax = 0;
    let listCheckedCount = 0;
    // 当前
    if (key1 === '基础信息') {
      Object.keys(checkList[key1]).forEach((key: string) => {
        if (filterMap.indexOf(key) === -1) {
          if (Array.isArray(checkList[key1][key].value)) {
            // max += checkList[key1][key].value.length;
            checkList[key1][key].value.map(item => {
              max++;
              if (key === key2) {
                listMax++;
              }
              // 
              if (item[Object.keys(item)] === true) {
                checkedCount++;
                if (key === key2) {
                  listCheckedCount++;
                }
              }
            })

            checkList[key1][key2 || key].checkAll = key2 === undefined ? checkList[key1].checkAll : listCheckedCount === listMax;
            checkList[key1][key2 || key].indeterminate =
              listCheckedCount > 0 && listCheckedCount < listMax;
          } else {
            if (checkList[key1][key][Object.keys(checkList[key1][key])] === true) {
              checkedCount++;
            }
            max++
          }
        }
      })
    } else {
      console.log(checkList[key1].value, index);

      Object.keys(checkList[key1].value[index]).forEach(key => {
        console.log(key);

        if (filterMap.indexOf(key) === -1) {
          if (checkList[key1].value[index][key].value) {
            checkList[key1].value[index][key].value.map((item: any) => {
              max++;
              if (key2 === '事件/活动记录' || key2 === '岗位记录') {
                if (key === key2) {
                  listMax++;
                }
              }
              if (item[Object.keys(item)] === true) {
                checkedCount++;
                if (key === key2) {
                  listCheckedCount++;
                }
              }
              if (key === key2) {
                console.log(listMax, listCheckedCount);

                checkList[key1].value[index][key2 || key].checkAll = key2 === undefined ? checkList[key1].value[index].checkAll : listCheckedCount === listMax;
                checkList[key1].value[index][key2 || key].indeterminate =
                  listCheckedCount > 0 && listCheckedCount < listMax;
              }
            })
          } else {
            max++;
            if (checkList[key1].value[index][key][Object.keys(checkList[key1].value[index][key])] === true) {
              checkedCount++;
            }
          }
        }
      })

      checkList[key1].value[index].checkAll = checkedCount === max;
      checkList[key1].value[index].indeterminate =
        checkedCount > 0 && checkedCount < max;
    }
    this.setData({
      checkList
    })
  },

  handleCheckAll(e: WechatMiniprogram.CustomEvent) {
    const { key1, key2, index } = e.currentTarget.dataset
    let { checkList, list } = this.data
    if (key2 === '事件/活动记录' || key2 === '岗位记录') {
      checkList[key1].value[index][key2].checkAll = !checkList[key1].value[index][key2].checkAll
      checkList[key1].value[index][key2].indeterminate = false
      list[key1][index][key2].map((item: any, idx: number) => {
        checkList[key1].value[index][key2].value.map((eItem: any, eidx) => {
          eItem[checkList[key1].value[index][key2].keys[eidx]] = checkList[key1].value[index][key2].checkAll
        })
      })
    } else {

      if (key2 === undefined) {
        // console.log('=undefinde');

        checkList[key1].value[index].checkAll = !checkList[key1].value[index].checkAll
        Object.keys(list[key1][index]).forEach((tmpKey2: string) => {
          if (tmpKey2 !== '上级Id') {
            if (Array.isArray(list[key1][index][tmpKey2])) {
              list[key1][index][tmpKey2].map((item: any, eventIndex: number) => {

                checkList[key1].value[index][tmpKey2].checkAll = checkList[key1].value[index].checkAll
                checkList[key1].value[index][tmpKey2].value[eventIndex][checkList[key1].value[index][tmpKey2].keys[eventIndex]] = checkList[key1].value[index].checkAll
              })
            } else {
              checkList[key1].value[index][tmpKey2][list[key1][index][tmpKey2].dataId] = checkList[key1].value[index].checkAll
            }
          }
        })
      } else {
        checkList[key1][key2].checkAll = !checkList[key1][key2].checkAll
        checkList[key1][key2].indeterminate = false
        list[key1][key2].map((item: any, idx: number) => {
          if (!item['值'].deleteTag) {
            checkList[key1][key2].value[idx][item['值'].dataId] = checkList[key1][key2].checkAll
          }
        })
      }
    }

    this.setData({
      checkList
    })
  },

  handleCurrentPageCheckAll(e: WechatMiniprogram.CustomEvent) {
    const { key1 } = e.currentTarget.dataset
    let { checkList, list } = this.data
    checkList[key1].checkAll = !checkList[key1].checkAll


    if (key1 === '基础信息') {
      Object.keys(list[key1]).forEach(key => {

        if (key !== '上级Id') {
          if (Array.isArray(list[key1][key])) {
            checkList[key1][key].checkAll = checkList[key1].checkAll
            list[key1][key].map((item: any, index: number) => {
              if (!item['值'].deleteTag) {
                checkList[key1][key].value[index][item['值'].dataId] = checkList[key1].checkAll
              }
            })
          } else {
            checkList[key1][key][list[key1][key].dataId] = checkList[key1].checkAll
          }
        }
      })
      this.checkHalf(key1)
    } else {
      list[key1].map((item: any, index: number) => {
        checkList[key1].value[index].checkAll = checkList[key1].checkAll
        checkList[key1].value[index].indeterminate = false
        Object.keys(item).forEach((key2: string) => {
          if (key2 !== '上级Id') {
            if (Array.isArray(item[key2])) {
              checkList[key1].value[index][key2].checkAll = checkList[key1].checkAll
              item[key2].map((event: any, eIndex: any) => {
                checkList[key1].value[index][key2].value[eIndex][checkList[key1].value[index][key2].keys[eIndex]] = checkList[key1].checkAll
              })
            } else {
              checkList[key1].value[index][key2][item[key2].dataId] = checkList[key1].checkAll
            }
          }
        })
      })
    }


    this.setData({
      checkList
    })

    // checkList[key1]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getInformation()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})