// pages/certification/certification.ts
import { informationDelete, updateWithDataId, informationList, informationAdd, agentApply } from "../../apis/information";
const app = getApp<IAppOption>()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    form: {},
    fileNameList: [],
    eventList: [],
    formName: '',
    modifiable: false,
    index: 0,
    visible: false,
    superiorIdAttachInfoResponseVoMap: []
  },
  strToArr(str: string) {
    return (str || '').split(',')
  },

  deleteAllDetail() {
    this.setData({
      visible: true
    })
  },
  deleteAllEvent(e) {
    // console.log(e);
    const { index } = this.data
    informationDelete({
      dataId: e.currentTarget.dataset.id,
      deleteAll: true
    }).then(() => {
      wx.showToast({
        icon: 'none',
        title: `删除成功`
      })
      this.getInformation(index)
    })
  },
  confirmDelete() {
    informationDelete({
      dataId: this.data.form['上级Id'],
      deleteAll: true
    }).then(() => {
      this.setData({
        visible: false
      })
      wx.navigateBack({
        delta: 1
      })
    })
  },
  confirmCancel() {
    this.setData({
      visible: false
    })
  },
  handleDeleteFile(e) {
    let that = this
    let { form } = this.data
    const { index } = e.currentTarget.dataset.index
    const { dataId, dataName, dataValue } = form['附件']
    let tempArr = dataValue
    tempArr.splice(index, 1)

    let payload = {
      updateDataList: [{
        dataId,
        dataName,
        dataValue: tempArr.map((item: { url: string; }) => item.url).toString(),
        modifiable: true,
      }]
    }
    updateWithDataId(payload).then((res: any) => {
      if (res.c === 200) {
        form['附件'].dataValue = tempArr
        that.setData({
          form,
        })
      }
    })
  },
  handleDeleteEventFile(e) {
    // let that = this
    let { form, index } = this.data
    const { findex, eindex } = e.currentTarget.dataset
    const { dataId, dataName, dataValue } = form['事件/活动记录'][eindex]['附件']
    let tempArr = dataValue
    tempArr.splice(findex, 1)

    let payload = {
      updateDataList: [{
        dataId,
        dataName,
        dataValue: tempArr.map((item: { url: string }) => item.url).toString(),
        modifiable: true,
      }]
    }
    // console.log(payload);

    updateWithDataId(payload).then((res: any) => {
      if (res.c === 200) {
        // form['事件/活动记录'][eindex]['附件'].dataValue = tempArr
        // that.setData({
        //   form,
        // })
        this.getInformation(index)
      }
    })
  },
  handleDeletePostFile(e) {
    let that = this
    let { form, index } = this.data
    const { findex, eindex } = e.currentTarget.dataset
    const { dataId, dataName, dataValue } = form['岗位记录'][eindex]['附件']
    let tempArr = dataValue
    tempArr.splice(findex, 1)

    let payload = {
      updateDataList: [{
        dataId,
        dataName,
        dataValue: tempArr.map((item: { url: string; }) => item.url).toString(),
        modifiable: true,
      }]
    }
    // console.log(payload);

    updateWithDataId(payload).then((res: any) => {
      if (res.c === 200) {
        // form['岗位记录'][eindex]['附件'].dataValue = tempArr
        // that.setData({
        //   form,
        // })
        this.getInformation(index)
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    // let tempData = wx.getStorageSync('informationDetail')
    this.setData({
      formName: wx.getStorageSync('informationName'),
      index: options.index
    })
    this.getInformation(options.index)
  },
  handleRecords(e) {
    wx.navigateTo({
      url: '/pages/dataRecords/dataRecords?id=' + e.currentTarget.dataset.id
    })
  },
  handleCorrigendum(e) {
    wx.navigateTo({
      url: `/pages/corrigendum/corrigendum?id=${e.currentTarget.dataset.id}`
    })
  },
  handleAddEvent(e) {
    // console.log(e);
    const { eventid, eventname } = e.currentTarget.dataset
    wx.setStorageSync('eventId', eventid);
    wx.setStorageSync('eventName', eventname);
    wx.navigateTo({
      url: '/pages/informationEventCreate/informationEventCreate'
    })
  },
  handleAdd(e) {
    const { dataname } = e.currentTarget.dataset
    const { formName, form } = this.data
    wx.setStorageSync('informationName', formName)
    wx.setStorageSync('informationEditDataName', dataname)
    wx.navigateTo({
      url: `/pages/informationEdit/informationEdit?type=add&keyId=${form['上级Id']}`
    })
  },
  handleEdit(e) {
    // console.log(e);
    const { value } = e.currentTarget.dataset
    const { formName } = this.data
    wx.setStorageSync('informationEditInfo', value)
    wx.setStorageSync('informationName', formName)
    wx.setStorageSync('informationEditDataName', formName === '职业经历' ? (value.dataName === '内容' ? '岗位描述' : value.dataName) : (value.dataName === '内容' ? '事件描述' : value.dataName))
    wx.navigateTo({
      url: `/pages/informationEdit/informationEdit?type=edit`
    })
  },
  //监听组件事件，返回的结果
  postListener: function (e) {
    console.log("上传的图片结果集合", e)
    console.log(e.detail.picsList)
    let { form, index } = this.data
    let { eindex } = e.currentTarget.dataset
    // let eIndex = e.currentTarget.dataset.index
    // console.log(index,eIndex);

    // console.log(form['岗位记录'][0]);

    if (form['岗位记录'] && form['岗位记录'][eindex]['附件']) {
      const { dataId, dataName, dataValue } = form['岗位记录'][eindex]['附件']
      let payload = {
        updateDataList: [{
          dataId,
          dataName,
          dataValue: dataValue.map(item => item.url).toString() + ',' + e.detail.picsList.map(item => item.url).toString(),
          modifiable: true,
        }]
      }
      console.log(payload);


      updateWithDataId(payload).then(res => {
        if (res.c === 200) {
          // e.detail.picsList.map(item => {
          //   form['岗位记录'][e.currentTarget.dataset.index]['附件'].dataValue.push(item)
          // })

          // this.setData({
          //   form: form
          // })
          this.getInformation(index)
        }
      })
    } else {
      // add
      let payload = {
        [form['岗位记录'][eindex]['上级Id']]: [
          {
            附件: e.detail.picsList.map((item: any) => item.url).toString()
          }
        ]
      }
      // let payload = {
      //   [form['上级Id']]: {
      //     ['岗位记录']:
      //       [
      //         {
      //           附件: e.detail.picsList.map(item => item.url).toString()
      //         }
      //       ]
      //   }
      // }
      console.log(payload);


      informationAdd(payload).then(res => {
        if (res.c === 200) {
          this.getInformation(index)
        }
      })
    }

  },
  eventListener: function (e) {
    console.log("上传的图片结果集合", e)
    console.log(e.detail.picsList)
    let { form, formName, index } = this.data
    const { eindex } = e.currentTarget.dataset

    if (formName === '社会活动经历') {
      if (form['附件']) {
        const { dataId, dataName, dataValue } = form['附件']
        let payload = {
          updateDataList: [{
            dataId,
            dataName,
            dataValue: dataValue.map(item => item.url).toString() + ',' + e.detail.picsList.map(item => item.url).toString(),
            modifiable: true,
          }]
        }
        console.log(payload);


        updateWithDataId(payload).then(res => {
          if (res.c === 200) {
            this.getInformation(index)
          }
        })
      } else {
        // add
        let payload = {
          jsonObject: {
            [form['上级Id']]: [
              {
                附件: e.detail.picsList.map(item => item.url).toString()
              }
            ]
          }
        }
        console.log(payload);
        if(!e.detail.picsList.length>0){
          informationAdd(payload).then(res => {
            if (res.c === 200) {
              this.getInformation(index)
            }
          })
        }
        
      }
    } else {
      if (form['事件/活动记录'][eindex]['附件']) {
        const { dataId, dataName, dataValue } = form['事件/活动记录'][eindex]['附件']
        let payload = {
          updateDataList: [{
            dataId,
            dataName,
            dataValue: dataValue.map((item: any) => item.url).toString() + ',' + e.detail.picsList.map(item => item.url).toString(),
            modifiable: true,
          }]
        }
        updateWithDataId(payload).then((res: any) => {
          if (res.c === 200) {
            this.getInformation(index)
          }
        })
      } else {
        // add
        let payload = {
          jsonObject: {
            [form['事件/活动记录'][eindex]['上级Id']]: [
              {
                附件: e.detail.picsList.map((item: any) => item.url).toString()
              }
            ]
          }
        }
        console.log(payload);

        informationAdd(payload).then((res: any) => {
          if (res.c === 200) {
            this.getInformation(index)
          }
        })
      }
    }


  },
  fileListener: function (e) {
    console.log("上传的图片结果集合", e)
    console.log(e.detail.picsList)
    let { form, index } = this.data
    if (form['附件']) {
      const { dataId, dataName, dataValue } = form['附件']

      let payload = {
        updateDataList: [{
          dataId,
          dataName,
          dataValue: dataValue.map(item => item.url).toString() + ',' + e.detail.picsList.map(item => item.url).toString(),
          modifiable: true,
        }]
      }
      console.log(payload);


      updateWithDataId(payload).then(res => {
        if (res.c === 200) {

          this.getInformation(index)
        }
      })
    } else {
      // add
      let payload = {
        jsonObject: {
          [form['上级Id']]: [
            {
              附件: e.detail.picsList.map((item: any) => item.url).toString()
            }
          ]
        }
      }
      // console.log(payload);


      informationAdd(payload).then((res: any) => {
        if (res.c === 200) {
          this.getInformation(index)
        }
      })
    }

  },
  previewImg(e) {
    const { sources } = e.currentTarget.dataset

    wx.previewMedia({ sources: [{ url: sources }], current: 0 })

  },
  getInformation(index: number) {
    console.log('getInformation', index);

    const { formName } = this.data
    informationList().then((res: any) => {
      if (res.c === 200) {
        let tempData = this.data.formName === '社会活动经历' ? res.d.jsonObject[this.data.formName][0]['事件/活动记录'][index] : res.d.jsonObject[this.data.formName][index]
        // console.log('#####################', res.d[this.data.formName][index]);

        if (tempData['附件'] !== undefined) {
          let temps = this.strToArr(tempData['附件'].dataValue)
          let fileArr: { name: string[]; url: string }[] = []
          temps.map((item: any) => {
            if (item !== '') {
              fileArr.push({
                name: item.split(':')[2],
                url: item
              })
            }

          })
          tempData['附件'].dataValue = fileArr
        }
        if (tempData['事件/活动记录']) {
          tempData['事件/活动记录'].map((item: any, index: any) => {
            if (item['附件']) {
              // console.log("item['附件']", item['附件']);
              let temps = this.strToArr(item['附件'].dataValue || '')
              let fileArr: { name: string[]; url: string }[] = []
              temps.map((item: any) => {
                if (item !== '') {
                  fileArr.push({
                    name: item.split(':')[2],
                    url: item
                  })
                }
              })
              tempData['事件/活动记录'][index]['附件'].dataValue = fileArr
            }
          })
        }
        if (tempData['岗位记录']) {
          tempData['岗位记录'].map((item, index) => {
            if (item['附件']) {
              // console.log("item['附件']", item['附件']);
              let temps = this.strToArr(item['附件'].dataValue || '')
              let fileArr: { name: string[]; url: string }[] = []

              temps.map(item => {
                if (item !== '') {
                  fileArr.push({
                    name: item.split(':')[2],
                    url: item
                  })
                }
              })
              tempData['岗位记录'][index]['附件'].dataValue = fileArr
            }
          })
        }
        this.setData({
          form: tempData,
          modifiable: tempData['时间'].modifiable,
          superiorIdAttachInfoResponseVoMap: res.d.superiorIdAttachInfoResponseVoMap
        })
      }
    })
  },
  handleApply() {
    this.selectComponent('#' + 'shadow2').show()
  },
  submitApply() {
    // let paylo
    const { formName, form } = this.data
    console.log(form, formName);
    // switch 
    // agentApply().then(res=>{
    //   console.log(res);

    // })
    let payload = {
      businessNameAuthenticationName: '',
      superiorId: form['上级Id']
    }
    if (formName === '学历教育' || formName === '非学历教育') {
      payload.businessNameAuthenticationName = form['教育机构'].dataValue
    } else {
      payload.businessNameAuthenticationName = form['单位名称'].dataValue
    }
    // console.log(payload);
    agentApply(payload).then(res => {
      // console.log(res);
      if (res.c === 200) {
        wx.showToast({
          icon: 'none',
          title: '提交成功'
        })
      }
      this.getInformation(this.data.index)
    })
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getInformation(this.data.index)
  },

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

  },

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

  },

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

  },

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

  },

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

  }
})