// pages/worksheetinfo/worksheetinfo.js
let Util = require("../../utils/util");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    images: [],
    signs: [],
    worksheetinfo: {},
    chargstations: [],
    chargstationsindex: 0,
    pcitures: [],
    workstatus: [{
      value: 1,
      text: '新建'
    }, {
      value: 2,
      text: '指派人员'
    }, {
      value: 3,
      text: '指派确认'
    }, {
      value: 4,
      text: '施工前安全准备'
    }, {
      value: 5,
      text: '进行中'
    }
    , {
      value: 6,
      text: '完成工作内容'
    }
    ],
    workstatusindex: 0,
    workstatusFinished: false,
    workBigclass: [{
      value: 1,
      text: '售后服务'
    }, {
      value: 2,
      text: '工程实施'
    }],
    workBigclassindex: 0,
    wokSmallclass:[{
      value: 1,
      text: '日常巡站'
      }, {
      value: 2,
      text: '紧急维修'
      }, {
      value: 3,
      text: '施工准备'
      }, {
      value: 4,
      text: '工程进程'
      }, {
      value: 5,
      text: '施工过程'
      }, {
      value: 6,
      text: '工程竣工'
      }, {
      value: 7,
      text: '工程验收'
      }, {
        value: 8,
        text: '其他'
      }],
    wokSmallclassIndex: 1,
    breakdownType: [{
      value: 1,
      text: '车辆导致'
    }, {
      value: 2,
      text: '桩体导致'
    }, {
      value: 3,
      text: '人为导致'
    }, {
      value: 4,
      text: '基础设施问题'
    }, {
      value: 5,
      text: '其他'
    }],
    breakdownTypeindex: 1,
    exceptdate: null,
    excepttime: '00:00',
    finishdate: null,
    finishtime: '00:00',
    exceptparams:{
      placeholder: '请选择时间', 
      startDateTime: '2020-01-01 00:00',
      endDateTime: '2040-01-01 00:00',
      pText: Util.formatTimePicker(new Date()) //'2022-04-30 00:00'
    },
    finishparams:{
      placeholder: '请选择时间', 
      startDateTime: '2020-01-01 00:00',
      endDateTime: '2040-01-01 00:00',
      pText: Util.formatTimePicker(new Date()), //'2022-04-30 00:00'
      pTextOld: null,
      flag: true
    },
    workEndtimeParams:{
      placeholder: '请选择时间', 
      startDateTime: '2020-01-01 00:00',
      endDateTime: '2040-01-01 00:00',
      pText: Util.formatTimePicker(new Date()) //'2022-04-30 00:00'
      // pText: '0000-00-00 00:00' //'2022-04-30 00:00'
    },
    accendantids: [],
    userNames:[],
    chargStationName:'',
    chargStationNameClearFlag: false



  },
  chargStationNameSelect:function(e){
    let url = `/pages/worksheetinfo/findstation`;
    wx.navigateTo({
      url
    });
  },
  bindChargstationsChange: function(e) {
    if (this.data.chargstationsindex != e.detail.value) {
      //console.log('picker发送选择改变，携带值为', e.detail.value)
      let chargstationid = this.data.chargstations[e.detail.value].id;
      let worksheetinfo = this.data.worksheetinfo;
      worksheetinfo.accendant = null;
      worksheetinfo.chargStationId = chargstationid;
      this.setData({
        chargstationsindex: e.detail.value,
        worksheetinfo
      })
    }

  },
  bindWorkstatusChange: function(e) {
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    let workStatus = this.data.workstatus[e.detail.value].value;
    let worksheetinfo = this.data.worksheetinfo;
    worksheetinfo.workStatus = workStatus;
    this.setData({
      workstatusindex: e.detail.value,
      worksheetinfo
    });
    if(e.detail.value == 5){
      let finishparams = this.data.finishparams
      finishparams['pTextOld'] =  this.data.finishparams.pText
      finishparams['pText'] = Util.formatTimePicker(new Date())
      finishparams['flag'] = false
      this.setData({
        finishparams: finishparams,
      });
    }
    console.log(this.data.finishparams);
    if(e.detail.value != 5 && !this.data.finishparams.flag){
      let finishparams = this.data.finishparams
      finishparams.pText = this.data.finishparams.pTextOld
      this.setData({
        finishparams: finishparams,
      });
    }
  },
  bindWorkBigclassChange: function(e) {
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    let workBigclass = this.data.workBigclass[e.detail.value].value;
    let worksheetinfo = this.data.worksheetinfo;
    worksheetinfo.workBigclass = workBigclass;
    this.setData({
      workBigclassindex: e.detail.value,
      worksheetinfo
    });
  },
  bindwokSmallclassChange: function(e) {
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    let wokSmallclass = this.data.wokSmallclass[e.detail.value].value;
    let worksheetinfo = this.data.worksheetinfo;
    worksheetinfo.wokSmallclass = wokSmallclass;
    this.setData({
      wokSmallclassindex: e.detail.value,
      worksheetinfo
    });
  },
  bindBreakdownType(e) {
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    let breakdownType = this.data.breakdownType[e.detail.value].value;
    let worksheetinfo = this.data.worksheetinfo;
    worksheetinfo.breakdownType = breakdownType;
    this.setData({
      breakdownTypeindex: e.detail.value,
      worksheetinfo
    });
  },
  bindAccendantChange: function(e) {
    let chargstationid = this.data.worksheetinfo.chargStationId==null?0:this.data.worksheetinfo.chargStationId;
    let accendant = this.data.worksheetinfo.accendant;
    let url = `/pages/worksheetinfo/accendant?chargstationid=${chargstationid}&accendant=${accendant}`;
    wx.navigateTo({
      url
    });
  },
  bindExceptdateChange(e) {
    this.setData({
      exceptdate: e.detail.value
    })
  },
  bindExcepttimeChange(e) {
    this.setData({
      excepttime: e.detail.value
    })
  },
  bindFinishdateChange(e) {
    this.setData({
      finishdate: e.detail.value
    })
  },
  bindFinishtimeChange(e) {
    this.setData({
      finishtime: e.detail.value
    })
  },
  bindMainLocationInput(e) {
    let mainLocation = e.detail.value;
    let worksheetinfo = this.data.worksheetinfo;
    worksheetinfo.mainLocation = mainLocation;
    this.setData({
      worksheetinfo
    });
  },
  bindContentInput(e) {
    let content = e.detail.value;
    let worksheetinfo = this.data.worksheetinfo;
    worksheetinfo.content = content;
    this.setData({
      worksheetinfo
    });
  },
  bindWorkSheetSubmit(e) {
    let worksheetinfo = this.data.worksheetinfo;
    worksheetinfo.operatorName = this.data.userNames.length>0?this.data.userNames[0]:"";
    worksheetinfo.pams = this.data.accendantids;
    worksheetinfo.accendant = null;
    console.log(this.data.workstatusindex);
    console.log("工单状态");
    // if (this.data.exceptdate && this.data.excepttime) {
    //   worksheetinfo.exceptTime = this.data.exceptdate + " " + this.data.excepttime + ":00";
    // }
    worksheetinfo.exceptTime = this.data.exceptparams.pText + ":00";
    // if (this.data.finishdate && this.data.finishtime){
    //   worksheetinfo.finishTime = this.data.finishdate + " " + this.data.finishtime + ":00";
    // }
    worksheetinfo.finishTime = this.data.finishparams.pText=='0000-00-00 00:00'?null:this.data.finishparams.pText + ":00";

    worksheetinfo.workEndtime = this.data.workEndtimeParams.pText == '0000-00-00 00:00'? null : this.data.workEndtimeParams.pText + ":00";

    let images = this.data.images;
    var imgString = [];
    
    var pciString = [];
    this.data.pcitures.forEach((item, index) =>{
      pciString.push(item.src);
    });
    if(worksheetinfo.mainLocation == '' || worksheetinfo.mainLocation == undefined){
      wx.showModal({
        showCancel: false,
        content: '地址不能为空，请填写！',
        confirmColor:'#00AADD',
      });
      return;
    }
    if(worksheetinfo.pams.length == 0){
      wx.showModal({
        showCancel: false,
        content: '运维人员不能为空，请填写！',
        confirmColor:'#00AADD',
      });
      return;
    }
    if(worksheetinfo.content == '' || worksheetinfo.content == undefined){
      wx.showModal({
        showCancel: false,
        content: '工作内容不能为空，请填写！',
        confirmColor:'#00AADD',
      });
      return;
    }
    if( this.data.finishparams.pText=='0000-00-00 00:00'&& this.data.workstatusindex == 6){
      wx.showModal({
        showCancel: false,
        content: '请填写实际完成时间！',
        confirmColor:'#00AADD',
      });
      return;
    }
    let signs = this.data.signs;
    console.log(signs.length == 0);
    var signString = [];
    if (signs.length == 0) {
      //2021-1-1撤销校验
      // wx.showToast({
      //   title: '请设置签名',
      //   icon: 'loading',
      //   duration: 2000,
      //   mask: true,
      //   success: function() {}
      // });
      // return;
    } else {
      console.info('上传签名')
      signs.forEach((item, index) => {
        wx.uploadFile({
          url: getApp().globalData.postHeadAgreement + '/restapi/wechat/editWorkSheetImg',
          filePath: signs[index],
          name: 'imageFileName',
          success: function(res) {
            let result = JSON.parse(res.data);
            if (result.code == 500) {
              wx.showModal({
                showCancel: false,
                content: result.msg,
                confirmColor:'#00AADD',
              });
            } else {
              signString.push(result.msg);
              console.log(signString);
            }
          }
        });
      });
    }
    var uploadSignOverFlag = setInterval(function() {
      if (signString.length == signs.length) {
        clearInterval(uploadSignOverFlag);
        if (images.length == 0) {
          if (worksheetinfo.pciture) {
            console.log(worksheetinfo.pciture);
            worksheetinfo.pciture = (pciString.concat(imgString).concat(signString)).join(",");
            //worksheetinfo.pciture = ((worksheetinfo.pciture.split(",")).concat(signString)).join(",");
            console.log(worksheetinfo.pciture);
          }
          wx.request({
            url: getApp().globalData.postHeadAgreement + '/restapi/wechat/editWorkSheet',
            data: worksheetinfo,
            method: 'POST',
            success(res) {
              //console.log(res);
              if (res.data.code == 500) {
                wx.showModal({
                  showCancel: false,
                  content: res.data.msg,
                  confirmColor:'#00AADD',
                });
              } else {
                wx.navigateBack();
              }
            }
          });
        } else {

          images.forEach((item, index) => {
            wx.uploadFile({
              url: getApp().globalData.postHeadAgreement + '/restapi/wechat/editWorkSheetImg',
              filePath: images[index],
              name: 'imageFileName',
              success: function(res) {
                let result = JSON.parse(res.data);
                if (result.code == 500) {
                  wx.showModal({
                    showCancel: false,
                    content: result.msg,
                    confirmColor:'#00AADD',
                  });
                } else {
                  imgString.push(result.msg);
                  console.log(imgString);
                  if (index == (images.length - 1)) {
                    var uploadImgOverFlag = setInterval(function() {
                      if (imgString.length == images.length) {
                        clearInterval(uploadImgOverFlag);
                        //worksheetinfo.pciture = ((worksheetinfo.pciture.split(",")).concat(signString)).join(",");
                        worksheetinfo.pciture = (pciString.concat(imgString).concat(signString)).join(",");
                        //var images = this.data.images.concat(res.tempFilePaths);
                        wx.request({
                          url: getApp().globalData.postHeadAgreement + '/restapi/wechat/editWorkSheet',
                          data: worksheetinfo,
                          method: 'POST',
                          success(res) {
                            //console.log(res);
                            if (res.data.code == 500) {
                              wx.showModal({
                                showCancel: false,
                                content: res.data.msg,
                                confirmColor:'#00AADD',
                              });
                            } else {
                              wx.navigateBack();
                            }
                          }
                        });
                      }
                    }, 100);
                  }
                }
              },
              fail: function(data) {
                console.log(data);
              }
            });
          });
        }
      }

    }, 100);


  },
  openImage(e) {
    //var that = this;
    var imgCount = (9 - this.data.pcitures.length) < 0 ? 0 : 9 - this.data.pcitures.length;
    console.log(imgCount);
    wx.chooseImage({
      count: 9 - (this.data.pcitures.length + this.data.images.length),
      //sizeType: ['original', 'compressed'],  //可选择原图或压缩后的图片
      //sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        //console.log(res);
        var images = this.data.images.concat(res.tempFilePaths);
        // 限制最多只能留下5张照片
        images = images.length <= imgCount ? images : images.slice(0, imgCount);
        if (images.length >= imgCount || imgCount<= 0){
          wx.showToast({
            title: '最多9张图片',
            icon:'none'
          });
        }
        this.setData({
          //pcitures: [],
          images
        });
      }
    });
  },
  removeImage(e) {
    //console.log(e);
    //console.log(this.data.images);
    let idx = e.currentTarget.dataset.idx;
    var images = this.data.images;
    images.splice(idx, 1);
    this.setData({
      images
    });
  },
  removePciture(e) {
    //console.log(e);
    //console.log(this.data.images);
    
    let idx = e.currentTarget.dataset.idx;
    var pcitures = this.data.pcitures;
    pcitures.splice(idx, 1);
    this.setData({
      pcitures
    });
  },
  removeSign(e) {
    //console.log(e);
    //console.log(this.data.images);
    let idx = e.currentTarget.dataset.idx;
    var signs = this.data.signs;
    signs.splice(idx, 1);
    this.setData({
      signs
    });
  },
  handlePcituresPreview(e) {

    console.info("ddddddddddd")
    const idx = e.target.dataset.idx
    const pcitures = this.data.pcitures.map(it=>it.url)
    console.info(this.data.pcitures)
    wx.previewImage({
      current: pcitures[idx], //当前预览的图片
      urls: pcitures, //所有要预览的图片
    })
  },
  handleImagePreview(e) {

    const idx = e.target.dataset.idx
    const images = this.data.images
    console.info(this.data.images)
    wx.previewImage({
      current: images[idx], //当前预览的图片
      urls: images, //所有要预览的图片
    })
  },
  handleSignPreview(e) {
    const idx = e.target.dataset.idx
    const signs = this.data.signs
    //console.log(idx);
    //console.log(signs);
    //console.log(signs[idx]);
    wx.previewImage({
      current: signs[idx], //当前预览的图片
      urls: signs, //所有要预览的图片
    })
  },

  clear_chargStationName(e){
    let worksheetinfo = this.data.worksheetinfo;
    worksheetinfo.chargStationId = null;
    worksheetinfo.pams = [];
    worksheetinfo.accendant =  '';
    worksheetinfo.mainLocation =  '';
    this.setData({
      worksheetinfo,
      chargStationNameClearFlag: true
    });
  },
  bindworkEndtimeParamsChange(e){
    let workEndtimeParams =  this.data.workEndtimeParams;
    workEndtimeParams.pText = e.detail
    this.setData({
      workEndtimeParams:workEndtimeParams
    })
    console.info("workEndtimeParams " + workEndtimeParams.pText)
  },

  bindFinishparamsChange(e){
    let finishparams =  this.data.finishparams;
    finishparams.pText = e.detail
    this.setData({
      finishparams:finishparams
    })
    console.info("finishparams " + finishparams.pText)
  },

  bindExceptparamsChange(e){
    let exceptparams =  this.data.exceptparams;
    exceptparams.pText = e.detail
    this.setData({
      exceptparams:exceptparams
    })
    console.info("exceptparams " + exceptparams.pText)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    //console.log(options);
    let {
      worksheet
    } = options;
    //console.log(worksheet);
    let worksheetinfo = JSON.parse(worksheet);



    
    //worksheetinfo.breakdownType = 2;
    this.setData({
      worksheetinfo,
      brandName:worksheetinfo.brandName
    });
    this.data.workstatus.forEach((item, index) => {
      if (item.value == worksheetinfo.workStatus) {
        this.setData({
          workstatusindex: index
        });
      }
    });
    this.data.workBigclass.forEach((item, index) => {
      if (item.value == worksheetinfo.workBigclass) {
        this.setData({
          workBigclassindex: index
        });
      }
    });
    this.data.wokSmallclass.forEach((item, index) => {
      if (item.value == worksheetinfo.wokSmallclass) {
        this.setData({
          wokSmallclassindex: index
        });
      }
    });
    if (worksheetinfo.exceptTime) {
      // let datetime = worksheetinfo.exceptTime.split(" ");
      // this.setData({
      //   exceptdate: datetime[0],
      //   excepttime: datetime[1].substr(0, 5)
      // });
      let exceptparams = this.data.exceptparams;
      exceptparams['pText'] = worksheetinfo.exceptTime.substr(0,16)
      this.setData({
        exceptparams: exceptparams
      });
    }
    if (worksheetinfo.workEndtime) {
      let workEndtimeParams = this.data.workEndtimeParams;
      workEndtimeParams['pText'] = worksheetinfo.workEndtime.substr(0,16)
      this.setData({
        workEndtimeParams: workEndtimeParams
      });
    }else{
      let workEndtimeParams = this.data.workEndtimeParams;
      workEndtimeParams['pText'] = '0000-00-00 00:00'
      this.setData({
        workEndtimeParams: workEndtimeParams
      });
    }


    if (worksheetinfo.finishTime) {
      // let datetime = worksheetinfo.finishTime.split(" ");
      // this.setData({
      //   finishdate: datetime[0],
      //   finishtime: datetime[1].substr(0, 5)
      // });
      let finishparams = this.data.finishparams;
      finishparams['pText'] = worksheetinfo.finishTime.substr(0,16)
      this.setData({
        finishparams: finishparams
      });
    }else{
      let finishparams = this.data.finishparams;
      finishparams['pText'] = Util.formatTimePicker(new Date())
      this.setData({
        finishparams: finishparams
      });
    }



    this.data.breakdownType.forEach((item, index) => {
      if (item.value == worksheetinfo.breakdownType) {
        this.setData({
          breakdownTypeindex: index
        });
      }
    });
    

    if (worksheetinfo.pciture) {
      let pcitures_src = worksheetinfo.pciture.split(",");
      var pcitures = [];
      pcitures_src.forEach((item, index) => {
        // pcitures[index] = { src: item, flag: item.indexOf('https://cdgl.pjnes.com/profile/station/') != -1};
        let url = getApp().globalData.postHeadAgreement
        url = url.replace("cloud/chargapi","") + "web/profile/station/" + item
        console.info(url)
        pcitures[index] = { url:url, src: item, flag: item.indexOf(getApp().globalData.postHeadAgreement) != -1};
      });
      this.setData({
        pcitures
      });
    }
    //console.log(worksheetinfo);

    if(worksheetinfo.workStatus==7){
      this.setData({
        workstatusFinished: true
      })
    }

    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    let that = this;
    //console.log(12345);


    if (userInfo && isLogin) {
      that.setData({
        chargStationName:worksheetinfo.chargStationName,
        worksheetinfo 
      });

      if(!worksheetinfo.chargStationName){
        that.setData({
          chargStationNameClearFlag:true,
        });
      }
    }
    wx.request({
      url: getApp().globalData.postHeadAgreement + '/restapi/wechat/getuserworksheet',
      data: worksheetinfo.id,
      method: 'POST',
      success(res) {
        //console.log(res);
        let accendantids = [];
        let userNames = [];
        res.data.forEach((item, index) => {
          accendantids.push(item.userId);
          userNames.push(item.userName);
        });
        that.setData({
          accendantids,
          userNames
        });
      }
    });
  },
  openSign(e) {
    let url = `/pages/sign/sign`;
    wx.navigateTo({
      url
    });

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // console.log("data",this.data);
    this.setData({
      brandName: this.data.brandName
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  }
})