const {
  API_BASE_URL,
  IMG_BASE_URL,
  saveArchives,
  entryDetail,
  getAddressLonLat,
  createQrcode,getFormSet,getPartnerSet,
  auditArchives,getDictionaryList
} = require('../../../api/api')
const utilAddWatermark = require('../../../utils/addWatermark')
const utilAddWatermark2 = require('../../../utils/addWatermark2')
const utilGetLocation = require('../../../utils/getLocation')
const utils = require('../../../utils/util')      

Page({
  data: {
    API_BASE_URL: API_BASE_URL,
    IMG_BASE_URL: IMG_BASE_URL,
    data: {
      name: ""
    },
    photo: {
      idCardFrontFileList: [], //身份证正面
      idCardBackFileList: [], //身份证反面
      bpCardFront: [], // 共签人身份证正面
      bpCardBack: [], //  共签人身份证反面
      bpFile: [], //   共签人子女证明材料 
      bankCard: [], //银行卡照片
      creditCertificate: [], //信誉凭证
      regnoUrl: [], //营业执照
      resolutionPaperUrl:[],//村民代表大会决议书
      yszcUrl:[],//村委议事章程
      accountInfoUrl:[],//对公账户信息
      ownershipCertificateUrl:[],//产权证明-集体土地使用证
      otherOwnershipCertificateUrl:[],//产权证明-不动产证书/查册证明/相关确权文件

      residenceBooklet: [], //户口本复印件
      houseOwnership: [], //房产证
    },
    projectId: '',
    isComplement: false, //默认不需要填写共签人信息
    userObj:{},//业主信息
    formSetObj: {}, //自定义字段
    bpRelationList: [], //共签人与业主关系
  },

  onLoad(e) {
    if(e.navTitle){
      wx.setNavigationBarTitle({
        title: e.navTitle,
      })
    }
    const projectId = e.projectId; //有projectId说明从列表进去,可能是修改或者是暂存过
    const type = e.type

    if (projectId) {
      this.setData({
        projectId,
        entryId:projectId
      })
    }
    this.setData({
      type,
    })
    this.entryDetail();
  },
  onReady() {
    const query = wx.createSelectorQuery()
    query.select('#Canvas')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node
        this.setData({
          canvas,
        })
      })
  },
  onShow(){
    // if(wx.getStorageSync('userObj')){
    //   // console.log("业主",wx.getStorageSync('userObj'));
    //   let userObj = wx.getStorageSync('userObj');
    //   this.setData(userObj);
    //   //照片
    //   this.setData({
    //     [`bankCard`]: userObj.bankCard,
    //     [`bpCardFront`]: userObj.bpCardFront,
    //     [`bpCardBack`]: userObj.bpCardBack,
    //     [`bpFile`]: userObj.bpFile,
    //   });
    //   wx.removeStorageSync('userObj');
    // }
  },
  /** 获取自定义字段 */
  getFormSet(partner) {
    getFormSet({
      stage: '05', //01:信息登记,02：踏勘设计,03：电站安装,04：电站并网,05电站勘测
      partner: partner,
    }).then((res) => {
      this.setData({
        formSetObj: res.data.columns
      })
    })
  },
  /*** 获取资方共签人 */
  getPartnerSet(partner, callback) {
    getPartnerSet({
      partnerId: partner,
    }).then((res) => {
      this.setData({
        partnerSetObj: res.data
      })
      callback()
    })
  },
  /*选择共签人与业主关系*/
  bindRelationList(e){
    this.setData({
      bpRelation: this.data.bpRelationList[e.detail.value].dict_value,
    })
  },
  /*** 获取共签人关系 */
  getDictionaryList(partner, callback) {
    getDictionaryList({
      code: 'bp_relation',//哪个字段要传哪个字段的名称
      capitalId: partner,
    }).then((res) => {
      if(res.data){
        this.setData({
          bpRelationList: res.data.map(item=>item.columns)
        })
      }
      if(callback) callback()
    })
  },
  /** 获取电站详情 **/
  entryDetail(e) {
    let that = this
    wx.showLoading({
      title: "加载中"
    })
    entryDetail({
      userId: wx.getStorageSync('userId'),
      entryId: this.data.entryId
    }).then((res) => {
      wx.hideLoading()      
      this.setData({
        detail: res,
        id: res.id, //修改数据的时候传此ID
        projectId: res.project_id,
        capitalId :res.management,
        tenant_type: res.tenant_type=='1' ? '个人' : '单位',//1.个人，2单位
        //业主信息参数
        name: res.tenant_name,
        phone: res.mobile,
        idCard: res.id_code,
        regno: res.regno,
        provinceName: res.province,
        cityName: res.city,
        areaName: res.area,
        address: res.address,
        //银行信息
        bankName: res.bank_name, //卡账号名称
        bankCode: res.bank_code, //卡账号
        tssBankNum: res.tss_bank_num, //卡开户行
        tssBankNumName: res.tss_bank_num_name, //卡开户行名称
        //共签人信息，年龄大于65岁需要共签人
        bpName: res.bp_name, //共签人名称
        bpRelation: res.bp_relation, //共签人与业主关系
        bpIdCard: res.bp_id_card, //共签人证件号码,不能与租户身份证号码相同
        bpMobile: res.bp_mobile, //共签人手机号
        bpAge: utils.getAgeByPid(res.bp_id_card),
        exigenceName: res.exigence_name, //紧急联系人
        exigencePhone: res.exigence_phone, //紧急联系人电话

        birthdayDate: res.birthday_date, //出生日期
        icValidityBegin: res.ic_validity_begin, //开始日期
        icValidityEnd: res.ic_validity_end, //结束日期
      })
      //当业主年龄大于65岁时，共签人信息必填,并且是开启overageFlag：是否开启超龄：1.开启 2.关闭
      this.getPartnerSet(res.management,()=>{
        if (res.overageFlag=='1' && res.age >= this.data.partnerSetObj.needSignerAge) {
          this.setData({
            isComplement: true
          })
        }else{
          this.setData({
            isComplement: false
          })
        }
      })
      this.getDictionaryList(res.management);
      if (res.longitude && res.latitude) {
        this.setData({
          longitudeAndLongitude: res.longitude + "," + res.latitude
        })
      }
      // 添加图片
      this.setData({
        [`photo.idCardFrontFileList`]:res.id_card_front ? [{name:res.id_card_front,url:IMG_BASE_URL + res.id_card_front}] : [], //身份证正面
        [`photo.idCardBackFileList`]:res.id_card_back ? [{name:res.id_card_back,url:IMG_BASE_URL + res.id_card_back}] : [], //身份证反面
        [`photo.bankCard`]:res.bank_card ? [{name:res.bank_card,url:IMG_BASE_URL + res.bank_card}] : [], //银行卡照片
        [`photo.bpCardFront`]:res.bp_card_front ? [{name:res.bp_card_front,url:IMG_BASE_URL + res.bp_card_front}] : [], //共签人身份证正面
        [`photo.bpCardBack`]:res.bp_card_back ? [{name:res.bp_card_back,url:IMG_BASE_URL + res.bp_card_back}] : [], //共签人身份证反面
        [`photo.regnoUrl`]:res.regno_url ? res.regno_url.split(",").map(itm=>{return {name:itm, url:IMG_BASE_URL + itm}}) : [],//营业执照
        [`photo.bpFile`]:res.bp_file ? res.bp_file.split(",").map(itm=>{return {name:itm, url:IMG_BASE_URL + itm}}) : [],//共签人子女证明材料多张
        //单位
        //个人
        [`photo.residenceBooklet`]:res.residence_booklet ? res.residence_booklet.split(",").map(itm=>{return {name:itm, url:IMG_BASE_URL + itm}}) : [],//户口本复印件
        [`photo.creditCertificate`]:res.credit_certificate ? res.credit_certificate.split(",").map(itm=>{return {name:itm, url:IMG_BASE_URL + itm}}) : [],//信誉凭证
        [`photo.houseOwnership`]:res.house_ownership ? res.house_ownership.split(",").map(itm=>{return {name:itm, url:IMG_BASE_URL + itm}}) : [],//房产证明
        //单位
        [`photo.resolutionPaperUrl`]:res.resolutionPaperUrl ?  [{name:res.resolutionPaperUrl,url:IMG_BASE_URL + res.resolutionPaperUrl}] : [],//村民代表大会决议书
        [`photo.yszcUrl`]:res.yszcUrl ?  [{name:res.yszcUrl,url:IMG_BASE_URL + res.yszcUrl}] : [],//村委议事章程
        [`photo.accountInfoUrl`]:res.accountInfoUrl ?  [{name:res.accountInfoUrl,url:IMG_BASE_URL + res.accountInfoUrl}] : [],//对公账户信息
        [`photo.ownershipCertificateUrl`]:res.ownershipCertificateUrl ?  [{name:res.ownershipCertificateUrl,url:IMG_BASE_URL + res.ownershipCertificateUrl}] : [],//产权证明-集体土地使用证
        [`photo.otherOwnershipCertificateUrl`]:res.otherOwnershipCertificateUrl ?  [{name:res.otherOwnershipCertificateUrl,url:IMG_BASE_URL + res.otherOwnershipCertificateUrl}] : [],//产权证明-不动产证书/查册证明/相关确权文件
      });
      this.getFormSet(res.management)
    })
  },
  /** 暂存提交数据 **/
  submitFrom(e) {
    var type = e.currentTarget.dataset.type    
    if (!this.data.address) {
      wx.showToast({
        title: '安装地址不能为空',
        icon: 'none'
      })
      return
    }else if(this.data.isComplement && this.data.tenant_type=='个人' && type == '2'){
      // if(this.data.bpAge<18 || this.data.bpAge>=this.data.partnerSetObj.signerConditionAge){
      if(utils.getAgeByPid(this.data.bpIdCard)<18 || utils.getAgeByPid(this.data.bpIdCard)>=this.data.partnerSetObj.signerConditionAge){
        wx.showModal({
          showCancel: false,
          content: '共签人年龄必须在18-'+this.data.partnerSetObj.signerConditionAge+'周岁之间！',
          complete: (res) => { 
          }
        })
        return
      }
    }
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    //接口数据
    var userId = wx.getStorageSync('userId')
    var CustomerEntry = {
      type: type, //1:暂存 2:提交
      projectId: this.data.projectId, //项目ID
      entryId: this.data.entryId, //
      address: this.data.address ? this.data.address.trim() : "", //详细地址
      regnoUrl: this.data.photo.regnoUrl.length > 0 ? this.data.photo.regnoUrl.map(itm=>itm.name).join(",") : "", //营业执照
      creditCertificate: this.data.photo.creditCertificate.length > 0 ? this.data.photo.creditCertificate.map(itm=>itm.name).join(",") : "", //信誉凭证
      exigenceName: this.data.exigenceName ? this.data.exigenceName : "", //紧急联系人
      exigencePhone: this.data.exigencePhone ? this.data.exigencePhone : "", //紧急联系人电话
      //共签人信息
      bpCardFront: this.data.photo.bpCardFront.length > 0 ? this.data.photo.bpCardFront[0].name : "",//共签人身份证正面
      bpCardBack: this.data.photo.bpCardBack.length > 0 ? this.data.photo.bpCardBack[0].name : "",//共签人身份证反面      
      bpFile: this.data.photo.bpFile.length > 0 ? this.data.photo.bpFile.map(itm=>itm.name).join(",") : "", //共签人子女证明材料
      bpName: this.data.bpName ? this.data.bpName : "", //共签人名称
      bpRelation: this.data.bpRelation ? this.data.bpRelation : "", //共签人与业主关系
      bpIdCard: this.data.bpIdCard ? this.data.bpIdCard : "", //共签人证件号码,不能与租户身份证号码相同
      bpMobile: this.data.bpMobile ? this.data.bpMobile : "", //共签人手机号
      //银行信息
      bankName: this.data.bankName ? this.data.bankName : "", //账号名称
      bankCode: this.data.bankCode ? this.data.bankCode : "", //账号
      bankCard: this.data.photo.bankCard.length > 0 ? this.data.photo.bankCard[0].name : "",//银行卡照片
      tssBankNum: this.data.tssBankNum ? this.data.tssBankNum : "", //开户行
      tssBankNumName:this.data.tssBankNumName ? this.data.tssBankNumName : "", //开户行名称
      //个人     
      residenceBooklet: this.data.photo.residenceBooklet.length > 0 ? this.data.photo.residenceBooklet.map(itm=>itm.name).join(",") : "", //户口本复印件
      houseOwnership: this.data.photo.houseOwnership.length > 0 ? this.data.photo.houseOwnership.map(itm=>itm.name).join(",") : "", //房产证照片
      idCardFront: this.data.photo.idCardFrontFileList.length > 0 ? this.data.photo.idCardFrontFileList[0].name : '', //身份证正面
      idCardBack: this.data.photo.idCardBackFileList.length > 0 ? this.data.photo.idCardBackFileList[0].name : '', //身份证反面

      birthdayDate: this.data.birthdayDate ? this.data.birthdayDate : "", //出生日期
      icValidityBegin: this.data.icValidityBegin ? this.data.icValidityBegin : "", //身份证生效日
      icValidityEnd: this.data.icValidityEnd ? this.data.icValidityEnd : "", //身份证到期日
      //单位
      resolutionPaperUrl:this.data.photo.resolutionPaperUrl.length > 0 ? this.data.photo.resolutionPaperUrl[0].name : "",//村民代表大会决议书
      yszcUrl:this.data.photo.yszcUrl.length > 0 ? this.data.photo.yszcUrl[0].name : "",//村委议事章程
      accountInfoUrl:this.data.photo.accountInfoUrl.length > 0 ? this.data.photo.accountInfoUrl[0].name : "",//对公账户信息
      ownershipCertificateUrl:this.data.photo.ownershipCertificateUrl.length > 0 ? this.data.photo.ownershipCertificateUrl[0].name : "",//产权证明-集体土地使用证
      otherOwnershipCertificateUrl:this.data.photo.otherOwnershipCertificateUrl.length > 0 ? this.data.photo.otherOwnershipCertificateUrl[0].name : "",//产权证明-不动产证书/查册证明/相关确权文件
    }

    if (this.data.id) {
      CustomerEntry.id = this.data.id
    }

    var data = {
      userId: userId,
      CustomerEntry: CustomerEntry,
    }

    // console.log("暂存", data)
    // if(this.data.bankCode && utils.validateBankNum(this.data.bankCode)){
    //   wx.showToast({ 
    //     title: '银行卡格式不正确', 
    //     icon: 'none' 
    //   })
    //   return
    // }

    saveArchives(data).then((res) => {
      wx.hideLoading()
      if (res.code == 200) {
        wx.showToast({
          title: type == '1' ? res.msg : "操作成功",
          icon: 'none',
          success: function () {
            setTimeout(function () {
              //延时返回上一页面
              wx.navigateBack()
            }, 1800) //延迟时间
          }
        })
      } else {
        wx.showToast({
          title: res.errMsg,
          icon: 'none'
        })
      }
    })

  },
  /** 取消 **/
  cancel(e) {
    wx.showModal({
      title: '提示',
      content: '确定取消？',
      complete: (res) => {
        if (res.cancel) {}
        if (res.confirm) {
          wx.navigateBack()
        }

      }
    })
  },
  //去除输入内容中的空格
  checkInputSpace: function(e) {
    let name = e.currentTarget.dataset.name;
    let value = e.detail.value.replace(/\s+/g, '');
    this.setData({
      [name]:value
    });
  },
  /** 打开开户行弹框 **/
  bindBankLinkChange(e) {
    if(this.data.type==18){
      return;
    }
    this.setData({
      showBankLink: true
    })
  },
  /** 选择的开户行 **/
  chooseBankLink(e) {
    this.setData({
      tssBankNum: e.detail.id,
      tssBankNumName: e.detail.name,
    })
  },
  /** 上传身份证正面OCR识别 **/
  afteruploadPhotoReadPositive(e) {
    const {
      file
    } = e.detail;
    const img = file.url;
    wx.showLoading({
      title: '上传中',
    })
    var that = this
    wx.uploadFile({
      url: that.data.API_BASE_URL + 'common/weChat/uploadImageIden',
      filePath: file.url,
      name: 'file',
      complete: function (res) {
        wx.hideLoading()
        if (res.statusCode == 200) {
          const data = JSON.parse(res.data)
          const OCRdata = JSON.parse(data.info)
          if (OCRdata.code) {
            wx.showToast({
              title: OCRdata.errMsg,
              icon: 'none',
            })
            return
          }
          var item = {
            url: "",
            name: "",
          }
          // 渲染各自图片
          switch (e.currentTarget.dataset.name) {
            case "idCardFrontFileList": //身份证正面
            if (OCRdata.data) { //OCR识别成功
              if (OCRdata.data.face) {
                if (OCRdata.data.face.data) {
                  if (OCRdata.data.face.data.name && e.currentTarget.dataset.type !=='fzr') {
                    that.setData({
                      name: OCRdata.data.face.data.name,
                      bankName: OCRdata.data.face.data.name,
                    })
                  }
                  if (OCRdata.data.face.data.name && e.currentTarget.dataset.type ==='fzr') {
                    that.setData({
                      corp: OCRdata.data.face.data.name,
                    })
                  }

                  if (OCRdata.data.face.data.idNumber) {
                    that.setData({
                      idCard: OCRdata.data.face.data.idNumber
                    })
                    if(that.data.customerType == '个人'){
                      that.getIsByIdCode(OCRdata.data.face.data.idNumber);
                    }
                  }
                  if (OCRdata.data.face.data.sex) {
                    if (OCRdata.data.face.data.sex == "男") {
                      that.setData({
                        gender: 1
                      })
                    } else if (OCRdata.data.face.data.sex == "女") {
                      that.setData({
                        gender: 2
                      })
                    }
                  }
                  if (OCRdata.data.face.data.birthDate) { //计算年龄
                    const date = new Date();
                    let birthDate = OCRdata.data.face.data.birthDate; //出生日期
                    birthDate = birthDate.replace('年', '-')
                    birthDate = birthDate.replace('月', '-')
                    birthDate = birthDate.replace('日', '')
                    // const year = OCRdata.data.face.data.birthDate; //出生日期                      
                    const age = utils.getAgeByPid(OCRdata.data.face.data.idNumber)
                    that.setData({
                      age: age,
                      birthdayDate: birthDate
                    })

                    //当业主年龄大于65岁时，需填写共签人信息
                    if (that.data.partnerSetObj.overageFlag=='1' && age >= that.data.partnerSetObj.needSignerAge) {
                    // if (age >= 65) {
                      that.setData({
                        isComplement: true
                      })
                    }else{
                      that.setData({
                        isComplement: false
                      })
                    }
                  }
                }
              }else{
                wx.showToast({
                  title: '请上传身份证正面',
                  icon: 'none'
                })
                return
              }
            }
              //身份证明水印
              // utilAddWatermark2.addWatermark(img,that.data).then((src) => {
              //   item = src;
              //   that.data.photo.idCardFrontFileList.push(item)
              //   that.setData({
              //     'photo.idCardFrontFileList': that.data.photo.idCardFrontFileList
              //   })
              // });

              item.url = img;
              item.name = data.path;
              that.data.photo.idCardFrontFileList.push(item)
              that.setData({
                'photo.idCardFrontFileList': that.data.photo.idCardFrontFileList
              })
              break;
              case "idCardBackFileList": //身份证反面
              if (OCRdata.data) {
                if (OCRdata.data.back) {
                  if (OCRdata.data.back.data) {
                    if (OCRdata.data.back.data.validPeriod) {
                      let icValidityBegin = OCRdata.data.back.data.validPeriod.substring(0,10)
                      icValidityBegin = icValidityBegin.replaceAll('.','-')
                      let icValidityEnd = OCRdata.data.back.data.validPeriod.substring(11,21)
                      if(icValidityEnd == '长期'){
                        icValidityEnd = '9999-12-31'
                      }else{
                        icValidityEnd = icValidityEnd.replaceAll('.', '-')
                      }                      
                      that.setData({
                        icValidityBegin: icValidityBegin,
                        icValidityEnd: icValidityEnd,
                      })
                    }
                  }
                }else{
                  wx.showToast({
                    title: '请上传身份证反面',
                    icon: 'none'
                  })
                  return
                }
              }
              item.url = img;
              item.name = data.path;
              that.data.photo.idCardBackFileList.push(item)
              that.setData({
                'photo.idCardBackFileList': that.data.photo.idCardBackFileList
              })
              break;
            case "bpCardFront": //共签人身份证正面
              if (OCRdata.data) {
                if (OCRdata.data.face) { 
                  if (OCRdata.data.face.data) {
                    if (OCRdata.data.face.data.name) {
                      that.setData({
                        bpName: OCRdata.data.face.data.name,
                      })
                    }
                    if (OCRdata.data.face.data.idNumber) {
                      that.setData({
                        bpIdCard: OCRdata.data.face.data.idNumber,
                        bpAge: utils.getAgeByPid(OCRdata.data.face.data.idNumber)
                      })
                    }
                  }
                }
              }
              //身份证明水印
              // utilAddWatermark2.addWatermark(img,that.data).then((src) => {
              //   item = src;
              //   that.data.photo.bpCardFront.push(item)
              //   that.setData({
              //     'photo.bpCardFront': that.data.photo.bpCardFront
              //   })
              // });

              item.url = img;
              item.name = data.path;
              that.data.photo.bpCardFront.push(item)
              that.setData({
                'photo.bpCardFront': that.data.photo.bpCardFront
              })
              break;
          }
        } else {
          wx.showToast({
            title: '上传失败',
            icon: 'error'
          })
        }
      }
    })
  },
  /** 上传银行卡OCR识别 **/
  afteruploadPhotoReadCard(e) {
    const {
      file
    } = e.detail;
    const img = file.url;
    wx.showLoading({
      title: '上传中',
    })
    var that = this
    wx.uploadFile({
      url: that.data.API_BASE_URL + 'common/updateImgBankCard',
      filePath: file.url,
      name: 'file',
      complete: function (res) {
        wx.hideLoading()
        if (res.statusCode == 200) {
          const data = JSON.parse(res.data)
          const OCRdata = JSON.parse(data.info)
          // console.log(66,OCRdata)
          if (OCRdata.code) {
            wx.showToast({
              title: OCRdata.errMsg,
              icon: 'none',
              duration: 2000
            })
            // return
          }
          // wx.showToast({
          //   title: '上传成功',
          //   icon: 'none',
          // })
          var item = {
            url: "",
            name: "",
          }
          if (OCRdata.data) { //OCR识别成功
            if (OCRdata.data) {
              if (OCRdata.data.cardNumber) {
                that.setData({
                  bankCode: OCRdata.data.cardNumber,
                })
              }
            }
          }
          item.url = img;
          item.name = data.path;
          that.data.photo.bankCard.push(item)
          that.setData({
            'photo.bankCard': that.data.photo.bankCard
          })
        } else {
          wx.showToast({
            title: '上传失败',
            icon: 'error'
          })
        }
      }
    })
  },
  /** 判断方位角方向 **/
  getDirection:function(rotate){
    // 计算应偏移度数
    let that = this;
    var area = parseInt(rotate/90)
    var detailArea = rotate%90
    if(area==0){
      that.setData({
        areaTT:"西偏北",
        detailAreaTT: 90-detailArea
      })
    }else if(area==1){
      that.setData({
        areaTT: "西偏南",
        detailAreaTT: detailArea
      })
    } else if (area == 2) {
      that.setData({
        areaTT: "东偏南",
        detailAreaTT: 90-detailArea
      })
    }else{
      that.setData({
        areaTT: "东偏北",
        detailAreaTT: detailArea
      })
    }
    return that.data.areaTT + that.data.detailAreaTT;
  },
  /** 上传图片之前 **/
  beforeRead(e){
    const type = e.currentTarget.dataset.type, that = this;
    const { callback } = e.detail;
    console.log("上传前",e);
    // callback(true);
    // return
    if (type == '水印') {
      let that = this;
      wx.getSystemInfoAsync({
        success (rep) {
          if(rep.platform == 'devtools'){
            callback(true);
          }else{
            //指南针监听,手机拍摄
            wx.onCompassChange(function(res){
              console.log("指针",res);
              var rotate = 360 - res.direction.toFixed(0)
              let direction = that.getDirection(rotate) + '°';
              that.setData({
                direction: direction
              });
              callback(true);
            });
          }
        }
      });
    }else{
      callback(true);
    }
  },
  /** 上传图片 **/
  afteruploadPhotoRead(e) {
    console.log("上传后",this.data.direction, e);
    const type = e.currentTarget.dataset.type
    const name = e.currentTarget.dataset.name
    // 细节照片添加水印
    if (type == '水印') {
      if (!this.data.name) {
        wx.showToast({
          title: '请输入业主姓名',
          icon: 'none'
        })
        return
      }
      if (!this.data.phone) {
        wx.showToast({
          title: '请输入业主联系电话',
          icon: 'none'
        })
        return
      }
      this.data.data.name = this.data.name
      this.data.data.phone = this.data.phone
      this.getLocation(e)
      return
    }
    //身份证明水印
    if(type == '身份证明水印'){
      const tempFilePath = e.detail.file.url;//图片路径
      const photoName = e.currentTarget.dataset.name; //图片名称
      utilAddWatermark2.addWatermark(tempFilePath,this.data).then((src) => {
        this.data.photo[photoName].push(src)
        this.setData({
          [`photo.${photoName}`]: this.data.photo[photoName]
        })
      });
      return;
    }
    if (Array.isArray(e.detail.file)) { //多张
      var count = 0;
      this.afteruploadPhotoReadS(e, count)
      return
    }

    const {
      file
    } = e.detail;
    const img = file.url;
    wx.showLoading({
      title: '上传中',
    })
    var that = this
    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 = img;
          item.name = res.data;
          that.data.photo[name].push(item)
          that.setData({
            [`photo.${name}`]: that.data.photo[name]
          })
        } else {
          wx.showToast({
            title: '选择失败',
            icon: 'error'
          })
        }
      }
    })
  },
  /** 上传多张图片递归 **/
  afteruploadPhotoReadS(e, count) {
    let ob = {
      name: '',
      url: '',
    }
    const name = e.currentTarget.dataset.name
    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.photo[name].push(ob);
          that.setData({
            [`photo.${name}`]: that.data.photo[name]
          })
          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 name = e.currentTarget.dataset.name
    const index = e.detail.index; //删除图片的下标
    this.data.photo[name].splice(index, 1);
    this.setData({
      // [`photo.${name}`]: index > 0 ? this.data.photo[name] : [],
      [`photo.${name}`]: this.data.photo[name]
    })
  },
  /** 上传pdf或图片 **/
  upload(e) {
    var that = this;
    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: that.data.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'
                })
                that.setData({
                  'photo.designPaper': res.data
                })
              } else {
                wx.showToast({
                  title: '选择失败',
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
  },
  //获取用户当前地理位置后为照片添加水印
  getLocation(e) {
    utilGetLocation.getLocationAddress().then((res) => {
      res.res.data = res.res.data.slice(res.res.data.lastIndexOf('省') + 1)
      this.setData({
        customerAddress: res.res.data,
        canvasLongitude: res.resLocation.longitude,
        canvasLatitude: res.resLocation.latitude,
      });
      //获取小程序二维码
      let lonLat = res.resLocation.longitude + ',' + res.resLocation.latitude;
      createQrcode({
        content:lonLat
      }).then(ret=>{
        let codeImg ="data:image/png;base64," + ret;
        this.setData({
          imageCodeImg:codeImg
        });
        // console.log("codeImg",codeImg);
        this.chooseImages(e)
      });
    })
  },
  //获取当前位置信息 位置信息转经纬度
  getNowLocationDetails: utils.debounce(function (e) {
    var that = this
    if (that.data.region[0] && that.data.address) {
      that.getAddressLonLat()
    }
  }),
  getAddressLonLat() {
    var that = this
    wx.showLoading({
      title: '加载中',
    })
    getAddressLonLat({
      address: that.data.region[0] + that.data.region[1] + that.data.region[2] + that.data.address
    }).then((res) => {
      wx.hideLoading()
      if (res.code == 200) {
        if (res.data) {
          var data = res.data.split(",")
          that.setData({
            longitude: data[0],
            latitude: data[1],
            longitudeAndLongitude: data[0] + "," + data[1]
          })
        }
      } else {
        wx.showToast({
          title: '获取经纬度失败',
          icon: 'none'
        })
      }
    })
  },
  //选择图片为图片添加水印
  async chooseImages(e) {
    const photoName = e.currentTarget.dataset.name; //图片名称
    const tempFilePath = e.detail.file.url //图片路径
    const canvasWidth = wx.getSystemInfoSync().screenWidth;
    // 获取图片信息
    await wx.getImageInfo({
      src: tempFilePath,
    }).then(async res => {
      let watermarkScale = res.width / canvasWidth;
      this.setData({
        canvasHeight: Math.round(res.height / watermarkScale),
        canvasWidth: canvasWidth,
      })

      await utilAddWatermark.addWatermark(tempFilePath, photoName, this.data).then((res) => {
        this.data.photo[photoName].push(res)
        this.setData({
          [`photo.${photoName}`]: this.data.photo[photoName]
        })
      })

    })
  },
  //打开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链接列表
        })
      }
    }
  },
  //拨打业主联系电话
  phoneFn(e) {
    const phone = e.currentTarget.dataset.phone;
    if (!phone) {
      wx.showToast({
        title: '暂无联系方式',
        icon: 'none'
      })
      return
    }
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },
  //业主信息
  userFn(e){
    wx.navigateTo({
      url: '/home/pages/ownerForm/ownerForm?projectId=' + this.data.entryId + '&type=3',
    })
  },

  /** 档案审核 **/
  audit(e) {
    let type = e.currentTarget.dataset.type;//1.审核通过 2.审核不通过
    if (type=='2' && !this.data.auditOpinion) {
      wx.showToast({
        title: '请输入驳回审核意见',
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: "提交中"
    })
    auditArchives({
      id: this.data.entryId,
      remark: this.data.auditOpinion ? this.data.auditOpinion : "",
      userId: wx.getStorageSync('userId'),
      type:type
    }).then((res) => {
      wx.hideLoading()
      if (res.code == 200) {
        let text='';
        if(type=='1'){
          text='通过成功'
        }else{
          text='驳回成功'
        }
        wx.showToast({
          title: text,
          icon: 'none',
          success: function () {
            setTimeout(function () {
              wx.navigateBack()
            }, 1500)
          }
        })
      } else {
        wx.showToast({
          title: res.msg || res.errMsg,
          icon: res.code
        })
      }
    })
  },
})