const {
  projectList,
  API_BASE_URL,
  IMG_BASE_URL,
  getElectricPlanAll,
  findAllPlan,
  saveOrEditCustomerEntry,
  entryDetail,
  getAddressByLonLat,
  getAddressLonLat,
  createQrcode
} = require('../../../api/api')

const utils = require('../../../utils/util')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    API_BASE_URL: API_BASE_URL,
    IMG_BASE_URL: IMG_BASE_URL,

    capture: ['camera'], //拍摄模式
    canvasLocation: "../../img/canvas-location.png", //手机拍摄添加水印定位图标
    canvasDate: "../../img/canvas-date.png", //手机拍摄添加水印日期图片
    canvasPeople: "../../img/canvas-people.png", //手机拍摄添加人员图片

    standardSolutionsList: [{
      type: "", //方案类型
      name: "", //方案名称
      id: "", //方案ID
      code: "", //方案编号
      drawing: "", //参考图纸
    }], //标准方案初始数量

    combinedSolutionsList: [{
      type: "", //方案类型
      name: "", //方案名称
      id: "", //方案ID
      code: "", //方案编号
      pickerIndex: 0, //方案类型选择下标
      drawing: "", //参考图纸
      addType: 1, //显示新增方案按钮
    }], //组合方案初始数量

    photo: {
      idCardFrontFileList: [], //身份证正面
      idCardBackFileList: [], //身份证反面
      // 无人机拍摄
      phoneOne: [], //俯拍图
      phoneTwo: [], //角度南
      phoneThree: [], //补充1
      phoneFour: [], //补充2
      // 手机拍摄
      phoneFive: [], //东北
      phoneSix: [], //东南
      phoneSeven: [], //南侧
      phoneEight: [], //西南
      phoneNine: [], //补充1
      phoneTen: [], //补充2
      phoneVideo: [], //屋顶视频  
      phoneHouse: [], //房产证
      //踏勘记录表
      surveyPhoneOne: [], //踏勘记录表1
      surveyPhoneTwo: [], //踏勘记录表2

      filingPhone: [], //备案文件

      // 外观照片
      outwardHousePhone: [], //房屋外观照片
      inwardHousePhone: [], //房屋内部照片
      roofHousePhone: [], //楼顶厚度照片

      designPaper: [], //设计图纸
    },

    roofType: "平屋顶", //默认为平屋顶
    schemeType: 1, //默认为标准方案
    shootType: 1, //默认为无人机拍摄
    azimuth: 1, //方位角默认为正南
    repaymentMethod: 1, //划转方式默认为二类卡

    projectId: ''
  },

  onLoad(e) {
    const projectId = e.projectId; //有projectId说明从列表进去,可能是修改或者是暂存过
    if (projectId) {
      this.setData({
        projectId
      })
    }
    this.getProjectList()
    this.getElectricPlanAll()
    this.findAllPlan()
  },


  onReady() {
    const query = wx.createSelectorQuery()
    query.select('#Canvas')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node
        this.setData({
          canvas,
        })
      })
  },


  openDocument(res) {
    console.log('openDocument', res)
    let path = res.currentTarget.dataset.path
    if (path) {
      //获取文件后缀
      let suffix = path.substring(path.lastIndexOf('.') + 1)
      if (suffix == 'pdf') {
        wx.downloadFile({
          // 示例 url，并非真实存在
          url: IMG_BASE_URL + path,
          success: function (res) {
            const filePath = res.tempFilePath
            wx.openDocument({
              filePath: filePath,
              showMenu: true,
              success: function (res) {
                console.log('打开文档成功')
              }
            })
          }
        })
      } else {
        wx.previewImage({
          urls: [IMG_BASE_URL + path] // 需要预览的图片http链接列表
        })
      }
    }
  },
  /**
   * 
   * 获取电站详情
   * 
   * @param {*} e 
   */
  entryDetail(e) {
    let that = this
    wx.showLoading({
      title: "加载中"
    })
    entryDetail({
      userId: wx.getStorageSync('userId'),
      entryId: e.projectId
    }).then((res) => {
      wx.hideLoading()
      var componentNum = 0;
      // 组件,逆变器,并网箱,支架
      if (res.componentList.length > 0) {
        var componentList = [];
        var converterList = [];
        var cagesList = [];
        var supportList = [];
        for (let i = 0; i < res.componentList.length; i++) {
          const element = res.componentList[i];
          var OB = {
            id: "",
            num: "", //数量
            model: "", //名称
            addType: 0,
          }
          if (element.item_type == 3) {
            OB.id = element.item_id;
            OB.num = element.num;
            OB.model = element.model;
            componentNum = element.num * element.model + componentNum
            componentList.push(OB)
          } else if (element.item_type == 1) {
            OB.id = element.item_id;
            OB.num = element.num;
            OB.model = element.model;
            converterList.push(OB)
          } else if (element.item_type == 2) {
            OB.id = element.item_id;
            OB.num = element.num;
            OB.model = element.model;
            cagesList.push(OB)
          } else if (element.item_type == 4) {
            OB.id = element.item_id;
            OB.num = element.num;
            OB.model = element.model;
            supportList.push(OB)
          }
        }

        //维持默认数组第一addType为1,用以显示新增按钮
        if (componentList.length > 0) {
          componentList[0].addType = 1;
          this.setData({
            componentList: componentList
          })
        } else {
          this.setData({
            componentList: [{
              id: "",
              num: "", //数量
              model: "", //名称
              addType: 1,
            }], //组件初始数量
          })
        }
        if (converterList.length > 0) {
          converterList[0].addType = 1;
          this.setData({
            converterList: converterList
          })
        } else {
          this.setData({
            converterList: [{
              id: "",
              num: "", //数量
              model: "", //名称
              addType: 1,
            }], //逆变器初始数量
          })
        }
        if (cagesList.length > 0) {
          cagesList[0].addType = 1;
          this.setData({
            cagesList: cagesList
          })
        } else {
          this.setData({
            cagesList: [{
              id: "",
              num: "", //数量
              model: "", //名称
              addType: 1,
            }], //并网箱初始数量
          })
        }
        if (supportList.length > 0) {
          supportList[0].addType = 1;
          this.setData({
            supportList: supportList
          })
        } else {
          this.setData({
            supportList: [{
              id: "",
              num: "", //数量
              model: "", //名称
              addType: 1,
            }], //支架初始数量
          })
        }
      } else {
        this.setData({
          componentList: [{
            id: "",
            num: "", //数量
            model: "", //名称
            addType: 1,
          }], //组件初始数量
          converterList: [{
            id: "",
            num: "", //数量
            model: "", //名称
            addType: 1,
          }], //逆变器初始数量
          cagesList: [{
            id: "",
            num: "", //数量
            model: "", //名称
            addType: 1,
          }], //并网箱初始数量
          supportList: [{
            id: "",
            num: "", //数量
            model: "", //名称
            addType: 1,
          }], //支架初始数量
        })
      }

      this.setData({
        componentNum: (componentNum/1000).toFixed(3),
      })

      let designPaperItem = res.design_drawings ? res.design_drawings.split(",") : ""

      let designPaper = []
      if (designPaperItem.length > 0) {
        designPaperItem.forEach(element => {
          let ob = {
            name: '',
            url: ''
          }
          ob.name = element
          ob.url = this.data.IMG_BASE_URL + element
          designPaper.push(ob)
        });
      }


      this.setData({
        id: res.id, //修改数据的时候传此ID
        projectId: res.project_id,
        projectCode: res.projectCode,
        projectName: res.projectName,
        name: res.tenant_name,
        phone: res.mobile,
        idCard: res.id_code,
        bankName: res.bank_name,
        bankCode: res.bank_code,
        [`region[0]`]: res.province,
        [`region[1]`]: res.city,
        [`region[2]`]: res.area,
        address: res.address,
        longitude: res.longitude,
        latitude: res.latitude,
        roofType: res.roof_type,
        shootType: res.shoot_type ? res.shoot_type : 2,
        azimuth: res.azimuth ? res.azimuth : 1,
        directionDeg: res.angle,
        repaymentMethod: res.repayment_method ? res.repayment_method : 1,
        deg: res.distance,
        height: res.building_height,
        remark: res.remarks,
        schemeType: res.scheme_type ? res.scheme_type : 1,
        solutionRemark: res.scheme_remarks,
        'photo.designPaper': designPaper, //设计图纸
        paycycle: res.pay_cycle,
        companyName: res.project_company_name ? res.project_company_name : ""
      })


      if (res.longitude && res.latitude) {
        this.setData({
          longitudeAndLongitude: res.longitude + "," + res.latitude
        })
      } else {
        this.getAddressLonLat()
      }

      if (res.scheme_type == 1) {
        for (let i = 0; i < that.data.planList.length; i++) {
          const element = that.data.planList[i];
          if (res.scheme_type_id && (res.scheme_type_id == element.id)) {
            this.setData({
              standardSolutionsListIndex: i,
            })
          }
        }
        this.setData({
          [`standardSolutionsList[0].id`]: res.scheme_id ? res.scheme_id : '',
          [`standardSolutionsList[0].type`]: res.scheme_type_name ? res.scheme_type_name : '',
          [`standardSolutionsList[0].typeId`]: res.scheme_type_id ? res.scheme_type_id : '',
          [`standardSolutionsList[0].name`]: res.scheme_name ? res.scheme_name : "",
        })
      } else if (res.scheme_type == 2) {
        if (res.composePlanList.length > 0) {
          var combinedSolutionsList = []
          for (let i = 0; i < res.composePlanList.length; i++) {
            var combinedSolutionsListOB = {}
            const element = res.composePlanList[i];



            // type: "", //方案类型
            // name: "", //方案名称
            // id: "", //方案ID
            // code: "", //方案编号
            // pickerIndex: 0, //方案类型选择下标
            // drawing: "", //参考图纸
            // addType: 1, //显示新增方案按钮
            if (i == 0) {
              combinedSolutionsListOB.addType = 1;
            }

            combinedSolutionsListOB.code = element.code;
            combinedSolutionsListOB.id = element.planId;
            combinedSolutionsListOB.name = element.name;
            combinedSolutionsListOB.type = element.planType;
            combinedSolutionsListOB.planTypeId = element.planTypeId;
            for (let i = 0; i < that.data.planList.length; i++) {
              const planTypeObj = that.data.planList[i];

              if (planTypeObj.allPlan.length > 0) {
                for (let j = 0; j < planTypeObj.allPlan.length; j++) {
                  const plan = planTypeObj.allPlan[j];
                  if (plan.id == element.planId) {
                    combinedSolutionsListOB.pickerIndex = i
                  }
                }
              }
            }
            combinedSolutionsList.push(combinedSolutionsListOB)
          }

          this.setData({
            combinedSolutionsList: combinedSolutionsList
          })
        }
      }


      // 添加图片
      if (res.shoot_type == 1) {
        if (res.roof_photo_one) {
          this.setData({
            [`photo.phoneOne[0].name`]: res.roof_photo_one,
            [`photo.phoneOne[0].url`]: this.data.IMG_BASE_URL + res.roof_photo_one,
          })
        }
        if (res.roof_photo_two) {
          this.setData({
            [`photo.phoneTwo[0].name`]: res.roof_photo_two,
            [`photo.phoneTwo[0].url`]: this.data.IMG_BASE_URL + res.roof_photo_two,
          })
        }
        if (res.roof_photo_three) {
          this.setData({
            [`photo.phoneThree[0].name`]: res.roof_photo_three,
            [`photo.phoneThree[0].url`]: this.data.IMG_BASE_URL + res.roof_photo_three,
          })
        }
        if (res.roof_photo_four) {
          this.setData({
            [`photo.phoneFour[0].name`]: res.roof_photo_four,
            [`photo.phoneFour[0].url`]: this.data.IMG_BASE_URL + res.roof_photo_four,
          })
        }
        if (res.roof_value) {
          this.setData({
            [`photo.phoneVideo[0].name`]: res.roof_value,
            [`photo.phoneVideo[0].url`]: this.data.IMG_BASE_URL + res.roof_value,
          })
        }
      } else if (res.shoot_type == 2) {
        if (res.roof_photo_one) {
          this.setData({
            [`photo.phoneSix[0].name`]: res.roof_photo_one,
            [`photo.phoneSix[0].url`]: this.data.IMG_BASE_URL + res.roof_photo_one,
          })
        }
        if (res.roof_photo_two) {
          this.setData({
            [`photo.phoneSeven[0].name`]: res.roof_photo_two,
            [`photo.phoneSeven[0].url`]: this.data.IMG_BASE_URL + res.roof_photo_two,
          })
        }
        if (res.roof_photo_three) {
          this.setData({
            [`photo.phoneEight[0].name`]: res.roof_photo_three,
            [`photo.phoneEight[0].url`]: this.data.IMG_BASE_URL + res.roof_photo_three,
          })
        }
        if (res.roof_photo_four) {
          this.setData({
            [`photo.phoneNine[0].name`]: res.roof_photo_four,
            [`photo.phoneNine[0].url`]: this.data.IMG_BASE_URL + res.roof_photo_four,

          })
        }
        if (res.roof_photo_five) {
          this.setData({
            [`photo.phoneTen[0].name`]: res.roof_photo_five,
            [`photo.phoneTen[0].url`]: this.data.IMG_BASE_URL + res.roof_photo_five,
          })
        }
        if (res.roof_value) {
          this.setData({
            [`photo.phoneVideo[0].name`]: res.roof_value,
            [`photo.phoneVideo[0].url`]: this.data.IMG_BASE_URL + res.roof_value,
          })
        }
      }


      if (res.id_card_back) {
        this.setData({
          [`photo.idCardBackFileList[0].name`]: res.id_card_back,
          [`photo.idCardBackFileList[0].url`]: this.data.IMG_BASE_URL + res.id_card_back,
        })
      }

      if (res.id_card_front) {
        this.setData({
          [`photo.idCardFrontFileList[0].name`]: res.id_card_front,
          [`photo.idCardFrontFileList[0].url`]: this.data.IMG_BASE_URL + res.id_card_front,
        })
      }
      if (res.house_ownership) {
        this.setData({
          [`photo.phoneHouse[0].name`]: res.house_ownership,
          [`photo.phoneHouse[0].url`]: this.data.IMG_BASE_URL + res.house_ownership,
        })
      }
      if (res.survey_record) {
        this.setData({
          [`photo.surveyPhoneOne[0].name`]: res.survey_record,
          [`photo.surveyPhoneOne[0].url`]: this.data.IMG_BASE_URL + res.survey_record,
        })
      }
      if (res.survey_record2) {
        this.setData({
          [`photo.surveyPhoneTwo[0].name`]: res.survey_record2,
          [`photo.surveyPhoneTwo[0].url`]: this.data.IMG_BASE_URL + res.survey_record2,
        })
      }

      // if (res.roof_photo_facade) {
      //   this.setData({
      //     [`photo.outwardHousePhone[0].name`]: res.roof_photo_facade,
      //     [`photo.outwardHousePhone[0].url`]: this.data.IMG_BASE_URL + res.roof_photo_facade,
      //   })
      // }

      if (res.roof_photo_interior) {
        this.setData({
          [`photo.inwardHousePhone[0].name`]: res.roof_photo_interior,
          [`photo.inwardHousePhone[0].url`]: this.data.IMG_BASE_URL + res.roof_photo_interior,
        })
      }

      if (res.dimensions_photo_thickness) {
        this.setData({
          [`photo.roofHousePhone[0].name`]: res.dimensions_photo_thickness,
          [`photo.roofHousePhone[0].url`]: this.data.IMG_BASE_URL + res.dimensions_photo_thickness,
        })
      }

      if (res.filing_document_photo) {
        this.setData({
          [`photo.filingPhone[0].name`]: res.filing_document_photo,
          [`photo.filingPhone[0].url`]: this.data.IMG_BASE_URL + res.filing_document_photo,
        })
      }



    })
  },


  /**
   * 
   * 获取产品编号
   * 
   * @param {*} e 
   */
  getProjectList(e) {
    projectList({
      userId: wx.getStorageSync('userId')
    }).then((res) => {
      this.setData({
        projectList: res
      })
    })
  },


  /**
   * 
   * 获取组件、逆变器、并网箱列表
   * 
   * @param {*} e 
   */
  getElectricPlanAll(e) {
    getElectricPlanAll({

    }).then((res) => {
      var componentApiList = [];
      var converterApiList = [];
      var cagesApiList = [];
      var supportListApiList = [];
      for (let i = 0; i < res.zjs.length; i++) {
        const element = res.zjs[i].columns;
        componentApiList.push(element)
      }
      for (let j = 0; j < res.inverters.length; j++) {
        const element = res.inverters[j].columns;
        converterApiList.push(element)
      }
      for (let k = 0; k < res.boxs.length; k++) {
        const element = res.boxs[k].columns;
        cagesApiList.push(element)
      }
      for (let m = 0; m < res.zhij.length; m++) {
        const element = res.zhij[m].columns;
        supportListApiList.push(element)
      }
      this.setData({
        componentApiList: componentApiList, //组件
        converterApiList: converterApiList, //逆变器
        cagesApiList: cagesApiList, //并网箱
        supportListApiList: supportListApiList
      })
    })
  },

  /**
   * 
   * 获取方案类型和方案名称
   * 
   * @param {*} e 
   */
  findAllPlan(e) {
    let that = this
    findAllPlan({

    }).then((res) => {
      for (let i = 0; i < res.length; i++) {
        if (res[i].allPlan) {
          res[i].allPlan = JSON.parse(res[i].allPlan)
          for (let j = 0; j < res[i].allPlan.length; j++) {
            var element = res[i].allPlan[j].columns;
            res[i].allPlan[j] = element
          }
        }
      }
      that.setData({
        planList: res,
      })

      if (that.data.projectId) {
        that.entryDetail({
          projectId: that.data.projectId
        })
      }
    })
  },



  /**
   * 
   * 暂存提交数据
   * 
   * @param {*} e 1:暂存 2:提交
   */
  submitFrom(e) {
    if (e.currentTarget.dataset.type == 1) { //暂存


      if (!this.data.projectId) {
        wx.showToast({
          title: '请选择产品名称',
          icon: 'none'
        })
        return
      }

      wx.showLoading({
        title: '提交中',
        mask: true
      })

      var composePlanList = []; // 标准方案或组合方案
      // if (this.data.schemeType == 1) { //标准
      //   if (this.data.standardSolutionsList[0].code && this.data.standardSolutionsList[0].name && this.data.standardSolutionsList[0].type && this.data.standardSolutionsList[0].id) {
      //     var composePlanListOB = {}
      //     composePlanListOB.code = this.data.standardSolutionsList[0].code;
      //     composePlanListOB.name = this.data.standardSolutionsList[0].name;
      //     composePlanListOB.planType = this.data.standardSolutionsList[0].type;
      //     composePlanListOB.planId = this.data.standardSolutionsList[0].id;
      //     composePlanList.push(composePlanListOB)
      //   }
      // } else 
      if (this.data.schemeType == 2) { //组合
        this.data.combinedSolutionsList.forEach(element => {
          if (element.code && element.name && element.type && element.id) {
            var composePlanListOB = {}
            composePlanListOB.code = element.code;
            composePlanListOB.name = element.name;
            composePlanListOB.planType = element.type;
            composePlanListOB.planId = element.id;
            composePlanListOB.planTypeId = element.planTypeId;
            composePlanList.push(composePlanListOB)
          }
        });
      }

      var itemList = []; //组件 逆变器 并网箱  1:组件 2:逆变器 3:并网箱 4:支架
      this.data.componentList.forEach(element => { //组件
        if (element.id) {
          var component = {}
          component.itemType = 3;
          component.itemId = element.id;
          component.num = element.num
          itemList.push(component)
        }
      });

      this.data.converterList.forEach(element => { //逆变器
        if (element.id) {
          var component = {}
          component.itemType = 1;
          component.itemId = element.id;
          component.num = element.num;
          itemList.push(component)
        }
      });

      this.data.cagesList.forEach(element => { //并网箱
        if (element.id) {
          var component = {}
          component.itemType = 2;
          component.itemId = element.id;
          component.num = element.num;
          itemList.push(component)
        }
      });


      this.data.supportList.forEach(element => { //支架
        if (element.id) {
          var support = {}
          support.itemType = 4;
          support.itemId = element.id;
          support.num = element.num;
          itemList.push(support)
        }
      });


      var designPaper = [];
      this.data.photo.designPaper.forEach(element => {
        designPaper.push(element.name)
      });
      designPaper.join(",")


      /**
       * 
       * 接口数据
       * 
       */
      var userId = wx.getStorageSync('userId')
      var CustomerEntry = {
        id: this.data.id ? this.data.id : "",
        type: 0, //0.暂存 2.准入登记   3.准入登记
        composePlanLists: composePlanList.length > 0 ? composePlanList : [],
        itemList: itemList.length > 0 ? itemList : [],
        projectId: this.data.projectId, //项目ID
        projectCode: this.data.projectCode, //产品编号
        projectName: this.data.projectName, //产品名称
        tenantName: this.data.name, //业主姓名
        mobile: this.data.phone, //联系方式
        province: this.data.region ? this.data.region[0] : "", //省
        city: this.data.region ? this.data.region[1] : "", //市
        area: this.data.region ? this.data.region[2] : "", //区
        idCode: this.data.idCard, //身份证卡号
        bankName: this.data.bankName, //开户银行
        bankCode: this.data.bankCode, //银行账号
        address: this.data.address, //详细地址
        longitude: this.data.longitude ? this.data.longitude : "", //经度
        latitude: this.data.latitude ? this.data.latitude : "", //纬度 
        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 : '', //身份证反面
        roofType: this.data.roofType, //屋顶类型
        shootType: this.data.shootType, //拍摄方式
        roofPhotoOne: this.data.shootType == 1 ? this.data.photo.phoneOne.length > 0 ? this.data.photo.phoneOne[0].name : "" : this.data.photo.phoneSix.length > 0 ? this.data.photo.phoneSix[0].name : "",
        roofPhotoTwo: this.data.shootType == 1 ? this.data.photo.phoneTwo.length > 0 ? this.data.photo.phoneTwo[0].name : "" : this.data.photo.phoneSeven.length > 0 ? this.data.photo.phoneSeven[0].name : "",
        roofPhotoThree: this.data.shootType == 1 ? this.data.photo.phoneThree.length > 0 ? this.data.photo.phoneThree[0].name : "" : this.data.photo.phoneEight.length > 0 ? this.data.photo.phoneEight[0].name : "",
        roofPhotoFour: this.data.shootType == 1 ? this.data.photo.phoneFour.length > 0 ? this.data.photo.phoneFour[0].name : "" : this.data.photo.phoneNine.length > 0 ? this.data.photo.phoneNine[0].name : "",
        roofPhotoFive: this.data.shootType == 1 ? "" : this.data.photo.phoneTen.length > 0 ? this.data.photo.phoneTen[0].name : "", //房屋照片
        roofValue: this.data.photo.phoneVideo.length > 0 ? this.data.photo.phoneVideo[0].name : "", //屋顶视频
        houseOwnership: this.data.photo.phoneHouse.length > 0 ? this.data.photo.phoneHouse[0].name : "", //房产证照片
        surveyRecord: this.data.photo.surveyPhoneOne.length > 0 ? this.data.photo.surveyPhoneOne[0].name : "", //踏勘记录表1
        surveyRecord2: this.data.photo.surveyPhoneTwo.length > 0 ? this.data.photo.surveyPhoneTwo[0].name : "", //踏勘记录表2

        // roofPhotoFacade: this.data.photo.outwardHousePhone.length > 0 ? this.data.photo.outwardHousePhone[0].name : "", //房屋外观照片;
        roofPhotoInterior: this.data.photo.inwardHousePhone.length > 0 ? this.data.photo.inwardHousePhone[0].name : "", //房屋内部照片;
        dimensionsPhotoThickness: this.data.photo.roofHousePhone.length > 0 ? this.data.photo.roofHousePhone[0].name : "", //楼顶厚度照片
        filingDocumentPhoto: this.data.photo.filingPhone.length > 0 ? this.data.photo.filingPhone[0].name : "", //备案文件


        distance: this.data.deg, //并网距离
        azimuth: this.data.azimuth, //方位角
        angle: this.data.azimuth != 1 ? this.data.directionDeg : "", //方位角角度
        buildingHeight: this.data.height, //建筑高度
        repaymentMethod: this.data.repaymentMethod, //划转方式
        remarks: this.data.remark, //备注
        designDrawings: designPaper + "", //设计图纸
        schemeType: this.data.schemeType, //设计方案
        schemeTypeId: this.data.schemeType == 1 ? this.data.standardSolutionsList[0].typeId ? this.data.standardSolutionsList[0].typeId : "" : "", //当设计方案为标准方案时,传参
        schemeTypeName: this.data.schemeType == 1 ? this.data.standardSolutionsList[0].type ? this.data.standardSolutionsList[0].type : "" : "",
        schemeId: this.data.schemeType == 1 ? this.data.standardSolutionsList[0].id ? this.data.standardSolutionsList[0].id : "" : "",
        schemeName: this.data.schemeType == 1 ? this.data.standardSolutionsList[0].name ? this.data.standardSolutionsList[0].name : "" : "",
        schemeRemarks: this.data.solutionRemark, //方案备注
      }

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


      // wx.hideLoading()
      // console.log("暂存", data)
      // return

      saveOrEditCustomerEntry(data).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,
            icon: 'none'
          })
        }
      })




    } else if (e.currentTarget.dataset.type == 2) { //提交
      if (!this.data.projectId) {
        wx.showToast({
          title: '请选择产品名称',
          icon: 'none'
        })
        return
      } else if (!this.data.name) {
        wx.showToast({
          title: '请输入姓名',
          icon: 'none'
        })
        return
      } else if (!this.data.phone) {
        wx.showToast({
          title: '请输入联系方式',
          icon: 'none'
        })
        return
      } else if (!this.data.idCard) {
        wx.showToast({
          title: '请输入身份证号码',
          icon: 'none'
        })
        return
      }else if (!this.data.bankName) {
        wx.showToast({
          title: '请输入开户银行',
          icon: 'none'
        })
        return
      } else if (!this.data.bankCode) {
        wx.showToast({
          title: '请输入银行账号',
          icon: 'none'
        })
        return
      } else if (!this.data.region) {
        wx.showToast({
          title: "请选择安装地址",
          icon: 'none'
        })
        return
      } else if (!this.data.address) {
        wx.showToast({
          title: "请输入安装地址",
          icon: 'none'
        })
        return
      } else if (!this.data.longitude && this.data.latitude) {
        wx.showToast({
          title: "请添加经纬度信息",
          icon: 'none'
        })
        return
      } else if (this.data.photo.idCardBackFileList.length == 0 || this.data.photo.idCardFrontFileList.length == 0) {
        wx.showToast({
          title: "请上传身份证照片",
          icon: 'none'
        })
        return
      } else if (this.data.shootType == 1 && (this.data.photo.phoneOne.length == 0 || this.data.photo.phoneTwo.length == 0 || this.data.photo.phoneVideo.length == 0)) {
        wx.showToast({
          title: "请上传房屋照片",
          icon: 'none'
        })
        return
      } else if (this.data.shootType == 2 && (this.data.photo.phoneSix.length == 0 || this.data.photo.phoneSeven.length == 0 || this.data.photo.phoneEight.length == 0 || this.data.photo.phoneVideo.length == 0)) {
        wx.showToast({
          title: "请上传房屋照片",
          icon: 'none'
        })
        return
      } else if (this.data.photo.outwardHousePhone.length == 0 || this.data.photo.inwardHousePhone.length == 0 || this.data.photo.roofHousePhone.length == 0) {
        wx.showToast({
          title: "请上传外观照片",
          icon: 'none'
        })
        return
      } else if (this.data.photo.phoneHouse.length == 0) {
        wx.showToast({
          title: "请上传房产证",
          icon: 'none'
        })
        return
      } else if (this.data.photo.surveyPhoneOne.length == 0) {
        wx.showToast({
          title: "请上传踏勘记录表",
          icon: 'none'
        })
        return
      } else if (!this.data.deg) {
        wx.showToast({
          title: "请输入并网距离",
          icon: 'none'
        })
        return
      } else if (this.data.azimuth != 1 && !this.data.directionDeg) {
        wx.showToast({
          title: "方位角为非正南时请输入角度",
          icon: 'none'
        })
        return
      } else if (!this.data.height) {
        wx.showToast({
          title: "请输入建筑高度",
          icon: 'none'
        })
        return
      } else if (this.data.photo.designPaper.length == 0) {
        wx.showToast({
          title: "请上传1-10张设计图纸",
          icon: 'none'
        })
        return
      } else if (this.data.schemeType == 1 && !this.data.standardSolutionsList[0].id) {
        wx.showToast({
          title: "请完整选择标准方案",
          icon: 'none'
        })
        return
      } else if (this.data.schemeType == 2) {
        for (let i = 0; i < this.data.combinedSolutionsList.length; i++) {
          const element = this.data.combinedSolutionsList[i];
          if (!element.code) {
            wx.showToast({
              title: "请完整选择组合方案",
              icon: 'none'
            })
            return;
          }
        }
      }

      for (let b = 0; b < this.data.componentList.length; b++) {
        const element = this.data.componentList[b];
        if (!element.num) {
          wx.showToast({
            title: "有组件未选择输入完整",
            icon: 'none'
          })
          return;
        }
      }

      for (let i = 0; i < this.data.converterList.length; i++) {
        const element = this.data.converterList[i];
        if (!element.num) {
          wx.showToast({
            title: "有逆变器未选择输入完整",
            icon: 'none'
          })
          return;
        }
      }

      // for (let j = 0; j < this.data.cagesList.length; j++) {
      //   const element = this.data.cagesList[j];
      //   if (!element.num) {
      //     wx.showToast({
      //       title: "有并网箱未选择输入完整",
      //       icon: 'none'
      //     })
      //     return;
      //   }
      // }

      wx.showLoading({
        title: '提交中',
        mask: true
      })


      var composePlanList = []; // 标准方案或组合方案
      // if (this.data.schemeType == 1) { //标准
      //   var composePlanListOB = {}
      //   composePlanListOB.code = this.data.standardSolutionsList[0].code;
      //   composePlanListOB.name = this.data.standardSolutionsList[0].name;
      //   composePlanListOB.planType = this.data.standardSolutionsList[0].type;
      //   composePlanListOB.planId = this.data.standardSolutionsList[0].id;
      //   composePlanList.push(composePlanListOB)
      // } else 
      if (this.data.schemeType == 2) { //组合
        this.data.combinedSolutionsList.forEach(element => {
          var composePlanListOB = {}
          composePlanListOB.code = element.code;
          composePlanListOB.name = element.name;
          composePlanListOB.planType = element.type;
          composePlanListOB.planId = element.id;
          composePlanListOB.planTypeId = element.planTypeId;
          composePlanList.push(composePlanListOB)
        });
      }

      var itemList = []; //组件 逆变器 并网箱  1:组件 2:逆变器 3:并网箱
      this.data.componentList.forEach(element => { //组件
        var component = {}
        if (element.id && element.num) {
          component.itemType = 3;
          component.itemId = element.id;
          component.num = element.num
          itemList.push(component)
        }
      });

      this.data.converterList.forEach(element => { //逆变器
        var component = {}
        if (element.id && element.num) {
          component.itemType = 1;
          component.itemId = element.id;
          component.num = element.num;
          itemList.push(component)
        }
      });

      this.data.cagesList.forEach(element => { //并网箱
        var component = {}
        if (element.id && element.num) {
          component.itemType = 2;
          component.itemId = element.id;
          component.num = element.num;
          itemList.push(component)
        }
      });


      var designPaper = [];
      this.data.photo.designPaper.forEach(element => {
        designPaper.push(element.name)
      });
      designPaper.join(",")

      /**
       * 
       * 接口数据
       * 
       */
      var userId = wx.getStorageSync('userId')
      var CustomerEntry = {
        id: this.data.id ? this.data.id : "", //当有此参数的时候页面为修改
        type: 3, //0.暂存 2.准入登记 3.提交审核
        composePlanLists: composePlanList,
        itemList: itemList,
        projectId: this.data.projectId, //项目ID
        projectCode: this.data.projectCode, //产品编号
        projectName: this.data.projectName, //产品名称
        tenantName: this.data.name, //业主姓名
        mobile: this.data.phone, //联系方式
        province: this.data.region[0], //省
        city: this.data.region[1], //市
        area: this.data.region[2], //区
        idCode: this.data.idCard, //身份证卡号
        bankName: this.data.bankName, //开户银行
        bankCode: this.data.bankCode, //银行账号
        address: this.data.address, //详细地址
        longitude: this.data.longitude, //经度
        latitude: this.data.latitude, //纬度
        idCardFront: this.data.photo.idCardFrontFileList[0].name, //身份证正面
        idCardBack: this.data.photo.idCardBackFileList[0].name, //身份证反面
        roofType: this.data.roofType, //屋顶类型
        shootType: this.data.shootType, //拍摄方式
        roofPhotoOne: this.data.shootType == 1 ? this.data.photo.phoneOne[0].name : this.data.photo.phoneSix[0].name,
        roofPhotoTwo: this.data.shootType == 1 ? this.data.photo.phoneTwo[0].name : this.data.photo.phoneSeven[0].name,
        roofPhotoThree: this.data.shootType == 1 ? this.data.photo.phoneThree.length > 0 ? this.data.photo.phoneThree[0].name : "" : this.data.photo.phoneEight[0].name,
        roofPhotoFour: this.data.shootType == 1 ? this.data.photo.phoneFour.length > 0 ? this.data.photo.phoneFour[0].name : "" : this.data.photo.phoneNine.length > 0 ? this.data.photo.phoneNine[0].name : "",
        roofPhotoFive: this.data.shootType == 1 ? "" : this.data.photo.phoneTen.length > 0 ? this.data.photo.phoneTen[0].name : "", //房屋照片
        roofValue: this.data.photo.phoneVideo[0].name, //屋顶视频
        houseOwnership: this.data.photo.phoneHouse[0].name, //房产证照片
        surveyRecord: this.data.photo.surveyPhoneOne[0].name, //踏勘记录表1
        surveyRecord2: this.data.photo.surveyPhoneTwo.length > 0 ? this.data.photo.surveyPhoneTwo[0].name : "", //踏勘记录表2

        // roofPhotoFacade: this.data.photo.outwardHousePhone[0].name, //房屋外观照片;
        roofPhotoInterior: this.data.photo.inwardHousePhone[0].name, //房屋内部照片;
        dimensionsPhotoThickness: this.data.photo.roofHousePhone[0].name, //楼顶厚度照片
        filingDocumentPhoto: this.data.photo.filingPhone.length > 0 ? this.data.photo.filingPhone[0].name : "", //备案文件

        distance: this.data.deg, //并网距离
        azimuth: this.data.azimuth, //方位角
        angle: this.data.azimuth != 1 ? this.data.directionDeg : "", //方位角角度
        buildingHeight: this.data.height, //建筑高度
        repaymentMethod: this.data.repaymentMethod, //划转方式
        remarks: this.data.remark, //备注
        designDrawings: designPaper + "", //设计图纸
        schemeType: this.data.schemeType, //设计方案
        schemeTypeId: this.data.schemeType == 1 ? this.data.standardSolutionsList[0].typeId : "", //当设计方案为标准方案时,传参
        schemeTypeName: this.data.schemeType == 1 ? this.data.standardSolutionsList[0].type : "",
        schemeId: this.data.schemeType == 1 ? this.data.standardSolutionsList[0].id : "",
        schemeName: this.data.schemeType == 1 ? this.data.standardSolutionsList[0].name : "",
        schemeRemarks: this.data.solutionRemark, //方案备注
      }

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

      // console.log("提交数据", data)
      // return

      saveOrEditCustomerEntry(data).then((res) => {
        wx.hideLoading()
        if (res.code == 200) {
          wx.showToast({
            title: this.data.id ? "修改成功" : "提交成功",
            icon: 'none',
            success: function () {
              setTimeout(function () {
                //延时返回上一页面
                wx.navigateBack()
              }, 1500) //延迟时间
            }
          })
        } else {
          wx.showToast({
            title: res.errMsg,
            icon: 'none'
          })
        }
      })
    }
  },


  /**
   * 
   * 上传图片
   * 
   * @param {*} e 
   */
  afteruploadPhotoRead(e) {

    const type = e.currentTarget.dataset.type

    if (type == 16) {
      var count = 0;
      this.afteruploadPhotoReadS(e, count)
      return
    }

    // 手机拍摄添加水印
    if (type == 7 || type == 8 || type == 9 || type == 10 || type == 11) {
      if (!this.data.name) {
        wx.showToast({
          title: '请输入业主姓名',
          icon: 'none'
        })
        return
      }
      this.getLocation(e)
      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: "",
          }
          // 渲染各自图片
          switch (e.currentTarget.dataset.type) {
            case "0": //身份证正面
              item.url = img;
              item.name = res.data;
              that.data.photo.idCardFrontFileList.push(item)
              that.setData({
                'photo.idCardFrontFileList': that.data.photo.idCardFrontFileList
              })
              break
            case "1": //身份证反面
              item.url = img;
              item.name = res.data;
              that.data.photo.idCardBackFileList.push(item)
              that.setData({
                'photo.idCardBackFileList': that.data.photo.idCardBackFileList
              })
              break
            case "2": //无人机俯拍
              item.url = img;
              item.name = res.data;
              that.data.photo.phoneOne.push(item)
              that.setData({
                'photo.phoneOne': that.data.photo.phoneOne
              })
              break
            case "3": //无人机角度南
              item.url = img;
              item.name = res.data;
              that.data.photo.phoneTwo.push(item)
              that.setData({
                'photo.phoneTwo': that.data.photo.phoneTwo
              })
              break
            case "4": //无人机补充1
              item.url = img;
              item.name = res.data;
              that.data.photo.phoneThree.push(item)
              that.setData({
                'photo.phoneThree': that.data.photo.phoneThree
              })
              break
            case "5": //无人机补充2
              item.url = img;
              item.name = res.data;
              that.data.photo.phoneFour.push(item)
              that.setData({
                'photo.phoneFour': that.data.photo.phoneFour
              })
              break
            case "12": //屋顶视频
              item.url = img;
              item.name = res.data;
              that.data.photo.phoneVideo.push(item)
              that.setData({
                'photo.phoneVideo': that.data.photo.phoneVideo
              })
              break
            case "13": //房产证
              item.url = img;
              item.name = res.data;
              that.data.photo.phoneHouse.push(item)
              that.setData({
                'photo.phoneHouse': that.data.photo.phoneHouse
              })
              break
            case "14": //踏勘表1
              item.url = img;
              item.name = res.data;
              that.data.photo.surveyPhoneOne.push(item)
              that.setData({
                'photo.surveyPhoneOne': that.data.photo.surveyPhoneOne
              })
              break
            case "15": //踏勘表2
              item.url = img;
              item.name = res.data;
              that.data.photo.surveyPhoneTwo.push(item)
              that.setData({
                'photo.surveyPhoneTwo': that.data.photo.surveyPhoneTwo
              })
              break
            case "17": //备案文件
              item.url = img;
              item.name = res.data;
              that.data.photo.filingPhone.push(item)
              that.setData({
                'photo.filingPhone': that.data.photo.filingPhone
              })
              break
            case "18": //房屋外观照片
              item.url = img;
              item.name = res.data;
              that.data.photo.outwardHousePhone.push(item)
              that.setData({
                'photo.outwardHousePhone': that.data.photo.outwardHousePhone
              })
              break
            case "19": //房屋内部照片
              item.url = img;
              item.name = res.data;
              that.data.photo.inwardHousePhone.push(item)
              that.setData({
                'photo.inwardHousePhone': that.data.photo.inwardHousePhone
              })
              break
            case "20": //楼顶厚度照片
              item.url = img;
              item.name = res.data;
              that.data.photo.roofHousePhone.push(item)
              that.setData({
                'photo.roofHousePhone': that.data.photo.roofHousePhone
              })
              break
          }
        } else {
          wx.showToast({
            title: '选择失败',
            icon: 'error'
          })
        }
      }
    })
  },



  /**
   * 
   * 上传设计图纸,多张图片递归
   * 
   * @param {*} e 
   */
  afteruploadPhotoReadS(e, count) {
    let ob = {
      name: '',
      url: '',
    }
    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()
        console.log("res", res)
        if (res.statusCode == 200) {
          count = count + 1;
          ob.name = res.data
          ob.url = element.url
          that.data.photo.designPaper.push(ob)
          console.log("designPaper", that.data.photo.designPaper)
          that.setData({
            'photo.designPaper': that.data.photo.designPaper
          })
          if (count == e.detail.file.length) {
            wx.showToast({
              title: '选择成功',
              icon: 'none'
            })
          } else {
            that.afteruploadPhotoReadS(e, count)
          }
        } else {
          wx.showToast({
            title: '选择失败',
            icon: 'error'
          })
        }
      }
    })
  },



  /**
   * 
   * 删除图片
   * 
   * @param {*} e 
   */
  deleteImg(e) {
    console.log("删除图片事件", e)

    switch (e.currentTarget.dataset.type) {
      case "0": //删除身份证正面
        this.setData({
          'photo.idCardFrontFileList': []
        })
        break;
      case "1": //删除身份证反面     
        this.setData({
          'photo.idCardBackFileList': []
        })
        break;
      case "2": //删除俯拍
        this.setData({
          'photo.phoneOne': []
        })
        break;
      case "3": //删除角度南
        this.setData({
          'photo.phoneTwo': []
        })
        break;
      case "4": //删除补充1
        this.setData({
          'photo.phoneThree': []
        })
        break;
      case "5": //删除补充2
        this.setData({
          'photo.phoneFour': []
        })
        break;
      case "6": //删除东北
        this.setData({
          'photo.phoneFive': []
        })
        break;
      case "7": //删除东南
        this.setData({
          'photo.phoneSix': []
        })
        break;
      case "8": //删除南侧
        this.setData({
          'photo.phoneSeven': []
        })
        break;
      case "9": //删除西南
        this.setData({
          'photo.phoneEight': []
        })
        break;
      case "10": //删除补充1
        this.setData({
          'photo.phoneNine': []
        })
        break;
      case "11": //删除补充2
        this.setData({
          'photo.phoneTen': []
        })
        break;
      case "12": //删除屋顶视频
        this.setData({
          'photo.phoneVideo': []
        })
        break;
      case "13": //删除房产证
        this.setData({
          'photo.phoneHouse': []
        })
        break;
      case "14": //删除踏勘1
        this.setData({
          'photo.surveyPhoneOne': []
        })
        break;
      case "15": //删除踏勘2
        this.setData({
          'photo.surveyPhoneTwo': []
        })
        break;
      case "16":
        this.deleteImgS(e)
        break;
      case "17": //备案文件
        this.setData({
          'photo.filingPhone': []
        })
        break;
      case "18": //房屋外观照片
        this.setData({
          'photo.outwardHousePhone': []
        })
        break;
      case "19": //房屋内部照片
        this.setData({
          'photo.inwardHousePhone': []
        })
        break;
      case "20": //楼顶厚度照片
        this.setData({
          'photo.roofHousePhone': []
        })
        break;
    }
  },

  /**
   * 删除设计图纸
   * 
   */
  deleteImgS(e) {
    const index = e.detail.index; //删除图片的下标
    this.data.photo.designPaper.splice(index, 1)
    this.setData({
      'photo.designPaper': this.data.photo.designPaper
    })
  },

  /**
   * 
   * 上传pdf或图片
   * 
   * @param {*} e 
   */
  upload(e) {
    var that = this;
    wx.chooseMessageFile({
      count: 1,
      type: 'all',
      success(res) {
        console.log('chooseMessageFile===', res)

        //获取文件后缀
        let suffix = res.tempFiles[0].path.substring(res.tempFiles[0].path.lastIndexOf('.') + 1)

        if (suffix.search(/jpg|png|jpeg|pdf/) == -1) {
          wx.showToast({
            title: '只能上传pdf文件或图片',
            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) {
              console.log("选择文件", res)
              wx.hideLoading()
              if (res.statusCode == 200) {
                wx.showToast({
                  title: '选择成功',
                  icon: 'none'
                })
                that.setData({
                  designPaper: res.data
                })
              } else {
                wx.showToast({
                  title: '选择失败',
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
  },


  /**
   * 
   * 选择产品编号
   * 
   * @param {*} ee 
   */
  bindprojectList(e) {
    this.setData({
      projectCode: this.data.projectList[e.detail.value].code,
      projectName: this.data.projectList[e.detail.value].name,
      projectId: this.data.projectList[e.detail.value].id,


      companyName: this.data.projectList[e.detail.value].companyName,
      paycycle: this.data.projectList[e.detail.value].pay_cycle
    })
  },


  /**
   * 
   * 选择标准方案类型
   * 
   * @param {*} e 
   */
  bindPlanChange(e) {
    const index = e.detail.value; //选择第几个
    this.data.standardSolutionsList[0].type = this.data.planList[index].name; //方案类型
    this.data.standardSolutionsList[0].typeId = this.data.planList[index].id; //方案类型id
    this.data.standardSolutionsList[0].name = ""; //方案名称
    this.data.standardSolutionsList[0].code = ""; //方案编号
    this.data.standardSolutionsList[0].nameId = ""; //方案名称Id
    this.data.standardSolutionsList[0].id = "";
    this.setData({
      standardSolutionsList: this.data.standardSolutionsList,
      standardSolutionsListIndex: index, //选择方案类型的下标用以渲染方案名称picker选择器
    })
  },


  /**
   * 
   * 选择标准方案名称
   * 
   * @param {*} e 
   */
  bindPlanNameChange(e) {
    if (!this.data.standardSolutionsListIndex) {
      wx.showToast({
        title: '请先选择标准方案类型',
        icon: 'none'
      })
      return
    }
    const index = e.detail.value; //选择第几个
    this.data.standardSolutionsList[0].name = this.data.planList[this.data.standardSolutionsListIndex].allPlan[index].name; //方案名称
    this.data.standardSolutionsList[0].id = this.data.planList[this.data.standardSolutionsListIndex].allPlan[index].id; //方案名称Id

    this.setData({
      standardSolutionsList: this.data.standardSolutionsList,
    })

  },


  /**
   * 
   * 选择组合方案类型
   * 
   * @param {*} e 
   */
  bindCombinationPlanChange(e) {
    const pickerIndex = e.detail.value; //选择器选择第几个
    const index = e.currentTarget.dataset.index; //选择第几个

    this.setData({
      [`combinedSolutionsList[${index}].type`]: this.data.planList[pickerIndex].name,
      [`combinedSolutionsList[${index}].planTypeId`]: this.data.planList[pickerIndex].id,
      [`combinedSolutionsList[${index}].pickerIndex`]: pickerIndex, //选择方案类型的下标用以渲染方案名称picker选择器
      [`combinedSolutionsList[${index}].name`]: "",
      [`combinedSolutionsList[${index}].code`]: "",
      [`combinedSolutionsList[${index}].id`]: "",
    })
  },


  /**
   * 
   * 选择组合方案名称
   * 
   * @param {*} e 
   */
  bindCombinationPlanNameChange(e) {
    const pickerIndex = e.detail.value; //选择器选择第几个
    const cindex = e.currentTarget.dataset.cindex; //选择第几个
    const index = e.currentTarget.dataset.index; //选择第几个
    for (let i = 0; i < this.data.combinedSolutionsList.length; i++) {
      const element = this.data.combinedSolutionsList[i];
      if (index == i && !element.type) {
        wx.showToast({
          title: '请先选择当前组合方案类型',
          icon: 'none'
        })
        return
      }
    }
    this.setData({
      [`combinedSolutionsList[${index}].id`]: this.data.planList[cindex].allPlan[pickerIndex].id,
      [`combinedSolutionsList[${index}].name`]: this.data.planList[cindex].allPlan[pickerIndex].name,
      [`combinedSolutionsList[${index}].code`]: this.data.planList[cindex].allPlan[pickerIndex].code,
    })
  },

  /**
   * 
   * 选择组件
   * 
   * @param {*} e 
   */
  bindComponentChange(e) {
    const pickerIndex = e.detail.value; //选择器选择第几个
    const index = e.currentTarget.dataset.index; //选择第几个
    this.setData({
      [`componentList[${index}].model`]: this.data.componentApiList[pickerIndex].model,
      [`componentList[${index}].id`]: this.data.componentApiList[pickerIndex].id,
    })
  },


  /**
   *
   * 选择逆变器
   *  
   * @param {*} e 
   */
  bindConverterChange(e) {
    const pickerIndex = e.detail.value; //选择器选择第几个
    const index = e.currentTarget.dataset.index; //选择第几个
    this.setData({
      [`converterList[${index}].model`]: this.data.converterApiList[pickerIndex].model,
      [`converterList[${index}].id`]: this.data.converterApiList[pickerIndex].id,
    })
  },



  /**
   * 
   * 选择并网箱
   * 
   * @param {*} e 
   */
  bindCagesChange(e) {
    const pickerIndex = e.detail.value; //选择器选择第几个
    const index = e.currentTarget.dataset.index; //选择第几个
    this.setData({
      [`cagesList[${index}].model`]: this.data.cagesApiList[pickerIndex].model,
      [`cagesList[${index}].id`]: this.data.cagesApiList[pickerIndex].id,
    })
  },

  /**
   * 
   * 选择支架
   * 
   * @param {*} e 
   */
  bindSupportListChange(e) {
    const pickerIndex = e.detail.value; //选择器选择第几个
    const index = e.currentTarget.dataset.index; //选择第几个
    this.setData({
      [`supportList[${index}].model`]: this.data.supportListApiList[pickerIndex].model,
      [`supportList[${index}].id`]: this.data.supportListApiList[pickerIndex].id,
    })
  },


  /**
   * 
   * 选择设计方案
   * 
   * @param {*} e 1:标准方案 2:组合方案
   */
  radioChangeSolution(e) {
    this.setData({
      schemeType: e.detail.value == 1 ? 1 : 2,
    })
  },

  /**
   * 
   * 选择屋顶类型
   * 
   * @param {*} e 
   */
  radioChangeRoofType(e) {
    this.setData({
      roofType: e.detail.value,
    })
  },

  /**
   * 
   * 选择拍摄方式
   * 
   * @param {*} e 
   */
  radioChangeShooting(e) {
    this.setData({
      shootType: e.detail.value == 1 ? 1 : 2
    })
  },

  /**
   * 
   * 选择方位角
   * 
   * @param {*} e 
   */
  radioChangeAzimuth(e) {
    if (e.detail.value == 1) {
      this.setData({
        azimuth: 1
      })
    } else if (e.detail.value == 2) {
      this.setData({
        azimuth: 2
      })
    } else if (e.detail.value == 3) {
      this.setData({
        azimuth: 3
      })
    }
  },


  /**
   * 
   * 选择划转方式
   * 
   * @param {*} e 
   */
  radioChangeRepaymentMethod(e) {
    this.setData({
      repaymentMethod: e.detail.value
    })
  },


  /**
   * 
   * 选择用户地址
   * 
   * @param {*} e 
   */
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value,
      address: "",
      longitudeAndLongitude: "",
      longitude: "",
      latitude: "",
    })
  },


  /**
   * 
   * 
   * 输入组件,逆变器,并网箱的数量
   * 
   * @param {*} e  1:组件 2:逆变器 3:并网箱
   */
  inputNum(e) {
    switch (e.currentTarget.dataset.type) {
      case "1":
        this.setData({
          [`componentList[${e.currentTarget.dataset.index}].num`]: e.detail.value,
        })

        var componentNum = 0
        for (let i = 0; i < this.data.componentList.length; i++) {
          const element = this.data.componentList[i];
          componentNum = element.num * element.model
        }
        this.setData({
          componentNum: (componentNum/1000).toFixed(3)
        })
        break;
      case "2":
        this.setData({
          [`converterList[${e.currentTarget.dataset.index}].num`]: e.detail.value,
        })
        break;
      case "3":
        this.setData({
          [`cagesList[${e.currentTarget.dataset.index}].num`]: e.detail.value,
        })
      case "4":
        this.setData({
          [`supportList[${e.currentTarget.dataset.index}].num`]: e.detail.value,
        })
        break;
    }
  },



  /**
   * 
   * 新增方案
   * 
   * @param {*} e 
   */
  addSolution(e) {
    const list = [{
      type: "", //方案类型
      name: "", //方案名称
      id: "", //方案ID
      code: "", //方案编号
      pickerIndex: 0, //方案类型选择下标
      drawing: "", //参考图纸
    }]
    var demo = this.data.combinedSolutionsList.concat(list)
    this.setData({
      [`combinedSolutionsList[${demo.length-1}]`]: demo[demo.length - 1]
    })
  },


  /**
   * 
   * 删除方案
   * 
   * @param {*} e 
   */
  deleteSolution(e) {
    wx.showModal({
      title: '提示',
      content: '确定删除当前方案？',
      complete: (res) => {
        if (res.confirm) {
          this.data.combinedSolutionsList.splice(e.currentTarget.dataset.index, 1)
          this.setData({
            combinedSolutionsList: this.data.combinedSolutionsList
          })
        }
      }
    })
  },

  /**
   * 
   * 新增型号
   * 
   * @param {*} e 1:组件 2:逆变器 3:并网箱
   */
  add(e) {
    const list = {
      id: "",
      num: "",
      name: "",
    }
    switch (e.currentTarget.dataset.type) {
      case "1":
        this.setData({
          componentList: this.data.componentList.concat(list)
        })
        break;
      case "2":
        this.setData({
          converterList: this.data.converterList.concat(list)
        })
        break;
      case "3":
        this.setData({
          cagesList: this.data.cagesList.concat(list)
        })
      case "4":
        this.setData({
          supportList: this.data.supportList.concat(list)
        })
        break;
    }
  },

  /**
   * 
   * 删除型号
   * 
   * @param {*} e 1:组件 2:逆变器 3:并网箱
   */
  delete(e) {
    wx.showModal({
      title: '提示',
      content: '确定删除？',
      complete: (res) => {
        if (res.confirm) {
          switch (e.currentTarget.dataset.type) {
            case "1":
              this.data.componentList.splice(e.currentTarget.dataset.index, 1)
              this.setData({
                componentList: this.data.componentList
              })
              break;
            case "2":
              this.data.converterList.splice(e.currentTarget.dataset.index, 1)
              this.setData({
                converterList: this.data.converterList,
              })
              break;
            case "3":
              this.data.cagesList.splice(e.currentTarget.dataset.index, 1)
              this.setData({
                cagesList: this.data.cagesList,
              })
            case "4":
              this.data.supportList.splice(e.currentTarget.dataset.index, 1)
              this.setData({
                supportList: this.data.supportList,
              })
              break;
          }
        }
      }
    })
  },



  /**
   * 
   * 
   * 获取用户当前地理位置后为照片添加水印
   * 
   * @param {*} res 
   * @param {*} e 
   */
  getLocation(e) {
    var that = this
    wx.showLoading({
      title: '获取定位中',
    })
    wx.getLocation({
      type: 'wgs84',
      isHighAccuracy: true,
      success(resLocation) {
        getAddressByLonLat({
          lonLat: resLocation.longitude + "," + resLocation.latitude
        }).then((res) => {
          wx.hideLoading()
          if (res.code == 200) {
            res.data = res.data.split("省")
            that.setData({
              customerAddress: res.data.length > 1 ? res.data[1] : res.data,
              canvasLongitude: resLocation.longitude,
              canvasLatitude: resLocation.latitude
            })
            wx.getStorage({
              key: 'userName',
              success(res) {
                that.setData({
                  userName: res.data
                })
              }
            })
            //获取小程序二维码
            let lonLat = resLocation.longitude + ',' + resLocation.latitude;
            createQrcode({
              content:lonLat
            }).then(ret=>{
              let codeImg ="data:image/png;base64," + ret;
              that.setData({
                imageCodeImg:codeImg
              });
              // console.log("codeImg",codeImg);
              that.chooseImages(e)
            });
            // that.chooseImages(e)
          } else {
            wx.showToast({
              title: '定位失败',
              icon: 'none'
            })
          }

        })
      },
      fail(res) {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '拍摄上传房屋照片,请先授权小程序定位权限',
          cancelText: "取消",
          confirmText: "确定",
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                withSubscriptions: true,
              })
            }
          }
        })
      }
    })
  },


  /**
   * 
   * 获取当前位置信息 经纬度转位置信息
   * 
   * @param {*} e 
   */
  getNowLocation(e) {
    var that = this
    wx.getLocation({
      type: 'wgs84',
      isHighAccuracy: true,
      success(res) {
        console.log("获取经纬", res)
        wx.showLoading({
          title: '获取定位中',
        })
        getAddressByLonLat({
          lonLat: res.longitude + "," + res.latitude
        }).then((res) => {
          wx.hideLoading()
          if (res.code == 200) {

          } else {
            wx.showToast({
              title: '定位失败',
              icon: 'none'
            })
          }
        })
      },
      fail(res) {
        wx.showModal({
          title: '提示',
          content: '请授权当前小程序定位权限',
          cancelText: "取消",
          confirmText: "确定",
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                withSubscriptions: true,
              })
            }
          }
        })
      }
    })
  },



  /**
   * 
   * 获取当前位置信息 位置信息转经纬度
   * 
   * @param {*} 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'
          })
        }
      } else {
        wx.showToast({
          title: '获取经纬度失败',
          icon: 'none'
        })
      }
    })
  },



  /**
   * 
   * 
   * 选择图片
   * 
   * 
   * @param {*} res 
   */
  async chooseImages(res) {
    const type = res.currentTarget.dataset.type
    const {
      file
    } = res.detail;
    await this.addWatermark(file.url, type)
  },



  /**
   * 
   * 添加水印方法
   * 
   * @param {*} tempFilePath//图片路径 
   * @param {*} type //类型
   */
  addWatermark(tempFilePath, type) {
    return new Promise(async (resolve, reject) => {

      wx.showLoading({
        title: '添加水印中',
      })

      // 获取图片信息
      const imgInfo = await wx.getImageInfo({
        src: tempFilePath
      })

      //获取当前设备像素
      const dpr = wx.getSystemInfoSync().pixelRatio

      //创建画笔
      const ctx = this.data.canvas.getContext('2d')

      //设置画布大小
      if (wx.getSystemInfoSync().platform == "ios") {
        this.data.canvas.width = imgInfo.width
        this.data.canvas.height = imgInfo.height
        ctx.scale(1, 1)
      } else {
        this.data.canvas.width = imgInfo.width * 1.5
        this.data.canvas.height = imgInfo.height * 1.5
        ctx.scale(1.5, 1.5)
      }

      // 创建图片对象
      const image = this.data.canvas.createImage();

      //设置图片路径
      image.src = tempFilePath;

      //绘制照片
      image.onload = () => {
        //绘制定位图标  
        const imageLocation = this.data.canvas.createImage();
        imageLocation.src = this.data.canvasLocation
        imageLocation.onload = () => {
          ctx.drawImage(imageLocation, 20, imgInfo.height - 100, 80, 80)
        }

        //绘制人员图标
        const imagePeople = this.data.canvas.createImage();
        imagePeople.src = this.data.canvasPeople
        imagePeople.onload = () => {
          ctx.drawImage(imagePeople, 20, imgInfo.height - 220, 80, 80)
        }

        //绘制日期图标
        // const imageDate = this.data.canvas.createImage();
        // imageDate.src = this.data.canvasDate
        // imageDate.onload = () => {
        //   ctx.drawImage(imageDate, imgInfo.width - 500, imgInfo.height - 220, 80, 80)
        // }

        ctx.drawImage(image, 0, 0, imgInfo.width, imgInfo.height)

        //绘制黑色背景矩形
        //绘制黑色渐变背景矩形
        var grd = ctx.createLinearGradient(0, 0, imgInfo.width, 0);
        grd.addColorStop(0, "rgba(0,0,0,0.8)");
        grd.addColorStop(1, "rgba(255,255,255,0.4)");
        ctx.fillStyle = grd;
        ctx.fillRect(0, imgInfo.height - 250, imgInfo.width, 250)

        //设置文字大小及字体
        if (wx.getSystemInfoSync().platform == "ios") {
          ctx.font = `35px sans-serif`
        } else {
          ctx.font = `25px sans-serif`
        }

        //设置画笔颜色
        ctx.fillStyle = '#ffffff';

        // //绘制时间
        // let time = utils.formatTime(new Date())
        // ctx.fillText(`${time}`, imgInfo.width - 400, imgInfo.height - 165)

        //设置文字大小及字体
        if (wx.getSystemInfoSync().platform == "ios") {
          ctx.font = `40px sans-serif`
        } else {
          ctx.font = `30px sans-serif`
        }

        //绘制用户姓名
        let name = this.data.name
        ctx.fillText("用户姓名:" + `${name}`, 120, imgInfo.height - 195)

        //绘制勘测人员
        let time = utils.formatTime(new Date())
        let surveyName = this.data.userName
        ctx.fillText("勘测人员:" + `${surveyName}` + "(" + `${time}` + ")", 120, imgInfo.height - 145)


        //绘制地点
        ctx.fillText(`${this.data.customerAddress}`, 120, imgInfo.height - 25)

        //绘制经纬度
        ctx.fillText("经度:" + `${this.data.canvasLongitude}` + "  " + "纬度:" + `${this.data.canvasLatitude}`, 120, imgInfo.height - 75)


        //绘制完成后将canvas转为为图片
        setTimeout(() => {
          wx.hideLoading()
          wx.showLoading({
            title: '上传中',
            mask: true
          })
          wx.canvasToTempFilePath({
            canvas: this.data.canvas,
            complete: (res) => {
              console.log("将canvas转为为图片", res)
              if (res.errMsg == "canvasToTempFilePath:ok") {
                var that = this
                wx.uploadFile({
                  url: that.data.API_BASE_URL + 'common/weChat/uploadImage',
                  filePath: res.tempFilePath,
                  name: 'file',
                  complete: function (res) {
                    wx.hideLoading()
                    console.log("上传图片", res)
                    if (res.statusCode == 200) {
                      var item = {
                        url: "",
                        name: "",
                      }
                      switch (type) {
                        case "7": //手机东南
                          item.url = that.data.IMG_BASE_URL + res.data;
                          item.name = res.data;
                          that.data.photo.phoneSix.push(item)
                          that.setData({
                            'photo.phoneSix': that.data.photo.phoneSix
                          })
                          break
                        case "8": //手机南侧
                          item.url = that.data.IMG_BASE_URL + res.data;
                          item.name = res.data;
                          that.data.photo.phoneSeven.push(item)
                          that.setData({
                            'photo.phoneSeven': that.data.photo.phoneSeven
                          })
                          break
                        case "9": //手机西南
                          item.url = that.data.IMG_BASE_URL + res.data;
                          item.name = res.data;
                          that.data.photo.phoneEight.push(item)
                          that.setData({
                            'photo.phoneEight': that.data.photo.phoneEight
                          })
                          break
                        case "10": //手机补充1
                          item.url = that.data.IMG_BASE_URL + res.data;
                          item.name = res.data;
                          that.data.photo.phoneNine.push(item)
                          that.setData({
                            'photo.phoneNine': that.data.photo.phoneNine
                          })
                          break
                        case "11": //手机补充2
                          item.url = that.data.IMG_BASE_URL + res.data;
                          item.name = res.data;
                          that.data.photo.phoneTen.push(item)
                          that.setData({
                            'photo.phoneTen': that.data.photo.phoneTen
                          })
                          break
                      }
                    } else {
                      wx.showToast({
                        title: "选择失败",
                        icon: 'none'
                      })
                    }
                  }
                })
              } else {
                wx.hideLoading()
                wx.showToast({
                  title: "选择失败",
                  icon: 'none'
                })
              }
              resolve(res.tempFilePath)
            },
          })
        }, 300)
      }
    })
  },
})