// pages/s-remould-task/s-remould-task.js
var myRequest = require("../../utils/api.js");
var utils = require("../../utils/utils.js");

import {
  setWatcher
} from './watch.js';

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  
  data: {
    type: '',
    maxFile:10,
    showMultiTextAndTitle: false,
    handlerVisible: false,
    inputValue:[],
    handlerTitle: '改造类型',
    handlerValue: '',
    HandlersData: [],
    selectChange: '',
    checkArr: [0, undefined, undefined, undefined, undefined],
    distArr: {},
    proList: [],
    fileList: [],
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    filePath: '',
    planId: '',
    deviceName: '',
    build: {
      devCompany: '',
      consCompany: '',
      buildDate: '',
      manufacturer: '',
      img: ''
    },
    datetimeVisible: false,
    datetime: '',
    renovationList: [],
    mapVal: '',
    oldDevice: {
      id: '',
      name: ''
    },
    dictType: ['renovationType', 'renovationContent', 'renovationReason', 'renovationMeasure', 'prodInfo'],
    dialogType:null,
    dialogExitIndex:null
  },
  watch: {
    deviceName: {
      handler(v, o) {
        let mapVal = this.data.mapVal
        let type = this.data.type
        let oldDevice = this.data.oldDevice
        if (type = 'exit') {
          if (v != oldDevice.id) {
            if (mapVal.has(v)) {
              setTimeout(() => {
                wx.showToast({
                  title: '当前站点已有方案，请选择其他站点',
                  icon: 'none'
                })
                this.setData({
                  deviceName: oldDevice.id,
                  deviceName: oldDevice.name
                })
              }, 0);

            }
          }
        } else {
          if (mapVal.has(v)) {
            setTimeout(() => {
              wx.showToast({
                title: '当前站点已有方案，请选择其他站点',
                icon: 'none'
              })
              this.setData({
                deviceName: '',
                deviceName: ''
              })
            }, 0);

          }

        }


      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let data = JSON.parse(options.data)

    let mapVal = new Set(JSON.parse(data.mapVal))
    if (data.type == 'exit') {
      this.setData({
        type: 'exit',
        mapVal,
        planId: data.planId,
        deviceName: data.deviceName,
        oldDevice: {
          id: data.id,
          name: data.name
        },
        deviceName: data.deviceName
      })
      this.getRenList()
      this.getBuildInfo()
    } else {
      this.setData({
        mapVal,
        planId: data.planId,
      })
    }
    setWatcher(this);
  },
  isExitType(){
    return this.data.build.reviewStatus==3||this.data.build.reviewStatus==0||this.data.type!='exit'
  },
  chooseUpload() {
    var that = this
    wx.chooseMessageFile({
      count: 10,
      type: 'file',
      extension: ['.xlsx', '.xls', '.XLSX', '.XLS', 'xlsx', 'xls', 'XLSX', 'XLS'],
      success(res) {
        const tempFilePaths = res.tempFiles
        for (var i in tempFilePaths) {
          wx.uploadFile({
            url: 'http://xxx', //上传的服务器地址
            filePath: tempFilePaths[i].path,
            name: 'file',
            formData: {
              'file': tempFilePaths[i].path
                   },

            header: {
              [wx.getStorageSync('tokenName')]: wx.getStorageSync('token'),
            },
            success: function (resp) {
              console.log(resp)
              var data = JSON.parse(resp.data)
              console.log(data)
              if (data.code == 200) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'none',
                  duration: 1300
                })
              } else {
                wx.showToast({
                  title: data.message,
                  icon: 'none',
                  duration: 2000
                })
              }
            },
            fail: function (err) {
              console.log(err)
            }
          })
        }
      }
    })
  },

  onSetDist(e){

   this.setData({
    selectChange:e.detail.index
   })
   this.onPickerChange({
     detail:{
       value:[e.detail.val.value],
       label:[e.detail.val.label],
       item:e.detail.val.item
     }
   })
  },

  showPikcer(e) {
    if(this.isExitType()){
      let index = e.currentTarget.dataset.key
      if (this.data.checkArr[index] != undefined) {
        if (index != 4) {
          this.getlableData(this.data.checkArr[index],'').then(res => {
  
            this.setData({
              handlerVisible: true,
              HandlersData: res,
              selectChange: index
            })
  
          }).catch((e) => {
            wx.showToast({
              title: e,
              icon: 'none',
            })
          })
  
        } else {
          this.getProData(this.data.checkArr[index]).then(res => {
            this.setData({
              handlerVisible: true,
              HandlersData: res,
              selectChange: index
            })
  
          }).catch((e) => {
            wx.showToast({
              title: e,
              icon: 'none',
            })
          })
        }
  
      } else {
        wx.showToast({
          title: '请选择上级数据',
          icon: 'none',
        })
      }
  

    }

   

  },
  showPickerTime() {
  if(this.isExitType()){
    this.setData({
      datetime: this.data.build.buildDate ? this.data.build.buildDate : new Date().getTime(),
      datetimeVisible: true
    })
     
   }
  
  },
  onConfirm(e) {
    console.log(e)
    this.setData({
      'build.buildDate': e.detail.value
    })
  },
  handleAdd(e) {
    var that = this;
    const {
      files
    } = e.detail;
    var fileLists = this.data.fileList;
    for (let i = 0; i < files.length; i++) {
      myRequest.updateImg({
        file: files[i].url
      }).then(function (res) {
        fileLists.push({
          url: app.globalData.fileUrl + res,
          type: 'image',
          percent: 100
        });
        that.setData({
          fileList: fileLists,
        })
      }).catch(function (res) {
        console.log(res);
      })
    }
  },
  handleRemove(e) {
    if(!this.isExitType()){
      return 
    }
    const {
      index
    } = e.detail;
    const {
      fileList
    } = this.data;
    fileList.splice(index, 1);
    this.setData({
      fileList,
      
    });
  },
  handleSuccess(e) {

    var filed = e.currentTarget.dataset.filed;
    const {
      files
    } = e.detail;
    this.setData({

    });
  },
  focusHandle(e){
    let distArr=this.data.distArr
    distArr[4].prodModel=e.detail.value
    this.setData({
      distArr
    })
  },

  savedevDialog(e) {
    console.log(this.data.distArr)
    let dictType = this.data.dictType
    let renovationList = this.data.renovationList
   
    // if (Object.keys(this.data.distArr).length < 4) {
    //   wx.showToast({
    //     title: '请填写完整',
    //     icon: 'none',
    //   })
    //   return
    // }
    // let flag = false

    // renovationList.forEach(item => {
    //   if (item.renovationContent.dictId == this.data.distArr[1].value) {
    //     flag = true
    //   }
    // })
    // if (flag) {
    //   wx.showToast({
    //     title: '不可添加重复的整改内容',
    //     icon: 'none',
    //   })
    //   return
    // }



    let obj = {}
    for (let i in this.data.distArr) {
      console.log(i)
      if (i != 4) {
        obj[dictType[i]] = {
          dictId: this.data.distArr[i].value,
          dictName: this.data.distArr[i].label,
        }

      } else {
        obj[dictType[i]] = this.data.distArr[i]
      }

    }
    if(this.data.dialogType=='add'){
      renovationList.push(obj)
    }else{
       renovationList[this.data.dialogExitIndex]=obj
    }
    
    console.log(renovationList)
    this.setData({
      renovationList
    })
    



    this.closeDialog()
  },
  showDialog(e) {
    if(!this.isExitType()){
      return
    }
    if ( JSON.stringify(this.data.distArr) != '{}' && this.data.distArr[0].value != '') {
      this.checkData(0)
      this.setData({
        showMultiTextAndTitle: true,
        dialogType:'add'
      });

    } else {
      wx.showToast({
        title: '请选择改造类型',
        icon: 'none',
      })
    }

  },
  checkItemData(e){
   
    let {item,index} = e.currentTarget.dataset
    console.log(item,index)

    let inputValue=[item.renovationContent,item.renovationReason,item.renovationMeasure,{
      dictId:item.prodInfo.prodId,
      dictName:item.prodInfo.prodName,
      ...item.prodInfo}
    ]
    
    let distArr={
      ...this.data.distArr,
      1:{value:item.renovationContent.dictId,label:item.renovationContent.dictName},
      2:{value:item.renovationReason.dictId,label:item.renovationReason.dictName},
      3:{value:item.renovationMeasure.dictId,label:item.renovationMeasure.dictName},
      4:{
        value:item.prodInfo.prodId,
        label:item.prodInfo.prodModel,
        ...item.prodInfo}

    }
    this.setData({
      inputValue,
      distArr,
      showMultiTextAndTitle:true,
      dialogType:'exit',
      dialogExitIndex:index
    })
    console.log(this.data.distArr)
  },
  //清空数据选择
  checkData(index) {
    if(this.data.dialogType=='exit') return 
    let distArr = this.data.distArr
    for (let i in distArr) {
      if (i > index) {
        distArr[i] = {}
      }
    }
    this.setData({
      distArr
    })
  },
  getRenList() {
    let that = this;
    myRequest.myRequest('renovationList/list', {
      planId: that.data.planId,
      deviceName: that.data.deviceName
    }, 'get').then(function (res) {
      let responseData=res.data.data.items
      let distArr = {
        0: {
          value: responseData[0].renovationType.dictId,
          label: responseData[0].renovationType.dictName
        }
      }

      that.setData({
        distArr,
        [`checkArr[1]`]: responseData[0].renovationType.dictId,
        renovationList:responseData
      })
    }).catch(function (res) {
      console.log(res);
    })
  },
  getBuildInfo() {
    let that = this;
    myRequest.myRequest('renovationList/selectBuild', {
      planId: that.data.planId,
      deviceName: that.data.deviceName
    }, 'get').then(function (res) {
      if (res.data.data?.img) {
        let fileLists = []
        let img = JSON.parse(res.data.data.img)
        img.forEach(item => {
          fileLists.push({
            url: item,
            type: 'image',
            percent: 100
          });
        })

        that.setData({
          fileList: fileLists,
          maxFile:that.isExitType()?10:fileLists.length
        })

      }
      that.setData({
        build: res.data.data
      })
    }).catch(function (res) {
      console.log(res);
    })
  },
  ondelTap(e) {
    console.log(e)
    let index = e.currentTarget.dataset.index
    let renovationList = this.data.renovationList
    renovationList.splice(index, 1)
    this.setData({
      renovationList
    })
  },
  closeDialog() {
    let disArr = this.data.distArr
    let newdisArr = {
      0: disArr[0]
    }
    const child1 = this.selectComponent("#myComent1");  
    child1.clearvalue() 
    const child2 = this.selectComponent("#myComent2");  
    child2.clearvalue() 
    const child3 = this.selectComponent("#myComent3");  
    child3.clearvalue() 
    const  child4 = this.selectComponent("#myComent4");  
    child4.clearvalue() 
    this.setData({
      showMultiTextAndTitle: false,
      distArr: newdisArr
    });
  },
  search() {
    if(this.isExitType()){
      wx.navigateTo({
        url: '../search-site/search-site?type=xunjian',
      })
    }
   
  },
  changeInputDeviceName(e){
    this.setData({
      deviceName:e.detail.value
    })
  },
  changeInput(e) {
 
    let obj = e.currentTarget.dataset.key
    let key = `build.${obj}`
    let val = e.detail.value
    this.setData({
      [key]: val
    })
  },
  onPickerChange(e) {

    let distArr = this.data.distArr;
    if (this.data.selectChange != 4) {
      distArr[this.data.selectChange] = {
        value: e.detail.value[0],
        label: e.detail.label[0]
      }
    } else {
      if(e.detail.item){
        distArr[this.data.selectChange] =e.detail.item
      }else{
        distArr[this.data.selectChange]={
          prodName:e.detail.label[0]
        }
      }
     
    }

    let checkArr = this.data.checkArr;
    checkArr[parseInt(this.data.selectChange) + 1] = e.detail.value[0]
    this.checkData(this.data.selectChange)
    this.setData({
      distArr,
      checkArr,
    })
  },
  getlableData(parentId,dictName) {
    var that = this;
    return new Promise((resole, reject) => {
      myRequest.myRequest('renovationDict/list', {
        parentId,
        dictName
      }, 'get').then(function (res) {
        if (res.data.data.length) {
          let HandlersData = res.data.data.map(item => {
            return {
              label: item.dictName,
              value: item.dictId,
              item: item
            }
          })
          resole(HandlersData)

        } else {
          reject([])
        }

      }).catch(function (res) {
        console.log(res);
      })

    })

  },
  getProData(dictId) {
    var that = this;
    return new Promise((resole, reject) => {
    

    })

  },
 
  sumitData() {
    let that = this;
    let build = this.data.build
    let deviceName = this.data.deviceName
    let renovationList = JSON.parse(JSON.stringify(this.data.renovationList))
    build.img= ''
    if (that.data.fileList.length != 0) {
      let img = that.data.fileList.map(res => res.url)
      build.img = JSON.stringify(img)
    }
    let details = [] 
    renovationList.forEach(item => {
      for (let i in item) {
        console.log(i)
        if (i != 'prodInfo'&&i!='listId') {
          
       
        }else {     
          item['prodId'] = item[i].prodId
        }
      }
      
      details.push(item)
    })
    if (deviceName == '') {
      wx.showToast({
        title: '请输入站点名称',
        icon: 'none'
      })
      return
    }
    if (details.length == 0) {
      wx.showToast({
        title: '请完善整改详情',
        icon: 'none'
      })
      return
    }


    myRequest.myRequest('renovationList/add', {
      planId: that.data.planId,
      deviceName: deviceName,
      details: details,
      build: build
    }, 'post').then(function (res) {

      setTimeout(() => {
        var pages = getCurrentPages(); // 获取页面栈
        var prevPage = pages[pages.length - 2]; // 上一个页面
        prevPage.getPlanList()
        wx.navigateBack({
          delta: 1
        })
      }, 500);
      wx.showToast({
        title: '操作成功',
        icon: 'none',
      })
    }).catch(function (res) {
      console.log(res);
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  delsumitData() {
    let that = this
    
    myRequest.myRequest('renovationList/delete?planId=' + that.data.planId + '&buildId=' + that.data.build.buildId, {


    }, 'post').then(function (res) {
      setTimeout(() => {
        var pages = getCurrentPages(); // 获取页面栈
        var prevPage = pages[pages.length - 2]; // 上一个页面
        prevPage.getPlanList()
        wx.navigateBack({
          delta: 1
        })
      }, 500);
      wx.showToast({
        title: '操作成功',
        icon: 'none',
      })
    }).catch(function (res) {
      console.log(res);
    })
  },
  onReady: function () {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})