const {
  API_BASE_URL,
  IMG_BASE_URL,
  entryDetail,
  qualityRectificationDetail,
  saveChangingQuality,
  saveAcceptQuality
} = require('../../../api/api')
Page({
  data: {
    tabIndex: 1,
    projectId:'',//电站id
    entryId:'',//整改id
    detail:{},//详情信息
    detailData:{},
    changeAcceptRemarks:'',//验收意见
  },
  //一级切换TAB
  changeTab(e){    
    let type = e.currentTarget.dataset.index
    this.setData({
      tabIndex: type
    })
  },
  /** 数据 **/
  initData(){
    wx.showLoading({
      title: "加载中"
    });
    entryDetail({
      userId: wx.getStorageSync('userId'),
      entryId: this.data.projectId
    }).then(res=>{ 
      this.setData({
        detail: res,
      })  
    });
    qualityRectificationDetail({
      id:this.data.entryId
    }).then(res=>{
      res.data.resultWrong.forEach(item=>{
        item.items.forEach(itm=>{
          itm.columns.img_path = itm.columns.img_path ? itm.columns.img_path.split(",").map(it=>{return {url:IMG_BASE_URL + it}}) : [];
          itm.columns.change_img = itm.columns.change_img ? itm.columns.change_img.split(",").map(it=>{return {url:IMG_BASE_URL + it}}) : [];
        });
      });
      res.data.resultRight.forEach(item=>{
        item.items.forEach(itm=>{
          itm.columns.img_path = itm.columns.img_path ? itm.columns.img_path.split(",").map(it=>{return {url:IMG_BASE_URL + it}}) : [];
          itm.columns.change_img = itm.columns.change_img ? itm.columns.change_img.split(",").map(it=>{return {url:IMG_BASE_URL + it}}) : [];
        });
      });
      this.setData({
        detailData:res.data
      });
      wx.hideLoading();
    });
  },
  onLoad(options) {
    if(options.title == '查看'){
      this.setData({
        tabIndex: 2
      })
    }
    this.setData({
      entryId:options.entryId,
      projectId:options.projectId,
      userType: wx.getStorageSync('userType'),
    });
    if((options.title && options.title == '详情') || options.title == '查看'){
      this.setData({
        title:options.title,
      });
      wx.setNavigationBarTitle({
        title: options.title,
      })
    }
    this.initData();
  },
  /** 上传图片 **/
  afteruploadPhotoRead(e) {
    this.afteruploadPhotoReadS(e, 0)
  },
  /** 上传多张图片递归 **/
  afteruploadPhotoReadS(e, count) {
    const index = e.currentTarget.dataset.index
    const childIndex = e.currentTarget.dataset.childindex
    wx.showLoading({
      title: '加载第' + (count + 1) + '张照片中',
      mask: true,
    })
    const element = e.detail.file[count];
    var that = this;
    wx.uploadFile({
      url: API_BASE_URL + 'common/weChat/uploadImage',
      filePath: element.url,
      name: 'file',
      success(res) {
        wx.hideLoading()
        if (res.statusCode == 200) {
          count = count + 1;
          let ob = {
            url: IMG_BASE_URL + res.data,
          }
          let change_img = that.data.detailData.resultWrong[index].items[childIndex].columns.change_img;
          change_img.push(ob)
          that.setData({
            [`detailData.resultWrong[${index}].items[${childIndex}].columns.change_img`]: change_img
          })
          if (count == e.detail.file.length) {
            wx.showToast({
              title: '选择成功',
              icon: 'none'
            })
          } else {
            that.afteruploadPhotoReadS(e, count)
          }
        } else {
          wx.showToast({
            title: '选择失败',
            icon: 'error'
          })
        }
      }
    })
  },
  /** 删除图片 **/
  deleteImg(e) {
    const index = e.currentTarget.dataset.index
    const childIndex = e.currentTarget.dataset.childindex
    const idx = e.detail.index;
    let change_img = this.data.detailData.resultWrong[index].items[childIndex].columns.change_img;
    change_img.splice(idx, 1);
    this.setData({
      [`detailData.resultWrong[${index}].items[${childIndex}].columns.change_img`]:change_img
    })
  },
  /** 整改描述 **/
  descFn(e){
    const index = e.currentTarget.dataset.index
    const childIndex = e.currentTarget.dataset.childindex
    this.setData({
      [`detailData.resultWrong[${index}].items[${childIndex}].columns.change_desc`]:e.detail.value
    })
  },
  /** 暂存/提交 **/
  submitFrom(e){
    let changeStatus = e.currentTarget.dataset.type;//3.提交 2.暂存
    let resultWrong = JSON.parse(JSON.stringify(this.data.detailData.resultWrong)), isMust = true, arr=[];
    try{
      resultWrong.map(item=>{
        item.items.map(itm=>{
          if(!itm.columns.change_img.length && changeStatus == '3'){
            // console.log()
            // isMust = false
            wx.showModal({
              title: '',
              content: itm.columns.item_name + ',整改照片不能为空',
              showCancel: false,
              complete: (res) => {
                if (res.confirm) {}
              }
            })
            isMust = false
            throw Error()
          }
          arr.push({
            id:itm.columns.id,
            changeImg:itm.columns.change_img.map(it=>it.url.replace(IMG_BASE_URL,'')).join(","),
            remark:itm.columns.change_desc
          });
        });
      });
    }catch(e) {
      console.log(e)
    }
    if(!isMust && changeStatus == '3'){
      // wx.showToast({
      //   // title: '请完善整改必填信息！',
      //   title: '整改图片不能为空！',
      //   icon: 'none'
      // })
      return
    }
    let fromData = {
      detailId:this.data.detailData.detailId,
      changeStatus:changeStatus,
      list:arr,
    }
    // console.log("提交",fromData);
    // return
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    saveChangingQuality(fromData).then(res=>{
      wx.hideLoading()
      if (res.code == 200) {
        wx.showToast({
          title: "操作成功",
          icon: 'none',
          success: function () {
            setTimeout(function () {
              wx.navigateBack()
            }, 1000)
          }
        })
      }
      else {
        wx.showToast({
          title: res.errMsg,
          icon: 'none'
        })
      }
    });
  },
  /** 驳回/验收 **/
  acceptFrom(e){
    let changeStatus = e.currentTarget.dataset.type;//4驳回 5 通过
    if(changeStatus == '4' && !this.data.changeAcceptRemarks){
      wx.showToast({
        title: '验收意见必填！',
        icon: 'none'
      })
      return
    }
    let fromData = {
      id:this.data.entryId,
      changeStatus:changeStatus,
      changeAcceptRemarks:this.data.changeAcceptRemarks,
    }
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    saveAcceptQuality(fromData).then(res=>{
      wx.hideLoading()
      if (res.code == 200) {
        wx.showToast({
          title: "操作成功",
          icon: 'none',
          success: function () {
            setTimeout(function () {
              wx.navigateBack()
            }, 1000)
          }
        })
      }
      else {
        wx.showToast({
          title: res.errMsg,
          icon: 'none'
        })
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})