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

  /**
   * 页面的初始数据
   */
  data: {
    detail: {}, //接口返回的详情数据
    detailObj:{}, //处理后的详情数据
    photoList: [],//图片集合
    tabIndex: '1', //一级分类
    tabSecIndex: '1', //二级分类
    otherFiles: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log(66, options.type)
    this.data.entryId = options.projectId;
    if(options.type =='12'){
      this.setData({
        tabIndex: '4'
      })
    }
    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.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.filingDocumentPhoto[0].url`]:res.filing_document_photo ? IMG_BASE_URL + res.filing_document_photo : WU_TU_PIAN_URL,//备案证
          
          [`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,//产权证明-不动产证书

        });
        if(res.report){
          this.setData({
            [`photo.dbImgs[0].url`]:res.report.dbImgs ? IMG_BASE_URL + res.report.dbImgs : WU_TU_PIAN_URL,//电表图片
            [`photo.dbxImgs[0].url`]:res.report.dbxImgs ? IMG_BASE_URL + res.report.dbxImgs : WU_TU_PIAN_URL,//电表箱图片
            [`photo.tlzhjkImgs[0].url`]:res.report.tlzhjkImgs ? IMG_BASE_URL + res.report.tlzhjkImgs : WU_TU_PIAN_URL,//铜铝转换接头照片
            [`photo.powerCapacityUrl[0].url`]:res.report.powerCapacityUrl ? IMG_BASE_URL + res.report.powerCapacityUrl : WU_TU_PIAN_URL,//3日发电量
            [`photo.yxImg[0].url`]:res.report.yxImg ? IMG_BASE_URL + res.report.yxImg : WU_TU_PIAN_URL,//电站运行信息
            [`photo.gebImg[0].url`]:res.report.gebImg ? IMG_BASE_URL + res.report.gebImg : WU_TU_PIAN_URL,//补充信息
            [`photo.gebImg2[0].url`]:res.report.gebImg2 ? IMG_BASE_URL + res.report.gebImg2 : WU_TU_PIAN_URL,//补充信息2
            [`photo.archivesImg[0].url`]:res.report.archivesImg ? IMG_BASE_URL + res.report.archivesImg : WU_TU_PIAN_URL,//三户档案截图
            otherFiles: res.report.otherFiles?res.report.otherFiles.split(","):[]
          })
        }
      // } 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 residenceBooklet = res.residence_booklet ? res.residence_booklet.split(",") : [];
      if(residenceBooklet.length){
        this.data.photo.residenceBooklet=[];
        residenceBooklet.forEach(itm=>{
          this.data.photo.residenceBooklet.push({
            name:itm,
            url:IMG_BASE_URL + itm
          });
        });
      }
      //共签人子女证明材料
      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
          });
        });
      }
      //信誉凭证
      let creditCertificate = res.credit_certificate ? res.credit_certificate.split(",") : [];
      if(creditCertificate.length){
        this.data.photo.creditCertificate=[];
        creditCertificate.forEach(itm=>{
          this.data.photo.creditCertificate.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.creditCertificate`]: res.credit_certificate ? this.data.photo.creditCertificate : [{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.residenceBooklet`]: res.residence_booklet ? this.data.photo.residenceBooklet : [{url: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,
      })      

      // 组件,逆变器,并网箱
      var componentNum = 0; //默认
      if(res.management == '04'){//华融
        if (res.projectDetailList[0].componentList.length > 0) {
          this.getUsedMaterialInfo() 
        }
      }else{
        if (res.componentList.length > 0) {
          this.getUsedMaterialInfo() 
        }
      }

           
      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, //设计安装容量

        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 : "无", //共签人名称
        bpIdCard: res.bp_id_card ? res.bp_id_card : "无", //共签人证件号码,不能与租户身份证号码相同
        bpMobile: res.bp_mobile ? res.bp_mobile : "无", //共签人手机号
        bpRelation: res.bp_relation ? res.bp_relation : "无", //共签人与业主关系
        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 : "", //统一社会信用代码
      })
      //重新赋值，传给子组件
      const photoList = JSON.parse(JSON.stringify(this.data.photo))
      const detailObj = JSON.parse(JSON.stringify(this.data))
      this.setData({
        photoList,
        detailObj,
      }) 
      // console.log(9999, this.data.componentList)      
      // this.getFormSet(res.management)
      // this.getAllConditionList(res.management)
    })
  },
  /**
     * 
     * 获取自定义字段
     * 
     * @param {*} e 
     */
    getAllConditionList(partner) {
      getAllConditionList({
        partner: partner,
      }).then((res) => {
        this.setData({
          formSetObj: res.data
        })
      })
    },
    /**
   * 
   *  获取使用物料列表
   * 
   * @param {*} e 
   */
  getUsedMaterialInfo(e) {
    getUsedMaterialInfo({
      entryId: this.data.entryId,
    }).then((res) => {
      var componentList = []; //组件
      var converterList = []; //逆变器
      var cagesList = []; //并网箱
      var supportList = []; //支架
      if (res.code == 200) {
        res.data.materialEntryList = JSON.parse(res.data.materialEntryList)
        // if (res.data.warehouseId) {
        //   this.data.warehourseList.forEach(element => {
        //     if (element.id == res.data.warehouseId) {
        //       this.setData({
        //         warehourseName: element.name,
        //         warehouseId: res.data.warehouseId
        //       })
        //     }
        //   });
        // }
        //华融安装多产品
        if(res.data.projectSettingList){
          this.setData({
            productList: JSON.parse(res.data.projectSettingList)
          })
        }

        if (res.data.materialEntryList.length > 0) {
          res.data.materialEntryList.forEach(element => {
            if (element.type == "组件") {
              componentList.push(element)
            } else if (element.type == "逆变器") {
              converterList.push(element)
            } else if (element.type == "并网箱") {
              cagesList.push(element)
            } else if (element.type == "支架") {
              supportList.push(element)
            }
          });

          var list = [];
          componentList.forEach(element => {
            var pos = list.findIndex((res) => {
              return res.materialId == element.materialId && res.projectId == element.projectId
            })
            if (pos == -1) {
              element.itemList = [JSON.parse(JSON.stringify(element))]
              list.push(element)
            } else {
              list[pos].itemList.push(element)
            }
          });

          var list1 = [];
          converterList.forEach(element => {
            var pos = list1.findIndex((res) => {
              return res.materialId == element.materialId && res.projectId == element.projectId
            })
            if (pos == -1) {
              element.itemList = [JSON.parse(JSON.stringify(element))]
              list1.push(element)
            } else {
              list1[pos].itemList.push(element)
            }
          });

          this.setData({
            componentList: list,
            converterList: list1,
            cagesList: cagesList,
            supportList: supportList,
            nbqList: res.data.nbqMap?JSON.parse(res.data.nbqMap):[],
            zjMap: res.data.zjMap?JSON.parse(res.data.zjMap):''
          })
        } else {
          this.setData({
            componentList: [],
            converterList: [],
            cagesList: [],
            supportList: [],
            nbqList: res.data.nbqMap?JSON.parse(res.data.nbqMap):[],
            zjMap: res.data.zjMap?JSON.parse(res.data.zjMap):''
          })
        }
      }
    })
  },

  /**
   * 
   * 打开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'
              })
            }
          })
        }
      }
    })
  },
  //一级切换TAB
  changeTab(e){    
    let type = e.currentTarget.dataset.index
    this.setData({
      tabIndex: type
    })
  },
  //二级切换TAB
  changeSecTab(e){    
    let type = e.currentTarget.dataset.index
    this.setData({
      tabSecIndex: type
    })
  },
})