// pages/entryInfoDetails/entryInfoDetails.js
const {
  entryDetail,
  findAllPlan,
  IMG_BASE_URL,
  deleteCustomerEntry,
  WU_TU_PIAN_URL,getFormSet
} = require('../../../api/api')
const {
  checkPermission
} = require("../../../utils/permission");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detail: {},
    planList: [], //方案列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.entryId = options.projectId;
    this.setData({
      type: options.type,
      // userType: wx.getStorageSync('userType') == "TRADER" ? 0 : 1, //0:代理商 1:平台
      userType: wx.getStorageSync('userType'),
      traderId:wx.getStorageSync('traderId') ? wx.getStorageSync('traderId') : '-1',//代理商登录的traderId
      permission:wx.getStorageSync('permission'),
    })
  },

  onShow() {
    this.entryDetail()
    this.findAllPlan()
  },



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

    }).then((res) => {
      for (let i = 0; i < res.length; i++) {
        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,
      })
    })
  },


  /**
   * 
   * 获取电站详情
   * 
   * @param {*} e 
   */
  entryDetail(e) {
    entryDetail({
      userId: wx.getStorageSync('userId'),
      entryId: this.data.entryId,
    }).then((res) => {
      // 添加图片
      // if (res.shoot_type == 1) {
        this.setData({
          detail: res,
          // [`photo.phoneOne[0].url`]: res.roof_photo_one ? IMG_BASE_URL + res.roof_photo_one : WU_TU_PIAN_URL,
          // [`photo.phoneTwo[0].url`]: res.roof_photo_two ? IMG_BASE_URL + res.roof_photo_two : WU_TU_PIAN_URL,
          // [`photo.phoneThree[0].url`]: res.roof_photo_three ? IMG_BASE_URL + res.roof_photo_three : WU_TU_PIAN_URL,
          // [`photo.phoneFour[0].url`]: res.roof_photo_four ? IMG_BASE_URL + res.roof_photo_four : WU_TU_PIAN_URL,
          //房屋照片
          [`photo.roofPhotoOne[0].url`]:res.roof_photo_one ? IMG_BASE_URL + res.roof_photo_one : WU_TU_PIAN_URL,//房屋正面
          [`photo.roofPhotoTwo[0].url`]:res.roof_photo_two ? IMG_BASE_URL + res.roof_photo_two : WU_TU_PIAN_URL,//东南角
          [`photo.roofPhotoThree[0].url`]:res.roof_photo_three ? IMG_BASE_URL + res.roof_photo_three : WU_TU_PIAN_URL,//西南角
          [`photo.roofPhotoFour[0].url`]:res.roof_photo_four ? IMG_BASE_URL + res.roof_photo_four : WU_TU_PIAN_URL,//正南侧
          [`photo.roofPhotoFacade[0].url`]:res.roof_photo_facade ? IMG_BASE_URL + res.roof_photo_facade : WU_TU_PIAN_URL,//生活气息照1
          [`photo.roofPhotoInterior[0].url`]:res.roof_photo_interior ? IMG_BASE_URL + res.roof_photo_interior : WU_TU_PIAN_URL,//生活气息照2
          [`photo.roofPhotoFive[0].url`]:res.roof_photo_five ? IMG_BASE_URL + res.roof_photo_five : WU_TU_PIAN_URL,//补充1
          [`photo.roofPhotoSix[0].url`]:res.roof_photo_six ? IMG_BASE_URL + res.roof_photo_six : WU_TU_PIAN_URL,//补充2
          [`photo.houseSupplementOne[0].url`]:res.house_supplement_one ? IMG_BASE_URL + res.house_supplement_one : WU_TU_PIAN_URL,//房屋补充1
          [`photo.houseSupplementTwo[0].url`]:res.house_supplement_two ? IMG_BASE_URL + res.house_supplement_two : WU_TU_PIAN_URL,//房屋补充2
          //细节照片
          [`photo.roofPhotoSeven[0].url`]:res.roof_photo_seven ? IMG_BASE_URL + res.roof_photo_seven : WU_TU_PIAN_URL,//障碍物照片
          [`photo.dimensionsPhotoThickness[0].url`]:res.dimensions_photo_thickness ? IMG_BASE_URL + res.dimensions_photo_thickness : WU_TU_PIAN_URL,//楼顶厚度/围墙
          [`photo.detailSupplementOne[0].url`]:res.detail_supplement_one ? IMG_BASE_URL + res.detail_supplement_one : WU_TU_PIAN_URL,//细节补充1
          [`photo.detailSupplementTwo[0].url`]:res.detail_supplement_two ? IMG_BASE_URL + res.detail_supplement_two : WU_TU_PIAN_URL,//细节补充2

          [`photo.resolutionPaperUrl[0].url`]:res.resolutionPaperUrl ? IMG_BASE_URL + res.resolutionPaperUrl : WU_TU_PIAN_URL,//村民代表大会决议书
          [`photo.yszcUrl[0].url`]:res.yszcUrl ? IMG_BASE_URL + res.yszcUrl : WU_TU_PIAN_URL,//村委议事章程
          [`photo.accountInfoUrl[0].url`]:res.accountInfoUrl ? IMG_BASE_URL + res.accountInfoUrl : WU_TU_PIAN_URL,//对公账户信息
          [`photo.ownershipCertificateUrl[0].url`]:res.ownershipCertificateUrl ? IMG_BASE_URL + res.ownershipCertificateUrl : WU_TU_PIAN_URL,//产权证明
          [`photo.otherOwnershipCertificateUrl[0].url`]:res.otherOwnershipCertificateUrl ? IMG_BASE_URL + res.otherOwnershipCertificateUrl : WU_TU_PIAN_URL,//产权证明-不动产证书
        });
      // } else if (res.shoot_type == 2) {
      //   if (res.roof_photo_one) {
      //     this.setData({
      //       [`photo.phoneSix[0].url`]: res.roof_photo_one ? IMG_BASE_URL + res.roof_photo_one : WU_TU_PIAN_URL,
      //       [`photo.phoneSeven[0].url`]: res.roof_photo_two ? IMG_BASE_URL + res.roof_photo_two : WU_TU_PIAN_URL,
      //       [`photo.phoneEight[0].url`]: res.roof_photo_three ? IMG_BASE_URL + res.roof_photo_three : WU_TU_PIAN_URL,
      //       [`photo.phoneNine[0].url`]: res.roof_photo_four ? IMG_BASE_URL + res.roof_photo_four : WU_TU_PIAN_URL,
      //       [`photo.phoneTen[0].url`]: res.roof_photo_five ? IMG_BASE_URL + res.roof_photo_five : WU_TU_PIAN_URL,
      //     })
      //   }
      // }
       //共签人子女证明材料
       let bpFile = res.bp_file ? res.bp_file.split(",") : [];
       if(bpFile.length){
         this.data.photo.bpFile=[];
         bpFile.forEach(itm=>{
           this.data.photo.bpFile.push({
             name:itm,
             url:IMG_BASE_URL + itm
           });
         });
       }
      //房产证图片
      let phoneHouse = res.house_ownership ? res.house_ownership.split(",") : [];
      if(phoneHouse.length){
        this.data.photo.phoneHouse=[];
        phoneHouse.forEach(itm=>{
          this.data.photo.phoneHouse.push({
            name:itm,
            url:IMG_BASE_URL + itm
          });
        });
      }
      this.setData({
        [`photo.phoneVideo[0].url`]: res.roof_value ? IMG_BASE_URL + res.roof_value : WU_TU_PIAN_URL,
        [`photo.idCardBackFileList[0].url`]: res.id_card_back ? IMG_BASE_URL + res.id_card_back : WU_TU_PIAN_URL,
        [`photo.idCardFrontFileList[0].url`]: res.id_card_front ? IMG_BASE_URL + res.id_card_front : WU_TU_PIAN_URL,
        [`photo.phoneHouse`]: res.house_ownership ? this.data.photo.phoneHouse : [{url:WU_TU_PIAN_URL}],
        [`photo.surveyPhoneOne[0].url`]: res.survey_record ? IMG_BASE_URL + res.survey_record : WU_TU_PIAN_URL,
        [`photo.surveyPhoneTwo[0].url`]: res.survey_record2 ? IMG_BASE_URL + res.survey_record2 : WU_TU_PIAN_URL,
        [`photo.inwardHousePhone[0].url`]: res.roof_photo_interior ? IMG_BASE_URL + res.roof_photo_interior : WU_TU_PIAN_URL,
        [`photo.roofHousePhone[0].url`]: res.dimensions_photo_thickness ? IMG_BASE_URL + res.dimensions_photo_thickness : WU_TU_PIAN_URL,
        [`photo.filingPhone[0].url`]: res.filing_document_photo ? IMG_BASE_URL + res.filing_document_photo : WU_TU_PIAN_URL,
        [`photo.residenceBooklet[0].url`]: res.residence_booklet ? IMG_BASE_URL + res.residence_booklet : WU_TU_PIAN_URL,
        [`photo.bankCard[0].url`]: res.bank_card ? IMG_BASE_URL + res.bank_card : WU_TU_PIAN_URL,
        [`photo.zjpbImg[0].url`]: res.zjpb_img ? IMG_BASE_URL + res.zjpb_img : WU_TU_PIAN_URL,
        [`photo.zjzxImg[0].url`]: res.zjzx_img ? IMG_BASE_URL + res.zjzx_img : WU_TU_PIAN_URL,
        [`photo.zjcsImg[0].url`]: res.zjcs_img ? IMG_BASE_URL + res.zjcs_img : WU_TU_PIAN_URL,
        [`photo.zjhsImg[0].url`]: res.zjhs_img ? IMG_BASE_URL + res.zjhs_img : WU_TU_PIAN_URL,
        [`photo.nbqwzImg[0].url`]: res.nbqwz_img ? IMG_BASE_URL + res.nbqwz_img : WU_TU_PIAN_URL,
        [`photo.pdxwzImg[0].url`]: res.pdxwz_img ? IMG_BASE_URL + res.pdxwz_img : WU_TU_PIAN_URL,

        [`photo.bpCardBack[0].url`]: res.bp_card_back ? IMG_BASE_URL + res.bp_card_back : WU_TU_PIAN_URL,
        [`photo.bpCardFront[0].url`]: res.bp_card_front ? IMG_BASE_URL + res.bp_card_front : WU_TU_PIAN_URL,
        // [`photo.bpFile[0].url`]: res.bp_file ? IMG_BASE_URL + res.bp_file : WU_TU_PIAN_URL,
        [`photo.bpFile`]: res.bp_file ? this.data.photo.bpFile : [{url:WU_TU_PIAN_URL}],
        [`photo.regnoUrl[0].url`]: res.regnoUrl ? IMG_BASE_URL + res.regnoUrl : WU_TU_PIAN_URL,
      })


      //标准方案,组合方案
      if (res.scheme_type == 1) {
        for (let i = 0; i < this.data.planList.length; i++) {
          const element = this.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;


            for (let i = 0; i < this.data.planList.length; i++) {
              const planTypeObj = this.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
          })
        }
      }

      // 组件,逆变器,并网箱
      var componentNum = 0; //默认
      if (res.componentList.length > 0) {
        var componentList = [];
        var converterList = [];
        var cagesList = [];
        var support = [];
        for (let i = 0; i < res.componentList.length; i++) {
          const element = res.componentList[i];
          var OB = {
            id: "",
            num: "", //数量
            model: "", //名称
          }
          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;
            support.push(OB)
          }
        }
        this.setData({
          componentList: componentList, //组件
          converterList: converterList, //逆变器
          cagesList: cagesList, //并网箱
          support: support,
        })
      }


      // let designPaper = []
      // if (res.design_drawings) {
      //   let designPaperItem = res.design_drawings.split(",")
      //   if (designPaperItem.length > 0) {
      //     designPaperItem.forEach(element => {
      //       let ob = {
      //         name: '',
      //         url: ''
      //       }
      //       ob.name = element
      //       ob.url = IMG_BASE_URL + element
      //       designPaper.push(ob)
      //     });
      //   }
      // }


      this.setData({
        projectId: res.project_id,
        projectCode: res.projectCode,
        projectName: res.projectName,
        powerStationCode: res.power_station_code,
        createTime: res.createTime,
        name: res.tenant_name,
        tenant_type: res.tenant_type,
        phone: res.mobile ? res.mobile : "无",
        idCard: res.id_code ? res.id_code : "无",
        bankName: res.bank_name ? res.bank_name : "无",
        bankCode: res.bank_code ? res.bank_code : "无",
        region: res.province + res.city + res.area ? res.province + res.city + res.area + res.address : "无",
        longitudeAndLongitude: res.longitude && res.latitude ? res.longitude + "," + res.latitude : "无",
        roofType: res.roof_type,
        shootType: res.shoot_type ? res.shoot_type : 1,
        azimuth: res.azimuth ? res.azimuth : 1,
        directionDeg: res.angle ? res.angle : "无",
        repaymentMethod: res.repayment_method,
        deg: res.distance ? res.distance : "无",
        height: res.building_height ? res.building_height : "无",
        remark: res.remarks ? res.remarks : "无",
        schemeType: res.scheme_type ? res.scheme_type : 1,
        solutionRemark: res.scheme_remarks,
        scheme: res.scheme_type == 1 ? "标准方案" : "组合方案",
        schemeRemarks: res.scheme_remarks ? res.scheme_remarks : "无",
        'photo.designPaper': res.design_drawings, //设计图纸
        componentNum: (componentNum/1000).toFixed(3), //设计安装容量

        paycycle: res.pay_cycle ? res.pay_cycle : "无",
        companyName: res.project_company_name ? res.project_company_name : "无",

        age: res.age ? res.age : "无", //年龄
        gender: res.gender == "MALE" ? "男" : "女", //性别
        insuranceFlag: res.insurance_flag, // 保险购买情况:1.控制投放及续保 2.控制投放 3.其他
        filingType: res.filing_type, // 备案类型:1.农户备案 2.项目公司备案
        leaseDate: res.lease_date ? res.lease_date : "无", //预计投放日
        bpName: res.bp_name ? res.bp_name : "无", //共签人名称
        bpRelation: res.bp_relation ? res.bp_relation : "无", //共签人与业主关系
        bpIdCard: res.bp_id_card ? res.bp_id_card : "无", //共签人证件号码,不能与租户身份证号码相同
        bpMobile: res.bp_mobile ? res.bp_mobile : "无", //共签人手机号
        bankName: res.bank_name ? res.bank_name : "无", //卡账号名称
        bankCode: res.bank_code ? res.bank_code : "无", //卡账号
        tssBankNum: res.tss_bank_num ? res.tss_bank_num : "无", //卡开户行
        tssBankNumName: res.tss_bank_num_name ? res.tss_bank_num_name : "无", //卡开户行名称
        estimateCapacity:res.estimate_capacity ? res.estimate_capacity : '',//预估组件
        //   status = "0,2" credit = "4" 为电站初勘
        status: res.status,
        credit: res.credit,
        createTraderId:res.create_trader_id,//代理商id
        corp: res.corp ? res.corp : "", //负责人姓名
        regno: res.regno ? res.regno : "", //统一社会信用代码
      })

       //当业主年龄大于65岁时，显示共签人
       if (res.age >=65) {
        this.setData({
          isComplement: true
        })
      }
      this.getFormSet(res.management)
    })
  },
  /**
     * 
     * 获取自定义字段
     * 
     * @param {*} e 
     */
    getFormSet(partner) {
      getFormSet({
        stage: '01',
        partner: partner,
      }).then((res) => {
        this.setData({
          formSetObj: res.data.columns
        })
      })
    },

  /**
   * 
   * 打开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) {
                console.log('打开文档成功')
              }
            })
          }
        })
      } else {
        wx.previewImage({
          urls: [IMG_BASE_URL + path] // 需要预览的图片http链接列表
        })
      }
    }
  },

  /** 删除 **/
  async delete(e) {
    //检验权限
    let perm = e.currentTarget.dataset.perm;
    if(!(await checkPermission(perm))){
      return;
    }
    wx.showModal({
      title: '提示',
      content: '确定将当前电站删除？',
      complete: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中',
          })
          deleteCustomerEntry({
            id: this.data.entryId,
            userId: wx.getStorageSync("userId"),
          }).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'
              })
            }
          })
        }
      }
    })
  },




})