const {
  API_BASE_URL,
  IMG_BASE_URL,
  entryDetail,
  getProviceCodeList,
  accept,getFormSet,addUserInfo,mergeTmp
} = require('../../../api/api')
import Dialog from '@vant/weapp/dialog/dialog';
const SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g
const camelCase = function (name) {
  // - 是 match，separator 是 p1，letter 是 p2
  return name.replace(SPECIAL_CHARS_REGEXP, function (_, separator, letter, offset) {
    return offset ? letter.toUpperCase() : letter
  })
}
function dateStr (date){
  let year = date.slice(0,4);
  let month = date.slice(4,6);
  let day = date.slice(6);
  return year+'/'+month+'/'+day;
}
Page({
  data: {
    projectId:'',//电站id
    detail:{},//详情信息
    params:{
      bwInstitution: '0', //0是国网，1是南网
      powerPlantCode: '', //电厂编码
      addressConsistent: 'Y', // 购售电地址是否一致 Y:是、N:否
      province: "", //省
      city: "", //市
      area: "", //区
      address: "", //详细地址
      generatorNo:'',//发电户号
      powerCompanyName:'',//国网电力公司名称
      provinceCodeHand:'',//南网电力公司名称
      provinceCode:'',//电力公司编码
      yxImg:[],//电站运行信息照片
      gebImg:[],//补充照片
      gebImg2: [],//补充照片2
      dbImgs: [],//电表图片
      dbxImgs: [],//电表箱图片
      tlzhjkImgs: [], //铜铝转换接头照片
      powerCapacityUrl: [], //3日发电量
      archivesImg: [], //三户档案截图
      contractFile: [],//购售电合同
      contractVideoUrl: [], //购售电合同视频
      otherAttachment: [],//资方审查补充资料
      "insurance": {
        // "id": '',//保险单id
        // "entryId": '',//电站id
        "insuranceTypeName":'财产险',
        "insuranceType": "1",//目前只支持财产险
        // "insuranceDateFrom": '',//保险开始日期
        // "insuranceDateTo": '',//保险结束日期
        // "insuranceCompany": '',//保险公司
        // "insuranceNumber": '',//保险编号
        // "insuranceAmount": '',//保险金额
        // "firstBeneficiary": '',//第一受益人
        // "insurancePolicy": '',//保险单
        "bwtsFile":'',//并网调试报告
      },//保险
    },//提交参数
    showRegion:false,//省市区对话框
    powerCompanyList:[],//电力公司列表
    insuranceTypeList:[{
      name:'财产险',
      value:'1'
    }],//保险类型列表
    dateShow:false,//日期区间对话框
    formSetObj: {},//自定义字段
  },
  async onLoad(options) {
    this.setData({
      projectId:options.projectId
    });
    await this.getProviceCodeList();
    this.initData();
  },
  onReady() {

  },
  onShow() {

  },
  /** 获取自定义字段 */
  getFormSet(partner) {
    getFormSet({
      stage: '04', //01:信息登记,02：踏勘设计,03：电站安装,04：电站并网
      partner: partner,
    }).then((res) => {
      this.setData({
        formSetObj: res.data.columns
      })
    })
  },
  /** 数据 **/
  initData(){
    wx.showLoading({
      title: "加载中"
    });
    entryDetail({
      userId: wx.getStorageSync('userId'),
      entryId: this.data.projectId
    }).then(res=>{
      let obj = {};
      for(let i in res){
        let j = camelCase(i);
        obj[j]=res[i];
      }
      if(res.insurance){
        for(let i in res.insurance){
          let j = camelCase(i);
          obj.insurance[j]=res.insurance[i];
        }
      }
      // console.log("执行",obj);
      wx.hideLoading();
      for(let i in this.data.params){
        if(obj[i]){
          if(i=='insurance'){
            continue;
          }
          if(obj.addressConsistent=='Y'&&(i=='province'||i=='city'||i=='area'||i=='address')){
            this.data.params[i]='';
            continue;
          }
          this.data.params[i]=obj[i];
        }
      }
      for(let i in this.data.params.insurance){
        if(obj.insurance&&obj.insurance[i]){
          this.data.params.insurance[i]=obj.insurance[i];
        }
      }
      if(this.data.powerCompanyList.find(itm=>itm.code==this.data.params.provinceCode)){
        this.data.params.powerCompanyName=this.data.powerCompanyList.find(itm=>itm.code==this.data.params.provinceCode).power_company;
      }      
      if(this.data.params.insurance){
        // this.data.params.insurance.insuranceTypeName=this.data.insuranceTypeList.find(itm=>itm.value==this.data.params.insurance.insuranceType).name;
        // this.data.params.insurance.insuranceDateFrom=dateStr(this.data.params.insurance.insuranceDateFrom);
        // this.data.params.insurance.insuranceDateTo=dateStr(this.data.params.insurance.insuranceDateTo);
      }
      if (res.report) {
        if (res.report.gebImg) {
          this.setData({
            [`params.gebImg[0].name`]: res.report.gebImg,
            [`params.gebImg[0].url`]: IMG_BASE_URL + res.report.gebImg,
          })
        }
        if (res.report.gebImg2) {
          this.setData({
            [`params.gebImg2[0].name`]: res.report.gebImg2,
            [`params.gebImg2[0].url`]: IMG_BASE_URL + res.report.gebImg2,
          })
        }
        if (res.report.dbImgs) {
          this.setData({
            [`params.dbImgs[0].name`]: res.report.dbImgs,
            [`params.dbImgs[0].url`]: IMG_BASE_URL + res.report.dbImgs,
          })
        }
        if (res.report.dbxImgs) {
          this.setData({
            [`params.dbxImgs[0].name`]: res.report.dbxImgs,
            [`params.dbxImgs[0].url`]: IMG_BASE_URL + res.report.dbxImgs,
          })
        }
        if (res.report.tlzhjkImgs) {
          this.setData({
            [`params.tlzhjkImgs[0].name`]: res.report.tlzhjkImgs,
            [`params.tlzhjkImgs[0].url`]: IMG_BASE_URL + res.report.tlzhjkImgs,
          })
        }
        if (res.report.archivesImg) {
          this.setData({
            [`params.archivesImg[0].name`]: res.report.archivesImg,
            [`params.archivesImg[0].url`]: IMG_BASE_URL + res.report.archivesImg,
          })
        }
        if (res.report.powerCapacityUrl) {
          this.setData({
            [`params.powerCapacityUrl[0].name`]: res.report.powerCapacityUrl,
            [`params.powerCapacityUrl[0].url`]: IMG_BASE_URL + res.report.powerCapacityUrl,
          })
        }
        if (res.report.yxImg) {
          this.setData({
            [`params.yxImg[0].name`]: res.report.yxImg,
            [`params.yxImg[0].url`]: IMG_BASE_URL + res.report.yxImg,
          })
        }        
      }
      if (res.contract) {//合同文件
        this.setData({
          [`params.contractFile`]:res.contract ? res.contract.split(",").map(itm=>{return {name:itm, url:IMG_BASE_URL + itm}}) : [{url:WU_TU_PIAN_URL}],
        })
      }
       if (res.other_attachment) {//补充资料
        this.setData({
          [`params.otherAttachment`]:res.other_attachment ? res.other_attachment.split(",").map(itm=>{return {name:itm, url:IMG_BASE_URL + itm}}) : [{url:WU_TU_PIAN_URL}],
        })
      }
      if (res.contract_video_url) {//合同视频
        this.setData({
          [`params.contractVideoUrl`]:res.contract_video_url ? res.contract_video_url.split(",").map(itm=>{return {name:itm, url:IMG_BASE_URL + itm}}) : [{url:WU_TU_PIAN_URL}],
        })
      }
      this.data.params.province = res.electric_province
      this.data.params.city = res.electric_city
      this.data.params.area = res.electric_area
      this.data.params.address = res.electric_address
      this.data.params.bwInstitution = res.grid_institution
      this.setData({
        detail:res,
        params:this.data.params,
        address:this.data.params.address,
        generatorNo:this.data.params.generatorNo,
        provinceCodeHand:this.data.params.provinceCodeHand,
        powerPlantCode:this.data.params.powerPlantCode,
        insuranceCompany:this.data.params.insurance.insuranceCompany,
        firstBeneficiary:this.data.params.insurance.firstBeneficiary,
        insuranceNumber:this.data.params.insurance.insuranceNumber,
        insuranceAmount:this.data.params.insurance.insuranceAmount,
      });
      this.getFormSet(res.management)
    });
  },
  /** 获取电力公司 **/
  getProviceCodeList(e) {
    getProviceCodeList({}).then((res) => {
      if (res.code == 200) {
        let list = res.data.map(itm=>itm.columns);
        this.setData({
          powerCompanyList: list
        })
      }
    })
  },
  /** 业主信息 **/
  userFn(e){
    wx.navigateTo({
      url: '/home/pages/ownerForm/ownerForm?projectId=' + this.data.projectId + '&type=16',
    })
  },
  /** 购售电地址是否一致 **/
  radioChangeAddress(e) {
    this.setData({
      [`params.addressConsistent`]: e.detail.value,
      [`params.province`]: '',
      [`params.city`]: '',
      [`params.area`]: '',
      [`params.address`]: ""
    })
  },
  /** 并网机构 **/
  radioChangeType(e) {
    this.setData({
      [`params.bwInstitution`]: e.detail.value,      
    })
  },
  /** 打开省市区弹框 **/
  bindRegionChange(e) {
    this.setData({
      showRegion: true
    })
  },
  /** 选择的地址 **/
  chooseRegion(e) {
    this.setData({
      [`params.province`]: e.detail.provinceName,
      [`params.city`]: e.detail.cityName,
      [`params.area`]: e.detail.areaName,
      [`params.address`]: ""
    });
  },
  /** 选择电力公司 **/
  bindpowerCompanyList(e) {
    this.setData({
      [`params.powerCompanyName`]: this.data.powerCompanyList[e.detail.value].power_company,
      [`params.provinceCode`]: this.data.powerCompanyList[e.detail.value].code
    })
  },
  /** 查看图片注意方案 **/
  viewNote(e) {
    let title = e.currentTarget.dataset.tit;
    let message = e.currentTarget.dataset.msg;
    Dialog.alert({
      title: title,
      message: message,
      theme: 'round-button',
    }).then(() => { });
  },
  /** 上传图片 **/
  afteruploadPhotoRead(e) {
    const {
      file
    } = e.detail;
    const img = file.url;
    wx.showLoading({
      title: '上传中',
    })
    var that = this
    wx.uploadFile({
      url: 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: "",
          }
          let type = e.currentTarget.dataset.type
          item.url = img;
          item.name = res.data;
          that.data.params[type].push(item)
          that.setData({
            [`params.${type}`]: that.data.params[type]
          })
        } else {
          wx.showToast({
            title: '选择失败',
            icon: 'error'
          })
        }
      }
    })
  },
  /** 删除图片 **/
  deleteImg(e) {
    // console.log("删除图片事件", e)
    let index= e.detail.index;
    let type = e.currentTarget.dataset.type
    this.data.params[type].splice(index, 1);
    this.setData({
      [`params.${type}`]: index > 0 ? this.data.params[type] : []
    });
  },
  /** 上传多张图片递归 **/
  afteruploadPhotoReadS(e, file, count, type) {
    let ob = {
      name: '',
      url: '',
    }
    const name = e.currentTarget.dataset.name
    wx.showLoading({
      title: '加载第' + (count + 1) + '张照片中',
      mask: true,
    })
    const element = file[count];
    var that = this;
    var url = ''
    if(type =='file'){
      //获取文件后缀
      let suffix = element.path.substring(element.path.lastIndexOf('.') + 1)
      if (suffix.search(/jpg|png|jpeg|pdf/) == -1) {
        wx.showToast({
          title: '只能上传jpg、png、jpeg、pdf文件',
          icon: 'none'
        })
        return
      }
      url = API_BASE_URL + 'common/uploadFile_Name?fileName='+ element.name
    }else{
      url = API_BASE_URL + 'common/weChat/uploadImage'
    }
    wx.uploadFile({
      url: url,
      filePath: type =='file'?element.path:element.tempFilePath,
      name: 'file',
      success(res) {
        wx.hideLoading()
        if (res.statusCode == 200) {
          console.log(989898988, res)
          count = count + 1;
          // ob.name = res.data
          ob.name = type =='file'?JSON.parse(res.data).path: res.data,
          ob.url = type =='file'?JSON.parse(res.data).path:element.tempFilePath
          that.data.params[name].push(ob);
          that.setData({
            [`params.${name}`]: that.data.params[name]
          })
          if (count == file.length) {
            wx.showToast({
              title: '选择成功',
              icon: 'none'
            })
          } else {
            that.afteruploadPhotoReadS(e, file, count, type)
          }
        } else {
          wx.showToast({
            title: '选择失败',
            icon: 'error'
          })
        }
      }
    })
  },
  /** 文件或图片上传选择-对话框 **/
  selectUplosd(e){
    var that = this;
    let name = e.currentTarget.dataset.name; 
    let maxCount = e.currentTarget.dataset.count;
    wx.showActionSheet({
      itemList: ['文件', '图片'],
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {//文件
            that.upload(e, name);
          } else if (res.tapIndex == 1) {//图片
            // console.log(6666666, maxCount)
            wx.chooseMedia({
              count: Math.min(maxCount, 9),
              mediaType: ['image','video'],
              sourceType: ['album'],
              success: function (rep) { 
                // console.log(98989, rep)
                if (Array.isArray(rep.tempFiles)) { //多张
                  var count = 0;
                  that.afteruploadPhotoReadS(e, rep.tempFiles, count)
                  return
                }
                wx.showLoading({
                  title: '选择中',
                })
                wx.uploadFile({
                  url: API_BASE_URL + 'common/weChat/uploadImage',
                  filePath: rep.tempFiles[0].tempFilePath,
                  name: 'file',
                  complete: function (res) {
                    wx.hideLoading()
                    if (res.statusCode == 200) {
                      wx.showToast({
                        title: '选择成功',
                        icon: 'none',
                      })
                      var item = {
                        url: "",
                        name: "",
                      }
                      item.url = rep.tempFiles[0].tempFilePath;
                      item.name = res.data;
                      that.data.params[name].push(item)
                      that.setData({
                        [`params.${name}`]: that.data.params[name]
                      })
                    } else {
                      wx.showToast({
                        title: '选择失败',
                        icon: 'error'
                      })
                    }
                  }
                })
              },
              fail: function(){},
            });
          }
        }
      }
    });
  },
  /** 上传pdf或图片 **/
  upload(e) {
    var that = this;
    let params = e.currentTarget.dataset.params;
    let name = e.currentTarget.dataset.name;
    wx.chooseMessageFile({
      count: 1,
      type: 'all',
      success(res) {
        //获取文件后缀
        // let suffix = res.tempFiles[0].path.substring(res.tempFiles[0].path.lastIndexOf('.') + 1)
        // if (suffix.search(/jpg|png|jpeg|pdf|dwg/) == -1) {
        //   wx.showToast({
        //     title: '只能上传jpg|png|jpeg|pdf|dwg文件或图片',
        //     icon: 'none'
        //   })
        //   return
        // } else {
          wx.showLoading({
            title: '选择中',
          })
          wx.uploadFile({
            url: API_BASE_URL + 'common/weChat/uploadImage',
            filePath: res.tempFiles[0].path,
            name: 'file',
            complete: function (res) {
              wx.hideLoading()              
              if (res.statusCode == 200) {
                wx.showToast({
                  title: '选择成功',
                  icon: 'none'
                })
                // let data = JSON.parse(res.data) 
                if(name =='contractFile' || name =='otherAttachment'){
                  that.data.params[name].push({
                    name: res.data,
                    url: IMG_BASE_URL + res.data
                  });
                  that.setData({
                    [`params.${name}`]: that.data.params[name]
                  })
                }else{
                  that.setData({
                    [`${params}`]: res.data
                  })
                } 
              } else {
                wx.showToast({
                  title: '选择失败',
                  icon: 'none'
                })
              }
            }
          })
        // }
      }
    })
  },
  /** 选择保险类型 **/
  bindinsuranceTypeList(e){
    this.setData({
      [`params.insurance.insuranceTypeName`]: this.data.insuranceTypeList[e.detail.value].name,
      [`params.insurance.insuranceType`]: this.data.insuranceTypeList[e.detail.value].value
    })
  },
  /** 选择保险日期 **/
  dateFn(){
    this.setData({ dateShow: !this.data.dateShow });
  },
  /** 日期格式 **/
  formatDate(date) {
    date = new Date(date);
    const year = date.getFullYear()
    const month = (date.getMonth() + 1) >9 ? (date.getMonth()+1) : '0'+(date.getMonth()+1)
    const day = date.getDate() >9 ? date.getDate() : '0'+date.getDate()
    return year+'/'+month+'/'+day;
  },
  /** 确认选择日期区间 **/
  dateConfirm(e){
    const [start, end] = e.detail;
    this.setData({
      [`params.insurance.insuranceDateFrom`]:this.formatDate(start),
      [`params.insurance.insuranceDateTo`]:this.formatDate(end),
      dateShow: false,
    });
  },
  //打开pdf文件或者大图查看图片
  openDocument(res) {
    let path = res.currentTarget.dataset.path
    if (path) {
      let suffix = path.substring(path.lastIndexOf('.') + 1) //获取文件后缀
      if(suffix=='mp4'){// 开始预览多媒体内容
        wx.previewMedia({ 
          sources: [{
            url :IMG_BASE_URL + path,
            type: 'video'
          }], // 需要预览的资源列表
        });     
      }else if(suffix != 'jpg' && suffix != 'png' && suffix != 'gif' && suffix != 'jpeg') {
        wx.showLoading({
          title: '加载中',
        })
        wx.downloadFile({
          url: IMG_BASE_URL + path,
          complete: function (res) {
            wx.hideLoading()
            const filePath = res.tempFilePath
            wx.openDocument({
              filePath: filePath,
              fileType: suffix,
              showMenu: true,
              success: function (res) {}
            })
          }
        })
      }else{
        wx.previewImage({
          urls: [IMG_BASE_URL + path] // 需要预览的图片http链接列表
        })
      }
    }
  },  
  /** 提交表单 **/
  submitFrom(e){
    let type = e.currentTarget.dataset.type
    let params = JSON.parse(JSON.stringify(this.data.params));
    for(let i in params){
      if(this.data[i]){
        params[i]=this.data[i];
      }
    }
    for(let i in params.insurance){
      if(this.data[i]){
        params.insurance[i]=this.data[i];
      }
    }
    let checkParams={...JSON.parse(JSON.stringify(params)),...JSON.parse(JSON.stringify(params.insurance))};
    console.log("checkParams",checkParams);
    for(let i in checkParams){
      //购售地址一致时不需要填写地址信息
      if(params.addressConsistent=='Y' && (i=='province' || i=='city' || i=='area' || i=='address')){
        continue;
      }
      //并网照片
      // if(i=='gebImg'){        
      //   if(!params[i].length){         
      //     wx.showToast({
      //       title: '请填写完表单必填项信息',
      //       icon: 'none'
      //     });
      //     return
      //   }
      // }     
      // if(!checkParams[i]){        
      //   wx.showToast({
      //     title: '请填写完表单必填项信息',
      //     icon: 'none'
      //   })
      //   return
      // }
    }
    params.application= {
      "entryId":this.data.projectId,//电站id
      "resultType": 1,//提交
      "insurance":params.insurance,//保险
    }
    params.entryId = this.data.projectId,//电站id
    params.gebImg = params.gebImg.length>0?params.gebImg[0].name:'';
    params.gebImg2 = params.gebImg2.length>0?params.gebImg2[0].name:'';
    params.dbImgs = params.dbImgs.length>0?params.dbImgs[0].name:'';
    params.dbxImgs = params.dbxImgs.length>0?params.dbxImgs[0].name:'';
    params.tlzhjkImgs = params.tlzhjkImgs.length>0?params.tlzhjkImgs[0].name:'';
    params.archivesImg = params.archivesImg.length>0?params.archivesImg[0].name:'';
    params.powerCapacityUrl = params.powerCapacityUrl.length>0?params.powerCapacityUrl[0].name:'';
    params.yxImg = params.yxImg.length>0?params.yxImg[0].name:'';
    
    params.contractFile = params.contractFile.length>0?params.contractFile.map(itm=>itm.name).join(","):'';//合同文件
    params.contractVideoUrl = params.contractVideoUrl.length>0?params.contractVideoUrl.map(itm=>itm.name).join(","):'';//合同视频
    params.otherAttachment = params.otherAttachment.length>0?params.otherAttachment.map(itm=>itm.name).join(","):'';//补充资料
    //地址处理
    params.electric_province = this.data.params.province;
    params.electric_city = this.data.params.city;
    params.electric_area = this.data.params.area;
    params.electric_address = this.data.params.address;

    params.generatorNo = this.data.generatorNo;
    params.powerPlantCode = this.data.powerPlantCode;
    params.provinceCodeHand = this.data.provinceCodeHand;
    params.isEmpower = 0;  //是否国网授权 0：是 1：否
    
    // params.insurance.insuranceDateFrom=params.insurance.insuranceDateFrom.split("/").join("");
    // params.insurance.insuranceDateTo=params.insurance.insuranceDateTo.split("/").join("");
    console.log("params",params);
    // return;
    if(type == '1'){//提交验收
      accept({
        userId: wx.getStorageSync('userId'),
        addReportReq: params
      }).then((res) => {
        wx.hideLoading()
        if (res.code == 200) {
          // this.bindImport(this.data.detail.generator_no); //国网授权
          wx.showToast({
            title: '提交成功',
            icon: 'none',
            success: function () {
              setTimeout(function () {
                wx.navigateBack()
              }, 1500)
            }
          })
        } else {
          wx.showToast({
            title: res.errMsg || res.msg,
            icon: 'none'
          })
        }
      });
    }else{//国网授权
      mergeTmp({
        userId: wx.getStorageSync('userId'),
        addReportReq: params
      }).then((res) => {
        wx.hideLoading()
        if (res.code == 200) {
          wx.showToast({
            title: '提交成功',
            icon: 'none',
            success: function () {
              setTimeout(function () {
                wx.navigateBack()
              }, 1500)
            }
          })
        } else {
          wx.showToast({
            title: res.errMsg || res.msg,
            icon: 'none'
          })
        }
      });
    }
  },
  /** 国网授权 **/
  bindImport(powerid) {
    addUserInfo({
      powerGenerationNo: powerid
    }).then((resApi) => {
      if (resApi.code == 200) {
        console.log("授权成功")
      }
    })
  },
})