const {
  API_BASE_URL,
  IMG_BASE_URL,
  entryDetail,  
  getAllConditionList,
  acceptItems,saveAcceptItem
} = require('../../../api/api')
Page({
  data: {
    API_BASE_URL: API_BASE_URL,
    IMG_BASE_URL: IMG_BASE_URL,
    itemList: [],
    tabIndex: 1,    
    detail:{},//详情信息 
    formSetObj: {},
    rightCount: 0,
    wrongCount: 0
  },
  onLoad(options) {
    this.setData({
      id: options.id,
      entryId:options.entryId,
    });   
    this.initData();
  },
  onShow() {

  },
  //切换TAB
  changeTab(e){    
    let type = e.currentTarget.dataset.index
    this.setData({
      tabIndex: type
    })
  },
  //验收结果-单选
  radioChange(e) {
    let index = e.currentTarget.dataset.index;
    let pindex = e.currentTarget.dataset.pindex;
    let rightCount = 0
    let wrongCount = 0
    this.setData({
      [`listData[${pindex}].items[${index}].columns.result`]: e.detail.value
    })
    let listData = JSON.parse(JSON.stringify(this.data.listData));
    setTimeout(()=>{
      listData.forEach(item=>{
        item.items.forEach(item2=>{
          if(item2.columns.type != '4'){//有选择项的才做统计
            if(item2.columns.result == '0'){//合格数量
              rightCount = rightCount+1
            }else if(item2.columns.result == '1'){//整改数量
              wrongCount = wrongCount+1
            }
          }
        })
      })
      this.setData({
        wrongCount,
        rightCount
      })
    },50)    
  },
  //文本输入
  descFun(e) {
    let name = e.currentTarget.dataset.name;
    let index = e.currentTarget.dataset.index;
    let pindex = e.currentTarget.dataset.pindex;
    let value = e.detail.value;
    if(name =='result_desc'){
      // value = value.replace(/^(\-)*(\d+)\.(\d{2}).*$/, '$1$2.$3');
      // this.setData({
      //   [`listData[${pindex}].items[${index}].columns.${name}`]: value
      // })
    }else if(name =='special_desc'){// 只能输入大于0的整数
      // this.setData({
      //   [`listData[${pindex}].items[${index}].columns.${name}`]: value
      // })
      // if (value<1) {
      //   this.setData({
      //     [`listData[${pindex}].items[${index}].columns.${name}`]: 1
      //   })
      // }
    }else{
      this.setData({
        [`listData[${pindex}].items[${index}].columns.${name}`]: e.detail.value
      })
    }    
    // console.log(1212, pindex, index, this.data.listData)
  },
  descBlurFun(e){
    let name = e.currentTarget.dataset.name; 
    let index = e.currentTarget.dataset.index;
    let pindex = e.currentTarget.dataset.pindex;
    let value = e.detail.value;
    if(name =='special_desc'){// 只能输入大于0的整数
      if(value<1){
        value = 1
      }else if(!/^[1-9]\d*$/.test(value)) {
        value = this.data.listData[pindex].items[index].columns.special_desc?this.data.listData[pindex].items[index].columns.special_desc: 1; // 重置为上次的值
      }
      this.setData({
        [`listData[${pindex}].items[${index}].columns.${name}`]: value
      })
    }
  },
  // 将输入值的小数点替换为一个字符，确保只有2位小数    
  descBlurflex2(e){
    let name = e.currentTarget.dataset.name; 
    let index = e.currentTarget.dataset.index;
    let pindex = e.currentTarget.dataset.pindex;
    let value = e.detail.value;
    if(name =='special_desc'){// 只能输入大于0的整数
      value = value.replace(/^(\-)*(\d+)\.(\d{2}).*$/, '$1$2.$3');
      this.setData({
        [`listData[${pindex}].items[${index}].columns.${name}`]: value
      })
    }
  },

  /** 数据 **/
  initData(){
    wx.showLoading({
      title: "加载中"
    });    
    //电站详情
    entryDetail({
      userId: wx.getStorageSync('userId'),
      entryId: this.data.entryId
    }).then(res=>{ 
      this.setData({
        detail: res,
      })
      this.getFormSet(res.management)
    });
    //获取字段
    acceptItems({
      detailId: this.data.id
    }).then(res=>{ 
      if(res.code == 200){
        let list = res.data.itemList.map(item=>item.columns);
        let rightCount = 0;
        let wrongCount = 0;
        list.forEach(item=>{
          item.items.forEach(item2=>{
            item2.columns.result = item2.columns.result?item2.columns.result:'0' //默认都选中
            item2.columns.imgPath = item2.columns.img_path ? item2.columns.img_path.split(",").map(itm => { return { name: itm, url: IMG_BASE_URL + itm}}) : []
            if(item2.columns.type != '4'){//有选择项的才做统计
              if(item2.columns.result == '0'){//合格数量
                rightCount = rightCount+1
              }else if(item2.columns.result == '1'){//整改数量
                wrongCount = wrongCount+1
              }
            }
          })
        })
        this.setData({
          listData: list,
          wrongCount,
          rightCount
          // rightCount: res.data.countRecord.columns.rightCount,
          // wrongCount: res.data.countRecord.columns.wrongCount
        })
      }
      wx.hideLoading();
    });
  },
  /** 获取自定义字段 */
  getFormSet(partner) {
    //01:信息登记,02：踏勘设计,03：电站安装,04：电站并网,05 档案
    getAllConditionList({
      partner: partner,
    }).then((res) => {
      this.setData({
        formSetObj: res.data
      })
    })
  }, 
  /** 上传图片 **/
  afteruploadPhotoRead(e) {
    var that = this;
    const choseType = Array.isArray(e.detail.file) ? (e.detail.file[0].choseType || undefined) : (e.detail.file.choseType || undefined); //camera相机  album相册
    const index = e.currentTarget.dataset.index
    const pindex = e.currentTarget.dataset.pindex
    console.log("上传后", this.data.listData, choseType, e);   
    if (Array.isArray(e.detail.file)) { //多张
      var count = 0;
      this.afteruploadPhotoReadS(e, count)
      return
    }
    const {
      file
    } = e.detail;
    wx.showLoading({
      title: '上传中',
    })
    wx.uploadFile({
      url: that.data.API_BASE_URL + 'common/weChat/uploadImage',
      filePath: file.url,
      name: 'file',
      complete: function (res) {
        console.log("上传图片", res)
        wx.hideLoading()
        if (res.statusCode == 200) {
          wx.showToast({
            title: '选择成功',
            icon: 'none',
          })
          var item = {
            url: "",
            name: "",
          }
          item.url = file.url;
          item.name = res.data;
          that.data.listData[pindex].items[index].columns.imgPath.push(item)
          that.setData({
            [`listData[${pindex}].items[${index}].columns.imgPath`]: that.data.listData[pindex].items[index].columns.imgPath
          })
        } else {
          wx.showToast({
            title: '选择失败',
            icon: 'error'
          })
        }
      }
    })
  },
  /** 上传多张图片递归 **/
  afteruploadPhotoReadS(e, count) {
    let ob = {
      name: '',
      url: '',
    }
    const index = e.currentTarget.dataset.index
    const pindex = e.currentTarget.dataset.pindex
    wx.showLoading({
      title: '加载第' + (count + 1) + '张照片中',
      mask: true,
    })
    const element = e.detail.file[count];
    var that = this;
    wx.uploadFile({
      url: that.data.API_BASE_URL + 'common/weChat/uploadImage',
      filePath: element.url,
      name: 'file',
      success(res) {
        wx.hideLoading()
        if (res.statusCode == 200) {
          count = count + 1;
          ob.name = res.data
          ob.url = element.url 
          that.data.listData[pindex].items[index].columns.imgPath.push(ob)
          that.setData({
            [`listData[${pindex}].items[${index}].columns.imgPath`]: that.data.listData[pindex].items[index].columns.imgPath
          })
          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 cindex = e.currentTarget.dataset.index
    const pindex = e.currentTarget.dataset.pindex
    const index = e.detail.index //删除图片的下标
    this.data.listData[pindex].items[cindex].columns.imgPath.splice(index, 1);
    this.setData({
      [`listData[${pindex}].items[${cindex}].columns.imgPath`]: this.data.listData[pindex].items[cindex].columns.imgPath
    })
  },  
  //打开pdf文件或者大图查看图片
  openDocument(res) {
    let path = res.currentTarget.dataset.path
    if (path) {
      let suffix = path.substring(path.lastIndexOf('.') + 1) //获取文件后缀
      if (suffix == 'pdf') {
        wx.showLoading({
          title: '加载中',
        })
        wx.downloadFile({
          url: IMG_BASE_URL + path,
          complete: function (res) {
            wx.hideLoading()
            const filePath = res.tempFilePath
            wx.openDocument({
              filePath: filePath,
              showMenu: true,
              success: function (res) {}
            })
          }
        })
      } else {
        wx.previewImage({
          urls: [IMG_BASE_URL + path] // 需要预览的图片http链接列表
        })
      }
    }
  },
  //提交
  submitFrom(e){
    let type = e.currentTarget.dataset.type;
    let listData = JSON.parse(JSON.stringify(this.data.listData));
    let itemList = []
    let isCheck = true
    try{
      listData.forEach(item=>{
        item.items.forEach(item2=>{
          if(item2.columns.name != '其他' && item2.columns.name != '各路电压正常' && type == '1'){//提交时，除了标题是其他和各路电压正常，任意验收结果，验收图片都是必传
            if(item2.columns.imgPath.length == 0){
              wx.showModal({
                title: '',
                content: item2.columns.name + ',验收照片不能为空',
                showCancel: false,
                complete: (res) => {
                  if (res.confirm) {}
                }
              })
              isCheck = false
              throw Error()
            }else if(item2.columns.result == '1' && item2.columns.test_remarks == ''){
              wx.showModal({
                title: '',
                content: item2.columns.name + ',验收说明不能为空',
                showCancel: false,
                complete: (res) => {
                  if (res.cancel) {}            
                  if (res.confirm) {}
                }
              })
              isCheck = false
              throw Error()
            }
          }else if(item2.columns.name == '各路电压正常' && item2.columns.result == '1' && type == '1'){//提交时，各路电压正常验收结果不正常的情况下验收图片必传
            if(item2.columns.imgPath.length == 0){
              wx.showModal({
                title: '',
                content: item2.columns.name + ',验收照片不能为空',
                showCancel: false,
                complete: (res) => {
                  if (res.cancel) {}            
                  if (res.confirm) {}
                }
              })
              isCheck = false
              throw Error()
            }
          }
          let resultDesc = ''
          if(item2.columns.result=='0' && item2.columns.type<4){
            resultDesc = item2.columns.result_right
          }else if(item2.columns.result=='1'&& item2.columns.type<4){
            resultDesc = item2.columns.result_wrong
          }else{
            resultDesc = item2.columns.result_desc
          }
          itemList.push({
            groupName: item.name,
            itemName: item2.columns.name,
            resultDesc: resultDesc,
            result: item2.columns.result,
            specialDesc: item2.columns.special_desc,
            imgPath: item2.columns.imgPath.length>0?item2.columns.imgPath.map(itm => itm.name).join(",") : "",          
            testRemarks: item2.columns.test_remarks,
            sort: item2.columns.sort,
          })
        })
      })
    }catch(e) {
      console.log(e)
    }
    if(!isCheck){
      return
    }
    console.log(666, itemList, isCheck)
    // return
    wx.showLoading({
      title: "提交中",
      mask: true
    });
    saveAcceptItem({
      detailId: this.data.id,
      saveResult: type,//0 暂存 1提交
      items: itemList
    }).then(res=>{ 
      if(res.code == 200){
        wx.showToast({
          title: '操作成功',
        })
        setTimeout(()=>{
          wx.navigateBack()
        },1500)
      }else{
        wx.showModal({
          title: '',
          content: res.errMsg,
          showCancel: false,
          complete: (res) => {
            if (res.confirm) {}
          }
        })
      }
      setTimeout(()=>{
        wx.hideLoading();
      },1500)
    });
  }
})