const {
  getProjectByArea,
  getCompany,
  API_BASE_URL,
  IMG_BASE_URL,
  getElectricPlanAll,
  findAllPlan,
  saveOrEditCustomerEntry,
  entryDetail,
  createQrcode,
  getFormSet,
  DEV,
  findTypeReferenceListNew,
  bankCardPage,
  surveyToDesign, getAllDictionarySelect,
  updateCustomerEntry,auditBack,designCustomerEntry,
  appletsFailed,
  appletsToExamine,getPressureLevel
} = require('../../../api/api')
const utilAddWatermark = require('../../../utils/addWatermark')
const utilAddWatermark2 = require('../../../utils/addWatermark2')
const utilGetLocation = require('../../../utils/getLocation')
const utils = require('../../../utils/util')

Page({
  data: {
    API_BASE_URL: API_BASE_URL,
    IMG_BASE_URL: IMG_BASE_URL,
    DEV: DEV,
    capture: ['camera', 'album'], //拍摄模式
    data: {
      name: ""
    },
    photo: {
      fwImg1: [],//房屋整体图
      fwImg2: [],//房屋内部结构图
      fwImg3: [],//房屋屋顶东南侧图片
      fwImg4: [],//房屋屋顶西南侧图片
      fwImg5: [],//遮阴物与房屋距离、高度
      flyImgs: [], //无人机航拍图
      roofPhotoOne: [], //安装区域整体照片
      roofPhotoTwo: [], //安装区域东南角照片
      roofPhotoThree: [], //安装区域西南角照片
      roofPhotoFour: [], //安装区域正南照片
      roofPhotoFive: [], //安装区域细节照片
      roofPhotoFacade: [], //房屋内部结构照片
      roofPhotoInterior: [], //房屋内部环境照片
      detailSupplementOne: [], //逆变器、配电箱预安装位置照片
      houseSupplementOne: [], //房屋其他障碍物照片
      surveyVideo: [], //踏勘补充证明视频
      surveyFiles: [], //踏勘记录表
      houseOwnership: [],//房产证
      vrRoofOne: [], //房屋整体图
      vrRoofTwo: [], //房屋整体俯视图
      vrRoofThree: [], //房屋内部结构图
      vrRoofFour: [], //入户全景照片
      houseOutlinePhoto:[], //房屋轮廓照片
      // phoneVideo: [], //屋顶视频
      // filingDocumentPhoto: [], //备案文件
      //踏勘记录表
      // surveyPhoneOne: [], //踏勘记录表1
      // surveyPhoneTwo: [], //踏勘记录表2
      //房屋照片
      // roofPhotoSix:[],//补充2
      // houseSupplementTwo:[],//房屋补充2
      //细节照片
      // roofPhotoSeven:[],//障碍物照片
      // dimensionsPhotoThickness:[],//楼顶厚度/围墙
      // detailSupplementTwo:[],//细节补充2
      //方案信息
      designDrawings: [], //设计图纸
      zjpbImg: [], //组件排布图
      zjzxImg: [], // 组件走线图
      zjcsImg: [], //支架侧视图
      zjhsImg: [], //电气图
      // nbqwzImg: [], //逆变器位置
      // pdxwzImg: [], //配电箱位置
      dzImgs: [], //组合图
    },
    photoTips: [
      //越秀
      {
      showKey: 'fly_imgs',
      key: 'flyImgs',
      num: 9,
      minNum: 3,
      title: '无人机航拍图',
    },{
      showKey: 'roof_photo_one',
      key: 'roofPhotoOne',
      num: 9,
      minNum: 2,
      title: '安装区域整体照片',
    }, {
      showKey: 'roof_photo_two',
      key: 'roofPhotoTwo',
      num: 9,
      minNum: 1,
      title: '安装区域东南角照片',
    }, {
      showKey: 'roof_photo_four',
      key: 'roofPhotoFour',
      num: 9,
      minNum: 1,
      title: '安装区域正南照片',
    }, {
      showKey: 'roof_photo_three',
      key: 'roofPhotoThree',
      num: 9,
      minNum: 1,
      title: '安装区域西南角照片',
    }, {
      showKey: 'roof_photo_five',
      key: 'roofPhotoFive',
      num: 9,
      minNum: 1,
      title: '安装区域细节照片',
    }, {
      showKey: 'roof_photo_interior',
      key: 'roofPhotoInterior',
      num: 9,
      minNum: 2,
      title: '房屋内部环境照片',
    }, {
      showKey: 'roof_photo_facade',
      key: 'roofPhotoFacade',
      num: 9,
      minNum: 2,
      title: '房屋内部结构照片',
    }, {
      showKey: 'detail_supplement_one',
      key: 'detailSupplementOne',
      num: 9,
      minNum: 1,
      title: '逆变器、配电箱预安装位置照片',
    },{
      showKey: 'house_outline_photo',
      key: 'houseOutlinePhoto',
      num: 9,
      minNum: 1,
      title: '房屋轮廓照片',
    }, {
      showKey: 'house_supplement_one',
      key: 'houseSupplementOne',
      num: 9,
      minNum: 1,
      title: '房屋其他障碍物照片',
    }, {
      showKey: 'survey_files',
      key: 'surveyFiles',
      num: 4,
      title: '踏勘记录表',
    },{
      showKey: 'roof_photo_one_03',
      key: 'roofPhotoOne',
      num: 9,
      minNum: 2,
      title: '房屋屋顶照片',
    },{
      showKey: 'roof_photo_two_03',
      key: 'roofPhotoTwo',
      num: 9,
      minNum: 1,
      title: '房屋屋顶东侧图片',
    },{
      showKey: 'roof_photo_three_03',
      key: 'roofPhotoThree',
      num: 9,
      minNum: 1,
      title: '房屋屋顶西侧图片',
    },{
      showKey: 'roof_photo_four_03',
      key: 'roofPhotoFour',
      num: 9,
      minNum: 1,
      title: '房屋屋顶南侧图片',
    },{
      showKey: 'fw_img3',
      key: 'fwImg3',
      num: 9,
      minNum: 1,
      title: '房屋屋顶东南侧图片',
    },{
      showKey: 'fw_img4',
      key: 'fwImg4',
      num: 9,
      minNum: 1,
      title: '房屋屋顶西南侧图片',
    },{
      showKey: 'fw_img5',
      key: 'fwImg5',
      num: 9,
      minNum: 1,
      title: '遮阴物与房屋距离、高度',
    },{
      showKey: 'survey_video',
      key: 'surveyVideo',
      num: 8,
      minNum: 1,
      title: '踏勘补充证明视频',
    },{
      showKey: 'house_ownership',
      key: 'houseOwnership',
      num: 8,
      minNum: 1,
      title: '房产证明',
    },{
      showKey: 'survey_files_03',
      key: 'surveyFiles',
      num: 9,
      minNum: 1,
      title: '户用勘察记录表（附平面草图）',
    },{
      showKey: 'fw_img1',
      key: 'fwImg1',
      num: 9,
      minNum: 1,
      title: '房屋整体图',
    },{
      showKey: 'vr_roof_one',
      key: 'vrRoofOne',
      num: 9,
      minNum: 1,
      title: '房屋整体图（VR全景）',
    },{
      showKey: 'vr_roof_two',
      key: 'vrRoofTwo',
      num: 9,
      minNum: 1,
      title: '房屋整体俯视图（无人机）',
    },{
      showKey: 'vr_roof_three',
      key: 'vrRoofThree',
      num: 9,
      minNum: 1,
      title: '房屋内部结构图（VR）',
    },{
      showKey: 'fw_img2',
      key: 'fwImg2',
      num: 9,
      minNum: 1,
      title: '房屋内部结构图',
    },{
      showKey: 'vr_roof_four',
      key: 'vrRoofFour',
      num: 9,
      minNum: 1,
      title: '入户全景照片(VR)',
    },{
      showKey: 'fly_imgs_04',
      key: 'flyImgs',
      num: 9,
      minNum: 3,
      title: '屋顶高空俯视照片',
    },{
      showKey: 'roof_photo_two_04',
      key: 'roofPhotoTwo',
      num: 9,
      minNum: 1,
      title: '屋顶东南照片',
    },{
      showKey: 'roof_photo_four_04',
      key: 'roofPhotoFour',
      num: 9,
      minNum: 1,
      title: '屋顶正南照片',
    },{
      showKey: 'roof_photo_three_04',
      key: 'roofPhotoThree',
      num: 9,
      minNum: 1,
      title: '屋顶西南照片',
    },{
      showKey: 'vr_roof_four_04',
      key: 'vrRoofFour',
      num: 9,
      minNum: 1,
      title: '入户全景照片',
    },{
      showKey: 'survey_files_04',
      key: 'surveyFiles',
      num: 4,
      title: '现场勘测表',
    }],
    //房屋信息
    sealRoof: '', //是否封屋顶
    schemeType: 1, //默认为标准方案
    azimuth: 1, //方位角默认为正南
    // repaymentMethod: 1, //划转方式默认为二类卡
    projectId: '',
    formSetObj: {}, //自定义字段
    caseImgArr: [], //示例图数据
    productZj: 0, //产品默认的组件值
    companyList: [], //对应产品的项目公司列表数据
    auditStatus: '1',
    nodeType: '1',
    gridType: '0',
    active:0,
  },
  /** 多产品-input输入控制 **/
  onInputArr(e){
    const pIndex = e.currentTarget.dataset.pindex;
    let value = e.detail.value;
    let name = e.currentTarget.dataset.name;
    // 将输入值的小数点替换为一个字符，确保只有两位小数
    value = value.replace(/^(\-)*(\d+)\.(\d{2}).*$/, '$1$2.$3');
    // 设置输入框的值
    this.setData({
      [`projectListTab[${pIndex}].${name}`]: value,
    });
  },
  /** input数值输入控制 **/
  onInput(e) {
    let value = e.detail.value;
    let name = e.currentTarget.dataset.name;
    // 将输入值的小数点替换为一个字符，确保只有两位小数
    value = value.replace(/^(\-)*(\d+)\.(\d{2}).*$/, '$1$2.$3');
    // 设置输入框的值
    this.setData({
      [`${name}`]: value
    });
  },
  //只能输入整数
  onInput2(e) {
    let value = e.detail.value;
    let name = e.currentTarget.dataset.name;   
    value = value.replace(/[^\d]/g,'');   
    this.setData({
      [`${name}`]: value
    });
  },
  onLoad(e) {
    console.log("option",e);
    if (e.navTitle) {
      wx.setNavigationBarTitle({
        title: e.navTitle,
      })
    }
    this.setData({
      projectId:e.projectId, //有projectId说明从列表进去,可能是修改或者是暂存过
      entryId: e.projectId,
      traderId: wx.getStorageSync('traderId'),
      type: e.type,
      navTitle:e.navTitle,
      disabledYear:(new Date()).getFullYear()
    })
    if(e.navTitle == '勘测设计'){
      this.setData({
        disable1:true,
      });
    }
    if(e.navTitle == '设计审核'){
      this.setData({
        disable1:true,
        disable2:true,
      });
    }
    this.findAllPlan();
    this.getCaseImg();
  },
  onReady() {
    const query = wx.createSelectorQuery()
    query.select('#Canvas')
      .fields({
        node: true,
        size: true
      })
      .exec(async (res) => {
        const canvas = res[0].node
        this.setData({
          canvas,
        })
      })
  },
  onShow() {},
  /*** 获取字典 */
  getDictionaryList(partner, callback) {
    getAllDictionarySelect({
      capitalId: partner,
    }).then((res) => {
      if(res.data){
        this.setData({    
          roofTypeList: res.data.roof_type.map(item=>item.columns), //屋顶类型
          angleAzimuthSel: res.data.angle_azimuth.map(item=>item.columns), //方位角
          voltageClassesSel: res.data.voltage_classes.map(item=>item.columns), //并网电压等级
        })
      }
      if(callback) callback(res.data)
    })
  },
  /** 获取自定义字段 */
  getFormSet(partner) {
    getFormSet({
      stage: '02', //01:信息登记,02：踏勘设计,03：电站安装,04：电站并网
      partner: partner,
    }).then((res) => {
      this.setData({
        formSetObj: res.data.columns,
      })
    })
  },
  /** 获取示例图 */
  getCaseImg() {
    findTypeReferenceListNew({
      typeId: '02', //勘测
    }).then((res) => {
      if (res.data) {
        this.setData({
          caseImgArr: res.data,
        })
      }
    })
  },
  /** 示图图片放大 **/
  viewPic(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.item.map(itm => IMG_BASE_URL + itm.imgsValue)[e.currentTarget.dataset.index], // 当前显示图片的 http 链接
      urls: e.currentTarget.dataset.item.map(itm => IMG_BASE_URL + itm.imgsValue) // 需要预览的图片 http 链接列表
    })
  },
  /** 获取电站详情 **/
  entryDetail(e) {
    let that = this
    wx.showLoading({
      title: "加载中"
    })
    entryDetail({
      userId: wx.getStorageSync('userId'),
      entryId: that.data.entryId
    }).then((res) => {
      wx.hideLoading()
      //预计投放日默认当前时间后60天
      let date = new Date();
      //这里的60就是你要加的天数，减也可以。年、月会相应加上去，值得注意的是date.getMonth()得到的月份比实际月份小1，所以实际月份是(date.getMonth()+1)
      date.setDate(date.getDate() + 60);
      var leaseDate = utils.formatTime2(date);
      this.setData({
        detail: res,
        id: res.id, //修改数据的时候传此ID
        tenant_type: res.tenant_type == '1' ? '个人' : '单位', //1.个人，2单位
        capitalId: res.zfId, //资方id
        provinceName: res.province,
        cityName: res.city,
        areaName: res.area,
        address: res.address,
        longitude: res.longitude,
        latitude: res.latitude,
        longitudeAndLongitude: (res.longitude && res.latitude) ? (res.longitude + "," + res.latitude) : '',
        companyName: res.project_company_name,
        companyId: res.project_company_id,
        filingType: res.filing_type, // 备案类型:1.农户备案 2.项目公司备案
        repaymentMethod:res.filing_type == 1 ? 1 : (res.filing_type == 2) ? 0 : '',//如果是农户备案。只能选择二类卡
        leaseDate: res.lease_date ? res.lease_date : leaseDate, //预计投放日
        //房屋信息
        sealRoof: res.seal_roof, //是否封屋顶，1是，2.否
        completionYear: res.completion_year ? res.completion_year : '', //房屋建成年份
        azimuth: res.azimuth ? res.azimuth : '', //方位角
        directionDeg: res.angle, //方位角
        buildingHeight: res.building_height, //建筑高度
        ewLength: res.ew_length, //东西长
        nsWide: res.ns_wide, //南北宽
        slopeGradient: res.slope_gradient, //屋面坡度
        purlineInterval: res.purline_interval, //檀条间距
        waterproof: res.waterproof, //屋顶防水情况
        sourcePollution: res.source_pollution, //是否有污染源
        opsCondition: res.ops_condition, //是否具备运维空间
        voltageClasses: res.voltage_classes, //并网电压等级
        transformerCapacity: res.transformer_capacity, //变压器容量
        restrictFlag: res.restrict_flag, //是否符合变压器容量限制要求
        distance: res.distance, //配电箱至并网点距离
        // dipAngle: res.dip_angle, //组件倾角
        roofArea: res.roof_area, //屋顶面积
        //方案信息
        // schemeType: res.scheme_type ? res.scheme_type : 1,
        solutionRemark: res.scheme_remarks,//方案备注
        //设计自审
        auditRemarks: res.zs_audit_remarks, //审核意见
        auditStatus: res.zs_flag?res.zs_flag: '1', //审核结果 
        nodeType: res.node_type?res.node_type:'1', //驳回节点
        // remark: res.remarks,
        // insuranceFlag: res.insurance_flag, // 保险购买情况:1.控制投放及续保 2.控制投放 3.其他
        // filingDocumentCode: res.filing_document_code, //项目备案代码
        windPressure: res.wind_pressure, //风压
        snowPressure: res.snow_pressure, //雪压
        pressureLevel: res.pressure_level, //风雪压等级
      });
      //并网方式处理
      if(res.recordBoxHistory){
        if(res.recordBoxHistory ==''){//并网方式没选择过，默认‘单户并网’          
          this.setData({
            gridType: '0',//并网方式
            boxTotalCount: '', //总数
            boxGroupNum: '', //编号
            boxGroupName: '', //名称
          })
        }else{
          this.setData({
            gridType: res.recordBoxHistory.type,//并网方式
            gridStatus: res.recordBoxHistory.status,//状态为1不能编辑
            boxTotalCount: res.recordBoxHistory.total_count,
            boxGroupNum: res.recordBoxHistory.group_number,
            boxGroupName: res.recordBoxHistory.group_name,
            boxGroupId: res.recordBoxHistory.box_group_id,
          })                
        }
      }
      //已选产品数据处理
      let projectDetailList = res.projectDetailList;
      let projectListPrm=[{
        "projectId":"",//产品id
        "projectName":"",//产品名称
        "projectCode":"",//产品编号
        "payCycle":"",//租金支付周期
        "roofType":"",//屋顶类型
        "assemblySpecs": 0, //产品默认的组件值
      }], arr=[];
      let projectListTab=[];
      projectDetailList.forEach(pItem=>{
        //产品
        let obj = {};
        for(let key in projectListPrm[0]){
          if(pItem[key]){
            obj[key] = pItem[key]
          }
        }
        arr.push(obj);
        //图片
        let photo = {};
        for(let key in this.data.photo){
          photo[key] = pItem[key] ? pItem[key].split(",").map(itm => { return { name: itm, url: IMG_BASE_URL + itm}}) : []
        }
        //tab
        pItem.addEntryReqDesignDetails[0].id = pItem.addEntryReqDesignDetails[0].schemeId;
        photo.designDrawings=pItem.addEntryReqDesignDetails[0].designDrawings ? pItem.addEntryReqDesignDetails[0].designDrawings.split(",").map(itm => { return { name: itm, url: IMG_BASE_URL + itm}}) : [];
        // 3组件,1逆变器,2并网箱,4支架
        var componentApiList = this.data.componentApiList;//组件列表
        let componentNum = 0;
        var componentList = [];
        var converterList = [];
        var cagesList = [];
        var supportList = [];
        if (pItem.componentList.length > 0) {
          for (let i = 0; i < pItem.componentList.length; i++) {
            const element = pItem.componentList[i];
            var OB = {
              id: "",
              num: "", //数量
              model: "", //名称
              addType: 0,
            }
            if (element.item_type == 3) {
              OB.id = pItem.assemblySpecs > Number(element.model) ? (utils.filterItem('model',pItem.assemblySpecs,componentApiList).id || "") : element.item_id;
              OB.num = element.num;
              OB.model = pItem.assemblySpecs > Number(element.model) ? (utils.filterItem('model',pItem.assemblySpecs,componentApiList).model || "") : element.model;
              OB.material_model = pItem.assemblySpecs > Number(element.model) ? (utils.filterItem('model',pItem.assemblySpecs,componentApiList).material_model || "") : element.material_model;
              componentNum = (Number(OB.num) * Number(OB.model) + componentNum)
              componentList.push(OB)
            } else if (element.item_type == 1) {
              OB.id = element.item_id;
              OB.num = element.num;
              OB.model = element.model;
              OB.material_model = element.material_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)
            }
          }
        }
        let obj2={
          ...obj,
          "dipAngle": pItem.dipAngle, //组件倾角
          "photoTips":that.data.photoTips,//照片
          photo:photo,
          "plan":pItem.addEntryReqDesignDetails[0],
          "componentNum":(componentNum / 1000).toFixed(3), //设计安装容量
          "converterList":converterList.length ? converterList : [{
            id: "",
            num: "", //数量
            model: "", //名称
            material_model:'',
            addType: 1,
          }],//1逆变器
          "cagesList":cagesList.length ? cagesList : [{
            id: "",
            num: "", //数量
            model: "", //名称
            addType: 1,
          }],//2并网箱
          "componentList":componentList.length ? componentList : [{
            id: utils.filterItem('model',pItem.assemblySpecs,componentApiList).id || "",
            num: "", //数量
            model: utils.filterItem('model',pItem.assemblySpecs,componentApiList).model || "", //名称
            material_model:utils.filterItem('model',pItem.assemblySpecs,componentApiList).material_model || '',
            addType: 1,
          }],//3组件
          "supportList":supportList.length ? supportList : [{
            id: "",
            num: "", //数量
            model: "", //名称
            addType: 1,
          }],//4支架
        }
        projectListTab.push(obj2);
      });
      this.setData({
        projectListPrm:arr.length ? arr : projectListPrm,
        projectListTab,
      });
      //设置的参数
      this.getFormSet(res.management);
      //下拉字典
      this.getDictionaryList(res.management, (res2)=>{
        if(res2.angle_azimuth){
          let angleList = res2.angle_azimuth.map(item=>item.columns);
          if(res.azimuth){
            let azimuthName = angleList.find(itm => itm.dict_key === res.azimuth).dict_value;
            this.setData({
              azimuthName
            })
          }   
        }
      }); 
      this.getCompanyList();
      this.getProjectList();
      // console.log("projectListPrm",this.data.projectListPrm);
      // console.log("projectListTab",projectListTab);
    })
  },
  //获取多产品-tab
  getProjectListTab(projectId,roofType,callback){
    callback = typeof callback == 'function' ? callback : function(){};
    if(projectId && this.data.projectListPrm.find(itm=>itm.projectId == projectId)){
      wx.showToast({
        title: '产品不能重复',
        icon:'none'
      })
      return callback(false);
    }else if(roofType && this.data.projectListPrm.find(itm=>itm.roofType == roofType)){
      wx.showToast({
        title: '屋顶类型不能重复',
        icon:'none'
      })
      return callback(false);
    }else{
      callback(true);
    }
    let projectListTab = this.data.projectListTab, projectListPrm = this.data.projectListPrm, arr = [], that=this;
    var componentApiList = this.data.componentApiList;//组件列表
    for(var i=0;i<projectListPrm.length;i++){
      if(projectListPrm[i].projectId && projectListPrm[i].roofType){
        let obj = projectListTab.find(itm=>itm.roofType == projectListPrm[i].roofType);
        if(obj){
          if(!obj.componentList[0].id){
            obj.componentList[0].id = utils.filterItem('model',projectListPrm[i].assemblySpecs,componentApiList).id || "";
            obj.componentList[0].model = utils.filterItem('model',projectListPrm[i].assemblySpecs,componentApiList).model || "";
            obj.componentList[0].material_model = utils.filterItem('model',projectListPrm[i].assemblySpecs,componentApiList).material_model || "";
          }
          arr.push(obj);
          continue;
        }
        arr.push({
          ...projectListPrm[i],
          "photoTips":that.data.photoTips,//照片
          "photo":that.data.photo,
          "plan":{
            "schemeTypeId":"",//方案类型id
            "schemeTypeName":"",//方案类型名称
            "schemeId":"",//方案id
            "schemeName":"",//方案名称
          },
          "componentNum":0, //设计安装容量
          "converterList":[{
            id: "",
            num: "", //数量
            model: "", //名称
            material_model:'',
            addType: 1,
          }],//1逆变器
          "cagesList":[{
            id: "",
            num: "", //数量
            model: "", //名称
            addType: 1,
          }],//2并网箱
          "componentList":[{
            id: utils.filterItem('model',projectListPrm[i].assemblySpecs,componentApiList).id || "",
            num: "", //数量
            model: utils.filterItem('model',projectListPrm[i].assemblySpecs,componentApiList).model || "", //名称
            material_model:utils.filterItem('model',projectListPrm[i].assemblySpecs,componentApiList).material_model || '',
            addType: 1,
          }],//3组件
          "supportList":[{
            id: "",
            num: "", //数量
            model: "", //名称
            addType: 1,
          }],//4支架
        });
      }
    }
    this.setData({
      projectListTab:arr,
      active:0,
    });
    if(arr.length){
      this.selectComponent("#tabResize").resize()
    }
    console.log("projectListPrm",this.data.projectListPrm);
    console.log("projectListTab",arr);
  },
  /** 打开省市区弹框 **/
  bindRegionChange(e) {
    if(this.data.disable1){
      return
    }
    this.setData({
      showRegion: true
    })
  },
  /** 选择的地址 **/
  chooseRegion(e) {
    this.setData({
      provinceName: e.detail.provinceName,
      cityName: e.detail.cityName,
      areaName: e.detail.areaName,
      address: "",
      projectListPrm:[{
        "projectId":"",//产品id
        "projectName":"",//产品名称
        "projectCode":"",//产品编号
        "payCycle":"",//租金支付周期
        "roofType":"",//屋顶类型
        "assemblySpecs": 0, //产品默认的组件值
      }],
      projectListTab:[],
      companyName: '',
      companyId: '',
      companyList:[]
    })
    this.getProjectList();
    this.getCompanyList();
    this.getPressure(e.detail.provinceName, e.detail.cityName, e.detail.areaName) //获取风雪压等级
  },
  //获取当前位置信息 位置信息转经纬度
  getNowLocationDetails: utils.debounce(function (e) {
    var that = this
    if (that.data.provinceName && that.data.address) {
      wx.showModal({
        content: '即将获取您当前所在位置的经纬度，请确认您已到达电站安装位置。',
        complete: (res) => { 
          if (res.confirm) {
            that.getNowLocation()
          }
        }
      })
    }
  }),
  /** 获取当前位置信息 经纬度转位置信息 **/
  getNowLocation(e) {
    var that = this
    wx.getLocation({
      type: 'wgs84',
      isHighAccuracy: true,
      success(res) {
        console.log("获取经纬", res)
        wx.showLoading({
          title: '获取定位中',
        })
        if(res.longitude && res.latitude){
          wx.hideLoading()
          that.setData({
            longitude: res.longitude.toFixed(6),
            latitude: res.latitude.toFixed(6),
            longitudeAndLongitude: res.longitude.toFixed(6) + "," + res.latitude.toFixed(6)
          })
        }
      },
      fail(res) {
        wx.showModal({
          title: '提示',
          content: '请授权当前小程序定位权限',
          cancelText: "取消",
          confirmText: "确定",
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                withSubscriptions: true,
              })
            }
          }
        })
      }
    })
  },
  /** 获取项目公司列表数据 **/
  getCompanyList(e) {
    getCompany({
      traderId: wx.getStorageSync('traderId'),
      projectId: this.data.entryId,
      partner: this.data.capitalId, //资方
      filingType: this.data.filingType?this.data.filingType:'', //备案类型
      province: this.data.provinceName,
      city: this.data.cityName,
      area: this.data.areaName,
    }).then((res) => {
      this.setData({
        companyList: res.data && res.data.length ? res.data.map(itm => itm.columns) : []
      })
    })
  },
  /* 获取风雪压等级*/
  getPressure(province,city,area) {
    getPressureLevel({
      province: this.data.provinceName,
      city: this.data.cityName,
      area: this.data.areaName,
    }).then((res) => {
      if(res.code == 200){
        if(res.data){
          this.setData({
            windPressure: res.data.columns.wind_pressure, //风压
            snowPressure: res.data.columns.snow_pressure, //雪压
            pressureLevel: res.data.columns.pressure_level, //风雪压等级
          })
        }
      }
    })
  },
  //选择项目公司
  bindcompanyList(e) {
    this.setData({
      companyId: this.data.companyList[e.detail.value].id,
      companyName: this.data.companyList[e.detail.value].name,
    })
  },
  /** 获取产品列表数据 **/
  getProjectList(e) {
    getProjectByArea({
      userId: wx.getStorageSync('userId'),
      type: 1,
      tenantType: this.data.tenant_type == '单位' ? '2' : '1', //租户类型：1.个人，2单位
      filType: this.data.tenant_type == '单位' ? '2' : '1', //租户类型：1.个人，2单位
      projectId: this.data.capitalId,
      filingType: this.data.filingType, //备案类型：1.农户，2项目公司
      province: this.data.provinceName,
      city: this.data.cityName,
      area: this.data.areaName,
    }).then((res) => {
      this.setData({
        projectList: res.data && res.data.length ? res.data.map(itm => itm.columns) : []
      })
    })
  },
  //选择产品
  bindprojectList(e) {
    this.getProjectListTab(this.data.projectList[e.detail.value].id,'',(res)=>{
      if(res){
        //产品信息
        let index = e.currentTarget.dataset.index;
        this.data.projectListPrm[index].projectCode = this.data.projectList[e.detail.value].code
        this.data.projectListPrm[index].projectName = this.data.projectList[e.detail.value].name
        this.data.projectListPrm[index].projectId = this.data.projectList[e.detail.value].id
        this.data.projectListPrm[index].payCycle = this.data.projectList[e.detail.value].pay_cycle
        this.data.projectListPrm[index].roofType = ''
        this.data.projectListPrm[index].assemblySpecs = this.data.projectList[e.detail.value].assembly_specs ? Number(this.data.projectList[e.detail.value].assembly_specs) : 0; //默认组件值
        this.setData({
          [`projectListPrm[${index}]`]:this.data.projectListPrm[index],
        })
      }
    });
  },
  //选择并网方式
  radioChangeGridType(e) {
    let detail = this.data.detail
    this.setData({
      gridType: e.detail.value,
    })    
    if(e.detail.value == '1'){//一户多站选项
      if(detail.recordBoxHistory && detail.recordBoxHistory != ''){//有历史记录取历史数据
        if(detail.recordBoxHistory.type == '1'){//判断是不是一户多站的数据，type=1
          this.setData({
            boxTotalCount: detail.recordBoxHistory.total_count?detail.recordBoxHistory.total_count:'',
            boxGroupNum: detail.recordBoxHistory.group_number?detail.recordBoxHistory.group_number:'',
            boxGroupName: detail.recordBoxHistory.group_name?detail.recordBoxHistory.group_name:'',
          })
        }else{//type不是1，则取一户多站字段         
          this.setData({
            boxTotalCount: detail.oneToAnyBoxSet.total_count?detail.oneToAnyBoxSet.total_count:'',
            boxGroupNum: detail.oneToAnyBoxSet.group_number?detail.oneToAnyBoxSet.group_number:'',
            boxGroupName: detail.oneToAnyBoxSet.group_name?detail.oneToAnyBoxSet.group_name:'',
            boxGroupId: detail.oneToAnyBoxSet.id?detail.oneToAnyBoxSet.id:'',
          })
        }        
      }else{//没有历史记录，oneToAnyBoxSet取原有数据
        this.setData({          
          boxTotalCount: detail.oneToAnyBoxSet.total_count?detail.oneToAnyBoxSet.total_count:'',
          boxGroupNum: detail.oneToAnyBoxSet.group_number?detail.oneToAnyBoxSet.group_number:'',
          boxGroupName: detail.oneToAnyBoxSet.group_name?detail.oneToAnyBoxSet.group_name:'',
          boxGroupId: detail.oneToAnyBoxSet.id?detail.oneToAnyBoxSet.id:'',
        })
      }      
    }else if(e.detail.value == '2' && detail.recordBoxHistory != ''){//整村汇流选项
      if(detail.recordBoxHistory && detail.recordBoxHistory != '' && detail.recordBoxHistory.type == '2'){//有历史数据
        this.setData({
          boxTotalCount: detail.recordBoxHistory.total_count?detail.recordBoxHistory.total_count:'',
          boxGroupNum: detail.recordBoxHistory.group_number?detail.recordBoxHistory.group_number:'',
          boxGroupName: detail.recordBoxHistory.group_name?detail.recordBoxHistory.group_name:'',
        })
      }else{//没有历史数据，全清空
        this.setData({
          boxTotalCount: '',
          boxGroupNum: '',
          boxGroupName: '',
        })
      }
    }else{//单户并网选项
      this.setData({
        boxTotalCount: '',
        boxGroupNum: '',
        boxGroupName: '',
      })
    }
  },
  //打开选择汇流组
  goConverge(e){   
    wx.navigateTo({
      url: '/home/pages/converge/converge?projectId='+this.data.entryId,
    })
  },
  //选择屋顶类型
  radioChangeRoofType(e) {
    let dval = e.detail.value
    let list = e.currentTarget.dataset.list
    let index = e.currentTarget.dataset.index;
    this.getProjectListTab('',this.data[list][dval].dict_value,(res)=>{
      if(res){
        this.setData({
          [`projectListPrm[${index}].roofType`]:this.data[list][dval].dict_value,
        })
      }
    });
  },
  //新增产品-按钮
  addProd(){
    let obj ={
      "projectId":"",//产品id
      "projectName":"",//产品名称
      "projectCode":"",//产品编号
      "payCycle":"",//租金支付周期
      "roofType":"",//屋顶类型
      "assemblySpecs": 0, //产品默认的组件值
    }
    this.data.projectListPrm.push(obj);
    this.setData({
      [`projectListPrm`]:this.data.projectListPrm,
    })
  },
  //删除产品-按钮
  delProd(e){
    let index = e.currentTarget.dataset.index;
    this.data.projectListPrm.splice(index,1);
    this.setData({
      [`projectListPrm`]:this.data.projectListPrm,
    })
    this.getProjectListTab();
  },
  //选择房屋建成年份
  bindCompletionYearDate(e) {
    this.setData({
      completionYear: e.detail.value
    })
  },
  /** 开卡 **/
  bankCardPage(e) {
    wx.showLoading({
      title: '加载中',
    })
    bankCardPage({
      entryId: this.data.entryId
    }).then((resApi) => {
      wx.hideLoading()
      console.log("开卡web", resApi)
      if (resApi.code == 200) {
        wx.navigateTo({
          url: '../webView/webView',
          success: function (res) {
            // 通过eventChannel向被打开页面传送数据
            res.eventChannel.emit('acceptDataFromOpenerPage', {
              data: resApi.data.gdUrl
            })
          }
        })
      } else {
        wx.showToast({
          title: resApi.errMsg,
          icon: 'none'
        })
      }
    })
  },
  //radio选择（划转方式、是否封屋顶、屋顶防水情况、是否有污染源、是否具备运维空间、是否符合变压器容量限制要求）
  radioChange(e) {
    let key = e.currentTarget.dataset.key;
    this.setData({
      [`${key}`]: e.detail.value,
    })
  },
  //下拉选择（方位角、并网电压等级）
  changeSelectVal(e) {
    let dval = e.detail.value
    let key = e.currentTarget.dataset.key
    let list = e.currentTarget.dataset.list
    this.setData({
      [key]: this.data[list][dval].dict_value,     
    })
    if(key == 'azimuthName'){ //方位角
      this.setData({
        azimuth: this.data[list][dval].dict_key,
      })
    }
  },
  //tab切换
  tabChange(e){
    this.setData({
      active:e.detail.index
    });
  },
  /** 获取组件、逆变器、并网箱、支架列表 **/
  getElectricPlanAll(callBack) {
    callBack = typeof callBack == 'function' ? callBack : function(){};
    getElectricPlanAll({
      partnerId: this.data.capitalId,//资方
    }).then((res) => {
      var AllComponentApiList = [];
      var converterApiList = [];
      var cagesApiList = [];
      var supportApiList = [];
      for (let i = 0; i < res.zjs.length; i++) {
        const element = res.zjs[i].columns;
        AllComponentApiList.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;
        supportApiList.push(element)
      } 
      // let componentApiList = AllComponentApiList.length ? AllComponentApiList.filter(itm => Number(itm.model) >= this.data.productZj) : []; //过滤大于等于productZj的组件列表
      this.setData({
        AllComponentApiList: AllComponentApiList,
        // componentApiList: componentApiList, //组件
        componentApiList: AllComponentApiList, //组件
        // [`componentList[${0}].material_model`]: componentApiList.length && (this.data.componentList[0].id == '') ? componentApiList[0].material_model : this.data.componentList[0].material_model,
        // [`componentList[${0}].model`]: componentApiList.length && (this.data.componentList[0].id == '') ? componentApiList[0].model : this.data.componentList[0].model,
        // [`componentList[${0}].id`]: componentApiList.length && (this.data.componentList[0].id == '') ? componentApiList[0].id : this.data.componentList[0].id,
        converterApiList: converterApiList, //逆变器
        cagesApiList: cagesApiList, //并网箱
        supportApiList: supportApiList, //支架
      })
      callBack();
    })
  },
  /** 获取方案类型和方案名称 **/
  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,
      })
      this.getElectricPlanAll(()=>{
        that.entryDetail();
      });//组件、逆变器列表数据
    })
  },
  /** 勘测暂存提交数据、设计审核自审暂存提交、勘测设计暂存提交 **/
  submitFrom(e) {
    var that = this
    var type = e.currentTarget.dataset.type
    var flag = e.currentTarget.dataset.flag
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    var composePlanList = []; // 标准方案或组合方案
    let projectListTab = JSON.parse(JSON.stringify(this.data.projectListTab))
    var itemList = []; //3组件 1逆变器 2并网箱  4支架
    var addEntryReqSurveyDetails = [];//多产品-图片
    var addEntryReqDesignDetails = [];//多产品-方案
    projectListTab.forEach(pItem=>{
      pItem.componentList.forEach(element => { //组件
        if (element.id) {
          var component = {}
          component.projectId = pItem.projectId;
          component.itemType = 3;
          component.itemId = element.id;
          component.num = element.num
          itemList.push(component)
        }
      });
      pItem.converterList.forEach(element => { //逆变器
        if (element.id) {
          var component = {}
          component.projectId = pItem.projectId;
          component.itemType = 1;
          component.itemId = element.id;
          component.num = element.num;
          itemList.push(component)
        }
      });
      pItem.cagesList.forEach(element => { //并网箱
        if (element.id) {
          var component = {}
          component.projectId = pItem.projectId;
          component.itemType = 2;
          component.itemId = element.id;
          component.num = element.num;
          itemList.push(component)
        }
      });
      pItem.supportList.forEach(element => { //支架
        if (element.id) {
          var support = {}
          support.projectId = pItem.projectId;
          support.itemType = 4;
          support.itemId = element.id;
          support.num = element.num;
          itemList.push(support)
        }
      });
      //图片
      for(let key in pItem.photo){
        pItem.photo[key] = pItem.photo[key].length > 0 ? pItem.photo[key].map(itm => itm.name).join(",") : ""
      }
      addEntryReqSurveyDetails.push({
        projectId: pItem.projectId,
        dipAngle: pItem.dipAngle, //组件倾角
        ...pItem.photo,
      });
      //方案
      let obj ={
        "projectId":pItem.projectId,  // 产品id
        ...pItem.plan,
        "designDrawings":pItem.photo['designDrawings'],//设计图纸
      }
      addEntryReqDesignDetails.push(obj);
    });
    //接口数据
    var userId = wx.getStorageSync('userId')
    var CustomerEntry = {
      type: type, //0:暂存 1:提交  3:初勘  4.初勘暂存
      composePlanLists: composePlanList.length > 0 ? composePlanList : [],
      itemList: itemList.length > 0 ? itemList : [],//设备列表
      projectList:this.data.projectListPrm,//产品列表
      addEntryReqSurveyDetails:addEntryReqSurveyDetails,//多产品-图片数据
      addEntryReqDesignDetails:addEntryReqDesignDetails,//多产品-方案数据
      // projectId: this.data.projectId, //项目ID
      // projectCode: this.data.projectCode, //产品编号
      // projectName: this.data.projectName, //产品名称
      // roofType: this.data.roofType, //屋顶类型
      //项目信息
      company: this.data.companyId, //项目公司id
      filingType: this.data.filingType ? this.data.filingType : "", //备案类型 1.农户备案 2.项目公司备案
      insuranceFlag: "1", // 保险购买情况:1.控制投放及续保 2.控制投放 3.其他
      leaseDate: this.data.leaseDate ? this.data.leaseDate : "", //预计投放日
      repaymentMethod: this.data.repaymentMethod, //划转方式
      province: this.data.provinceName ? this.data.provinceName : "", //省
      city: this.data.cityName ? this.data.cityName : "", //市
      area: this.data.areaName ? this.data.areaName : "", //区
      address: this.data.address ? this.data.address.trim() : "", //详细地址
      longitude: this.data.longitude ? this.data.longitude : "", //经度
      latitude: this.data.latitude ? this.data.latitude : "", //纬度
      //房屋信息
      mergeType: this.data.gridType,//并网方式
      boxTotalCount: this.data.boxTotalCount,//并网方式-本组电站个数
      boxGroupId: this.data.boxGroupId,//并网方式-汇流组id
      sealRoof: this.data.sealRoof, //是否封屋顶
      completionYear: this.data.completionYear, //房屋建成年份
      azimuth: this.data.azimuth, //方位角
      angle: this.data.azimuth!=1 && this.data.azimuth!=10 && this.data.azimuth!=11 && this.data.azimuth!=12 ? this.data.directionDeg : "", //方位角角度
      buildingHeight: this.data.buildingHeight ? this.data.buildingHeight : "", //建筑高度
      ewLength: this.data.ewLength ? this.data.ewLength : "", //东西长
      nsWide: this.data.nsWide ? this.data.nsWide : "", //南北宽
      // slopeGradient: this.data.roofType == '斜屋顶' ? this.data.slopeGradient : '', //屋面坡度
      // purlineInterval: this.data.roofType == '斜屋顶' ? this.data.purlineInterval : '', //檀条间距
      waterproof: this.data.waterproof, //屋顶防水情况
      sourcePollution: this.data.sourcePollution, //是否有污染源
      opsCondition: this.data.opsCondition, //是否具备运维空间
      voltageClasses: this.data.voltageClasses, //并网电压等级
      transformerCapacity: this.data.transformerCapacity, //变压器容量
      restrictFlag: this.data.restrictFlag, //是否符合变压器容量限制要求
      distance: this.data.distance ? this.data.distance : "", //配电箱至并网点距离
      // dipAngle: this.data.dipAngle ? this.data.dipAngle : "", //组件倾角
      roofArea: this.data.roofArea ? this.data.roofArea : "", //屋顶面积
      //房屋照片
      // fwImg1: this.data.photo.fwImg1.length > 0 ? this.data.photo.fwImg1.map(itm => itm.name).join(",") : "", //房屋整体图 
      // fwImg2: this.data.photo.fwImg2.length > 0 ? this.data.photo.fwImg2.map(itm => itm.name).join(",") : "", //房屋内部结构图 
      // fwImg3: this.data.photo.fwImg3.length > 0 ? this.data.photo.fwImg3.map(itm => itm.name).join(",") : "", //房屋屋顶东南侧图片
      // fwImg4: this.data.photo.fwImg4.length > 0 ? this.data.photo.fwImg4.map(itm => itm.name).join(",") : "", //房屋屋顶西南侧图片 
      // fwImg5: this.data.photo.fwImg5.length > 0 ? this.data.photo.fwImg5.map(itm => itm.name).join(",") : "", //遮阴物与房屋距离、高度
      // flyImgs: this.data.photo.flyImgs.length > 0 ? this.data.photo.flyImgs.map(itm => itm.name).join(",") : "", //无人机航拍图
      // roofPhotoOne: this.data.photo.roofPhotoOne.length > 0 ? this.data.photo.roofPhotoOne.map(itm => itm.name).join(",") : "", //安装区域整体照片
      // roofPhotoTwo: this.data.photo.roofPhotoTwo.length > 0 ? this.data.photo.roofPhotoTwo.map(itm => itm.name).join(",") : "", //安装区域东南角照片
      // roofPhotoThree: this.data.photo.roofPhotoThree.length > 0 ? this.data.photo.roofPhotoThree.map(itm => itm.name).join(",") : "", //安装区域西南角照片
      // roofPhotoFour: this.data.photo.roofPhotoFour.length > 0 ? this.data.photo.roofPhotoFour.map(itm => itm.name).join(",") : "", //安装区域正南照片
      // roofPhotoFive: this.data.photo.roofPhotoFive.length > 0 ? this.data.photo.roofPhotoFive.map(itm => itm.name).join(",") : "", //安装区域细节照片
      // roofPhotoFacade: this.data.photo.roofPhotoFacade.length > 0 ? this.data.photo.roofPhotoFacade.map(itm => itm.name).join(",") : "", //房屋内部结构照片;
      // roofPhotoInterior: this.data.photo.roofPhotoInterior.length > 0 ? this.data.photo.roofPhotoInterior.map(itm => itm.name).join(",") : "", //房屋内部环境照片;
      // detailSupplementOne: this.data.photo.detailSupplementOne.length > 0 ? this.data.photo.detailSupplementOne.map(itm => itm.name).join(",") : "", //逆变器、配电箱预安装位置照片
      // houseSupplementOne: this.data.photo.houseSupplementOne.length > 0 ? this.data.photo.houseSupplementOne.map(itm => itm.name).join(",") : "", //房屋其他障碍物照片
      // surveyVideo: this.data.photo.surveyVideo.length > 0 ? this.data.photo.surveyVideo.map(itm => itm.name).join(",") : "", //踏勘补充证明视频
      // surveyFiles: this.data.photo.surveyFiles.length > 0 ? this.data.photo.surveyFiles.map(itm => itm.name).join(",") : "", //踏勘记录表
      // houseOwnership: this.data.photo.houseOwnership.length > 0 ? this.data.photo.houseOwnership.map(itm => itm.name).join(",") : "", //房产证
      // vrRoofOne: this.data.photo.vrRoofOne.length > 0 ? this.data.photo.vrRoofOne.map(itm => itm.name).join(",") : "", //房屋整体图（VR全景）
      // vrRoofTwo: this.data.photo.vrRoofTwo.length > 0 ? this.data.photo.vrRoofTwo.map(itm => itm.name).join(",") : "", //房屋整体俯视图（VR）
      // vrRoofThree: this.data.photo.vrRoofThree.length > 0 ? this.data.photo.vrRoofThree.map(itm => itm.name).join(",") : "", //房屋内部结构图（VR）
      // vrRoofFour: this.data.photo.vrRoofFour.length > 0 ? this.data.photo.vrRoofFour.map(itm => itm.name).join(",") : "", //入户全景照片(VR)
      // houseOutlinePhoto: this.data.photo.houseOutlinePhoto.length > 0 ? this.data.photo.houseOutlinePhoto.map(itm => itm.name).join(",") : "", //房屋轮廓照片(VR)
      //方案信息
      schemeType: 1, //设计方案-1标准方案
      schemeRemarks: this.data.solutionRemark ? this.data.solutionRemark : "", //方案备注
      // designDrawings: this.data.photo.designDrawings.length > 0 ? this.data.photo.designDrawings.map(itm => itm.name).join(",") : "", //设计图纸,
      // zjpbImg: this.data.photo.zjpbImg.length > 0 ? this.data.photo.zjpbImg.map(itm => itm.name).join(",") : "", //组件排布图,
      // zjzxImg: this.data.photo.zjzxImg.length > 0 ? this.data.photo.zjzxImg.map(itm => itm.name).join(",") : "", //组件支架图,
      // zjcsImg: this.data.photo.zjcsImg.length > 0 ? this.data.photo.zjcsImg.map(itm => itm.name).join(",") : "", //组件接线图, 
      // zjhsImg: this.data.photo.zjhsImg.length > 0 ? this.data.photo.zjhsImg.map(itm => itm.name).join(",") : "", //电气图, 
      // 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 : "" : "",
      /**设计自审**/
      zsFlag: this.data.auditStatus ? this.data.auditStatus : "", //审核结果 1通过 2驳回
      nodeType: this.data.nodeType ? this.data.nodeType : "",//驳回节点 1勘测  2设计      
      zsAuditRemarks: this.data.auditRemarks ? this.data.auditRemarks : "",//审核意见

      windPressure: this.data.windPressure?this.data.windPressure:'', //风压
      snowPressure: this.data.snowPressure?this.data.snowPressure:'', //雪压
      pressureLevel: this.data.pressureLevel?this.data.pressureLevel:'', //风雪压等级
    }

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

    var data = {
      userId: userId,
      CustomerEntry: CustomerEntry,
    }
    console.log("submit", data,type,flag)
    // wx.hideLoading()
    // return
    //勘测设计-暂存、提交
    if(flag =='sj'){
      designCustomerEntry(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.msg || res.errMsg,
            icon: 'none'
          })
        }
      });
      return
    }
    //设计审核-设计自审-暂存、提交
    if(flag =='zs'){
      if(this.data.auditStatus =='1' || type =='0'){//审核通过或者暂存
        updateCustomerEntry(data).then(res=>{
          wx.hideLoading();
          if (res.code == 200) {
            wx.showToast({
              title: res.msg || "操作成功",
              icon: 'none',
              success: function () {
                setTimeout(function () {
                  //延时返回上一页面
                  wx.navigateBack()
                }, 1800) //延迟时间
              }
            })
          } else {
            wx.showToast({
              title: res.errMsg,
              icon: 'none'
            })
          }
        });
      }
      if(this.data.auditStatus =='2' && type =='1'){//审核驳回并且是保存
        if(!this.data.auditRemarks){
          wx.showToast({
            title: '请输入审核意见',
            icon: 'none'
          })
          return
        }      
        auditBack({
          userId: userId,
          id: this.data.id,
          zsAuditRemarks: that.data.auditRemarks,
          type: that.data.nodeType, //驳回节点：1.待勘测 2.待设计
        }).then((res) => {
          wx.hideLoading()
          if (res.code == 200) {
            wx.showToast({
              title: "操作成功",
              icon: 'none',
              success: function () {
                setTimeout(function () {
                  //延时返回上一页面
                  wx.navigateBack()
                }, 1800) //延迟时间
              }
            })
          } else {
            wx.showToast({
              title: res.errMsg,
              icon: 'none'
            })
          }
        })
      }
      return
    }
    //勘测提交设计
    if(type == '5'){
      surveyToDesign(data).then(res=>{
        wx.hideLoading();
        if (res.code == 200) {
          wx.showToast({
            title: res.msg || "操作成功",
            icon: 'none',
            success: function () {
              setTimeout(function () {
                //延时返回上一页面
                wx.navigateBack()
              }, 1800) //延迟时间
            }
          })
        } else {
          wx.showToast({
            title: res.errMsg,
            icon: 'none'
          })
        }
      });
      return
    }    
    //勘测暂存或提交审核
    saveOrEditCustomerEntry(data).then((res) => {
      wx.hideLoading()
      if (res.code == 200) {
        wx.showToast({
          title: type == '1' ? res.msg : "操作成功",
          icon: 'none',
          success: function () {
            setTimeout(function () {
              //延时返回上一页面
              wx.navigateBack()
            }, 1800) //延迟时间
          }
        })
      } else {
        wx.showToast({
          title: res.errMsg,
          icon: 'none'
        })
      }
    })
  },
  /** 取消 **/
  cancel(e) {
    wx.showModal({
      title: '提示',
      content: '确定取消？',
      complete: (res) => {
        if (res.cancel) {}
        if (res.confirm) {
          wx.navigateBack()
        }
      }
    })
  },
  /** 判断方位角方向 **/
  getDirection: function (rotate) {
    // 计算应偏移度数
    let that = this;
    var area = parseInt(rotate / 90)
    var detailArea = rotate % 90
    if (area == 0) {
      that.setData({
        areaTT: "西偏北",
        detailAreaTT: 90 - detailArea
      })
    } else if (area == 1) {
      that.setData({
        areaTT: "西偏南",
        detailAreaTT: detailArea
      })
    } else if (area == 2) {
      that.setData({
        areaTT: "东偏南",
        detailAreaTT: 90 - detailArea
      })
    } else {
      that.setData({
        areaTT: "东偏北",
        detailAreaTT: detailArea
      })
    }
    return that.data.areaTT + that.data.detailAreaTT;
  },
  /** 上传图片之前 **/
  beforeRead(e) {
    const water = e.currentTarget.dataset.water,
      that = this;
    const {
      callback
    } = e.detail;
    console.log("上传前", e);
    // callback(true);
    // return
    if (water == '水印') {
      let that = this;
      wx.getSystemInfoAsync({
        success(rep) {
          if (rep.platform == 'devtools') {
            callback(true);
          } else {
            callback(true);
            //指南针监听,手机拍摄
            wx.onCompassChange(function (res) {
              console.log("指针", res);
              var rotate = 360 - res.direction.toFixed(0)
              let direction = that.getDirection(rotate) + '°';
              that.setData({
                direction: direction
              });
            });
            setTimeout(() => {
              wx.stopCompass();
            }, 200);
          }
        }
      });
    } else {
      callback(true);
    }
  },
  /** 上传图片 **/
  afteruploadPhotoRead(e) {
    var that = this;
    const choseType = Array.isArray(e.detail.file) ? (e.detail.file[0].choseType || undefined) : (e.detail.file.choseType || undefined); //camera相机  album相册
    const water = e.currentTarget.dataset.water
    const name = e.currentTarget.dataset.name
    const pIndex = e.currentTarget.dataset.pindex
    console.log("上传后", this.data.direction, choseType, e);
    // 细节照片添加水印
    if (water == '水印') {
      if (!this.data.detail.tenant_name) {
        wx.showToast({
          title: '请输入业主姓名',
          icon: 'none'
        })
        return
      }
      if (!this.data.detail.mobile) {
        wx.showToast({
          title: '请输入业主联系电话',
          icon: 'none'
        })
        return
      }
      this.data.data.name = this.data.detail.tenant_name
      this.data.data.phone = this.data.detail.mobile
      if (choseType == 'camera') { //当从相机拍照时，图片添加水印
        this.getLocation(e)
        return
      }
    }
    //身份证明水印
    if (water == '身份证明水印') {
      const tempFilePath = e.detail.file[0].url; //图片路径
      const photoName = e.currentTarget.dataset.name; //图片名称
      utilAddWatermark2.addWatermark(tempFilePath, this.data).then((src) => {
        this.data.photo[photoName].push(src)
        this.setData({
          [`photo.${photoName}`]: this.data.photo[photoName]
        })
      });
      return;
    }
    //无水印上传
    if (Array.isArray(e.detail.file)) { //多张
      var count = 0;
      this.afteruploadPhotoReadS(e, count)
      return
    }
    const {
      file
    } = e.detail;
    wx.showLoading({
      title: '上传中',
    })
    wx.uploadFile({
      url: that.data.API_BASE_URL + 'common/weChat/uploadImage',
      filePath: file.url,
      name: 'file',
      complete: function (res) {
        console.log("上传图片", res)
        wx.hideLoading()
        if (res.statusCode == 200) {
          wx.showToast({
            title: '选择成功',
            icon: 'none',
          })
          var item = {
            url: "",
            name: "",
          }
          item.url = file.url;
          item.name = res.data;
          that.data.projectListTab[pIndex].photo[name].push(item)
          that.setData({
            [`projectListTab[${pIndex}].photo.${name}`]: that.data.projectListTab[pIndex].photo[name]
          })
        } else {
          wx.showToast({
            title: '选择失败',
            icon: 'error'
          })
        }
      }
    })
  },
  /** 上传多张图片递归 **/
  afteruploadPhotoReadS(e, count) {
    let ob = {
      name: '',
      url: '',
    }
    const name = e.currentTarget.dataset.name
    const pIndex = e.currentTarget.dataset.pindex
    wx.showLoading({
      title: '加载第' + (count + 1) + '张照片中',
      mask: true,
    })
    const element = e.detail.file[count];
    var that = this;
    wx.uploadFile({
      url: that.data.API_BASE_URL + 'common/weChat/uploadImage',
      filePath: element.url,
      name: 'file',
      success(res) {
        wx.hideLoading()
        if (res.statusCode == 200) {
          count = count + 1;
          ob.name = res.data
          ob.url = element.url
          console.log("图",that.data.projectListTab[pIndex],pIndex);
          that.data.projectListTab[pIndex].photo[name].push(ob);
          that.setData({
            [`projectListTab[${pIndex}].photo.${name}`]: that.data.projectListTab[pIndex].photo[name]
          })
          if (count == e.detail.file.length) {
            wx.showToast({
              title: '选择成功',
              icon: 'none'
            })
          } else {
            that.afteruploadPhotoReadS(e, count)
          }
        } else {
          wx.showToast({
            title: '选择失败',
            icon: 'error'
          })
        }
      }
    })
  },
  //获取用户当前地理位置后为照片添加水印
  getLocation(e) {
    if (this.data.customerAddress && this.data.imageCodeImg) { //有地址，有导航二维码图，直接绘制图片
      this.chooseImages(e);
      return;
    }
    utilGetLocation.getLocationAddress().then((res) => {
      res.res.data = res.res.data.slice(res.res.data.lastIndexOf('省') + 1)
      this.setData({
        customerAddress: res.res.data,
        canvasLongitude: res.resLocation.longitude,
        canvasLatitude: res.resLocation.latitude,
      });
      //获取小程序二维码
      let lonLat = res.resLocation.longitude + ',' + res.resLocation.latitude;
      createQrcode({
        content: lonLat
      }).then(ret => {
        // let codeImg ="data:image/png;base64," + ret;
        let codeImg = IMG_BASE_URL + ret;
        this.setData({
          imageCodeImg: codeImg
        });
        this.chooseImages(e)
      });
    })
  },
  //选择图片为图片添加水印
  async chooseImages(e) {
    const photoName = e.currentTarget.dataset.name; //图片名称
    const pIndex = e.currentTarget.dataset.pindex;
    const tempFilePath = e.detail.file.url || e.detail.file[0].url //图片路径
    const canvasWidth = wx.getSystemInfoSync().screenWidth;
    // 获取图片信息
    await wx.getImageInfo({
      src: tempFilePath,
    }).then(async res => {
      let watermarkScale = res.width / canvasWidth;
      this.setData({
        canvasHeight: Math.round(res.height / watermarkScale),
        canvasWidth: canvasWidth,
      })

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

    })
  },
  /** 删除图片 **/
  deleteImg(e) {
    const name = e.currentTarget.dataset.name
    const pIndex = e.currentTarget.dataset.pindex
    const index = (name != 'surveyFiles' && name != 'designDrawings') ? e.detail.index : e.currentTarget.dataset.index //删除图片的下标
    this.data.projectListTab[pIndex].photo[name].splice(index, 1);
    this.setData({
      [`projectListTab[${pIndex}].photo.${name}`]: this.data.projectListTab[pIndex].photo[name]
    })
  },
  /** 文件或图片上传选择-对话框 **/
  selectUplosd(e){
    var that = this;
    let name = e.currentTarget.dataset.name;
    let pIndex = e.currentTarget.dataset.pindex;
    let maxcount = e.currentTarget.dataset.maxcount;
    wx.showActionSheet({
      itemList: ['文件', '图片'],
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {//文件
            that.upload(e);
          } else if (res.tapIndex == 1) {//图片           
            wx.chooseMedia({
              count: maxcount - that.data.projectListTab[pIndex].photo[name].length,
              mediaType: ['image'],
              sourceType: ['album'],
              success: function (rep) { 
                if (Array.isArray(rep.tempFiles)) { //多张
                  var count = 0;
                  that.afteruploadPhotoReadFile(e, rep.tempFiles, count)
                  return
                }
                wx.showLoading({
                  title: '选择中',
                })
                wx.uploadFile({
                  url: API_BASE_URL + 'common/weChat/uploadImage',
                  filePath: rep.tempFiles[0].tempFilePath,
                  name: 'file',
                  complete: function (res) {
                    wx.hideLoading()
                    if (res.statusCode == 200) {
                      wx.showToast({
                        title: '选择成功',
                        icon: 'none',
                      })
                      var item = {
                        url: "",
                        name: "",
                      }
                      item.url = rep.tempFiles[0].tempFilePath;
                      item.name = res.data;
                      that.data.projectListTab[pIndex].photo[name].push(item)
                      that.setData({
                        [`projectListTab[${pIndex}].photo.${name}`]: that.data.projectListTab[pIndex].photo[name]
                      })
                    } else {
                      wx.showToast({
                        title: '选择失败',
                        icon: 'error'
                      })
                    }
                  }
                })
              },
              fail: function(){},
            });
          }
        }
      }
    });
  },
  /** 上传pdf或图片 **/
  upload(e) {
    var that = this;
    let name = e.currentTarget.dataset.name;
    let pIndex = e.currentTarget.dataset.pindex;
    let maxcount = e.currentTarget.dataset.maxcount;
    wx.chooseMessageFile({
      count: maxcount - this.data.projectListTab[pIndex].photo[name].length,
      type: 'all',
      success(res) {
        if (Array.isArray(res.tempFiles)) { //多张
          var count = 0;
          that.afteruploadPhotoReadFile(e, res.tempFiles, count, 'file')
          return
        }
        //获取文件后缀/jpg|png|jpeg|pdf|dwg
        let suffix = res.tempFiles[0].path.substring(res.tempFiles[0].path.lastIndexOf('.') + 1)
        // console.log(989898, name)
        if (suffix.search(/pdf|jpg|png|jpeg|doc|docx|xls|xlsx/) == -1&&name=='designDrawings') {
          wx.showToast({
            title: '文件格式不正确',
            icon: 'none'
          })
          return
        }else if(suffix.search(/jpg|png|jpeg|pdf/) == -1){         
          wx.showToast({
            title: '只能上传jpg、png、jpeg、pdf文件',
            icon: 'none'
          })
          return 
        }
        wx.showLoading({
          title: '选择中',
        })
        wx.uploadFile({
          // url: that.data.API_BASE_URL + 'common/weChat/uploadImage',
          url: that.data.API_BASE_URL + 'common/uploadFile_Name?fileName=' + res.tempFiles[0].name,
          filePath: res.tempFiles[0].path,
          name: 'file',
          complete: function (res) {
            wx.hideLoading()
            if (res.statusCode == 200) {
              wx.showToast({
                title: '选择成功',
                icon: 'none'
              })
              that.data.projectListTab[pIndex].photo[name].push({
                name: JSON.parse(res.data).path,
                url: IMG_BASE_URL + JSON.parse(res.data).path
              });
              that.setData({
                [`projectListTab[${pIndex}].photo.${name}`]: that.data.projectListTab[pIndex].photo[name]
              })
            } else {
              wx.showToast({
                title: '选择失败',
                icon: 'none'
              })
            }
          }
        })
      }
    })
  },
  /** 文件上传多张递归 **/
  afteruploadPhotoReadFile(e, file, count, type) {
    let ob = {
      name: '',
      url: '',
    }
    const name = e.currentTarget.dataset.name
    const pIndex = e.currentTarget.dataset.pindex
    wx.showLoading({
      title: '加载第' + (count + 1) + '张照片中',
      mask: true,
    })
    const element = file[count];
    var that = this;
    var url = ''
    if(type =='file'){
      //获取文件后缀
      let suffix = element.path.substring(element.path.lastIndexOf('.') + 1)      
      if (suffix.search(/pdf|jpg|png|jpeg|doc|docx|xls|xlsx/) == -1&&name=='designDrawings') {
        wx.showToast({
          title: '文件格式不正确',
          icon: 'none'
        })
        return
      }
      else if (suffix.search(/jpg|png|jpeg|pdf/) == -1 && name!='designDrawings') {
        wx.showToast({
          title: '只能上传jpg、png、jpeg、pdf文件',
          icon: 'none'
        })
        return
      }
      url = API_BASE_URL + 'common/uploadFile_Name?fileName='+ element.name
    }else{
      url = API_BASE_URL + 'common/weChat/uploadImage'
    }
    wx.uploadFile({
      url: url,
      filePath: type =='file'?element.path:element.tempFilePath,
      name: 'file',
      success(res) {
        wx.hideLoading()
        if (res.statusCode == 200) {          
          count = count + 1;
          ob.name = type =='file'?JSON.parse(res.data).path: res.data,
          ob.url = type =='file'?JSON.parse(res.data).path:element.tempFilePath
          that.data.projectListTab[pIndex].photo[name].push(ob);
          that.setData({
            [`projectListTab[${pIndex}].photo.${name}`]: that.data.projectListTab[pIndex].photo[name]
          })
          if (count == file.length) {
            wx.showToast({
              title: '选择成功',
              icon: 'none'
            })
          } else {
            that.afteruploadPhotoReadFile(e, file, count, type)
          }
        } else {
          wx.showToast({
            title: '选择失败',
            icon: 'error'
          })
        }
      }
    })
  },
  //选择标准方案类型
  bindPlanChange(e) {
    const pIndex = e.currentTarget.dataset.pindex;
    const index = e.detail.value;
    this.data.projectListTab[pIndex].plan.schemeTypeName = this.data.planList[index].name; //方案类型名称
    this.data.projectListTab[pIndex].plan.schemeTypeId = this.data.planList[index].id; //方案类型id
    this.data.projectListTab[pIndex].plan.schemeTypeIndex = index;
    this.data.projectListTab[pIndex].plan.id = "";
    this.data.projectListTab[pIndex].plan.schemeName = ""; //方案名称
    this.data.projectListTab[pIndex].plan.schemeId = ""; //方案名称Id
    this.setData({
      [`projectListTab[${pIndex}].plan`]: this.data.projectListTab[pIndex].plan,
    })
  },
  //选择标准方案名称
  bindPlanNameChange(e) {
    const pIndex = e.currentTarget.dataset.pindex;
    const index = e.detail.value;
    const schemeTypeId = this.data.projectListTab[pIndex].plan.schemeTypeId;
    if (!schemeTypeId) {
      wx.showToast({
        title: '请先选择标准方案类型',
        icon: 'none'
      })
      return
    }
    this.data.projectListTab[pIndex].plan.id = this.data.planList.find(itm=>itm.id == schemeTypeId).allPlan[index].id;
    this.data.projectListTab[pIndex].plan.schemeName = this.data.planList.find(itm=>itm.id == schemeTypeId).allPlan[index].name; //方案名称
    this.data.projectListTab[pIndex].plan.schemeId = this.data.planList.find(itm=>itm.id == schemeTypeId).allPlan[index].id; //方案名称Id
    this.setData({
      [`projectListTab[${pIndex}].plan`]: this.data.projectListTab[pIndex].plan,
    })

  },
  //选择组件
  bindComponentChange(e) {
    const pickerIndex = e.detail.value; //选择器选择第几个
    const index = e.currentTarget.dataset.index; //选择第几个
    const pIndex = e.currentTarget.dataset.pindex;
    var componentNum = 0
    var assemblySpecs = e.currentTarget.dataset.assemblyspecs;//默认组件值
    var componentApiList = this.data.componentApiList.filter(itm=>Number(itm.model) >= assemblySpecs);
    // console.log("componentApiList",componentApiList);
    // // return
    componentNum = this.data.projectListTab[pIndex].componentList[0].num * componentApiList[pickerIndex].model
    this.setData({
      [`projectListTab[${pIndex}].componentList[${index}].material_model`]: componentApiList[pickerIndex].material_model,
      [`projectListTab[${pIndex}].componentList[${index}].model`]: componentApiList[pickerIndex].model,
      [`projectListTab[${pIndex}].componentList[${index}].id`]: componentApiList[pickerIndex].id,
      [`projectListTab[${pIndex}].componentNum`]: (componentNum / 1000).toFixed(3)
    })
  },
  //选择逆变器
  bindConverterChange(e) {
    const pickerIndex = e.detail.value; //选择器选择第几个
    const index = e.currentTarget.dataset.index; //选择第几个
    const pIndex = e.currentTarget.dataset.pindex;
    this.setData({
      [`projectListTab[${pIndex}].converterList[${index}].material_model`]: this.data.converterApiList[pickerIndex].material_model,
      [`projectListTab[${pIndex}].converterList[${index}].model`]: this.data.converterApiList[pickerIndex].model,
      [`projectListTab[${pIndex}].converterList[${index}].id`]: this.data.converterApiList[pickerIndex].id,
    })
  },
  //选择并网箱
  bindCagesChange(e) {
    const pickerIndex = e.detail.value; //选择器选择第几个
    const index = e.currentTarget.dataset.index; //选择第几个
    const pIndex = e.currentTarget.dataset.pindex;
    this.setData({
      [`projectListTab[${pIndex}].cagesList[${index}].model`]: this.data.cagesApiList[pickerIndex].model,
      [`projectListTab[${pIndex}].cagesList[${index}].id`]: this.data.cagesApiList[pickerIndex].id,
    })
  },
  //选择支架
  bindSupportChange(e) {
    const pickerIndex = e.detail.value; //选择器选择第几个
    const index = e.currentTarget.dataset.index; //选择第几个
    const pIndex = e.currentTarget.dataset.pindex;
    this.setData({
      [`projectListTab[${pIndex}].supportList[${index}].model`]: this.data.supportApiList[pickerIndex].model,
      [`projectListTab[${pIndex}].supportList[${index}].id`]: this.data.supportApiList[pickerIndex].id,
    })
  },
  /** 输入组件,逆变器,并网箱,支架的数量 */
  inputNum(e) {
    const pIndex = e.currentTarget.dataset.pindex;
    switch (e.currentTarget.dataset.type) {
      case "组件":
        this.setData({
          [`projectListTab[${pIndex}].componentList[${e.currentTarget.dataset.index}].num`]: e.detail.value,
        })
        var componentNum = 0
        for (let i = 0; i < this.data.projectListTab[pIndex].componentList.length; i++) {
          const element = this.data.projectListTab[pIndex].componentList[i];
          componentNum = element.num * element.model
        }
        this.setData({
          [`projectListTab[${pIndex}].componentNum`]: (componentNum / 1000).toFixed(3)
        })
        break;
      case "逆变器":
        this.setData({
          [`projectListTab[${pIndex}].converterList[${e.currentTarget.dataset.index}].num`]: e.detail.value,
        })
        break;
      case "并网箱":
        this.setData({
          [`projectListTab[${pIndex}].cagesList[${e.currentTarget.dataset.index}].num`]: e.detail.value,
        })
        break;
      case "支架":
        this.setData({
          [`projectListTab[${pIndex}].supportList[${e.currentTarget.dataset.index}].num`]: e.detail.value,
        })
        break;
    }
  },
  /** 新增型号 */
  add(e) {
    const pIndex = e.currentTarget.dataset.pindex;
    const list = {
      id: "",
      num: "",
      name: "",
    }
    switch (e.currentTarget.dataset.type) {
      case "组件":
        this.setData({
          [`projectListTab[${pIndex}].componentList`]:this.data.projectListTab[pIndex].componentList.concat(list)
        })
        break;
      case "逆变器":
        this.setData({
          [`projectListTab[${pIndex}].converterList`]:this.data.projectListTab[pIndex].converterList.concat(list)
        })
        break;
      case "并网箱":
        this.setData({
          [`projectListTab[${pIndex}].cagesList`]:this.data.projectListTab[pIndex].cagesList.concat(list)
        })
      case "支架":
        this.setData({
          [`projectListTab[${pIndex}].supportList`]:this.data.projectListTab[pIndex].supportList.concat(list)
        })
        break;
    }
  },
  /** 删除型号 */
  delete(e) {
    const pIndex = e.currentTarget.dataset.pindex;
    wx.showModal({
      title: '提示',
      content: '确定删除？',
      complete: (res) => {
        if (res.confirm) {
          switch (e.currentTarget.dataset.type) {
            case "组件":
              this.data.projectListTab[pIndex].componentList.splice(e.currentTarget.dataset.index, 1)
              this.setData({
                [`projectListTab[${pIndex}].componentList`]:this.data.projectListTab[pIndex].componentList
              })
              break;
            case "逆变器":
              this.data.projectListTab[pIndex].converterList.splice(e.currentTarget.dataset.index, 1)
              this.setData({
                [`projectListTab[${pIndex}].converterList`]:this.data.projectListTab[pIndex].converterList
              })
              break;
            case "并网箱":
              this.data.projectListTab[pIndex].cagesList.splice(e.currentTarget.dataset.index, 1)
              this.setData({
                [`projectListTab[${pIndex}].cagesList`]:this.data.projectListTab[pIndex].cagesList
              })
            case "支架":
              this.data.projectListTab[pIndex].supportList.splice(e.currentTarget.dataset.index, 1)
              this.setData({
                [`projectListTab[${pIndex}].supportList`]:this.data.projectListTab[pIndex].supportList
              })
              break;
          }
        }
      }
    })
  },
  //审核结果
  radioAuditResult(e) {
    this.setData({
    auditStatus: e.detail.value,
    })
  },
  //驳回节点
  radioRejectNode(e) {
    this.setData({
      nodeType: e.detail.value,
    })
  },  
  //打开pdf文件或者大图查看图片  
  openDocument(res) {
    let path = res.currentTarget.dataset.path
    if (path) {
      let suffix = path.substring(path.lastIndexOf('.') + 1) //获取文件后缀
      if(suffix=='mp4'){// 开始预览多媒体内容
        wx.previewMedia({ 
          sources: [{
            url :IMG_BASE_URL + path,
            type: 'video'
          }], // 需要预览的资源列表         
        });     
      }else if(suffix != 'jpg' && suffix != 'png' && suffix != 'gif' && suffix != 'jpeg') {
        wx.showLoading({
          title: '加载中',
        })
        wx.downloadFile({
          url: IMG_BASE_URL + path,
          complete: function (res) {
            wx.hideLoading()
            const filePath = res.tempFilePath
            wx.openDocument({
              filePath: filePath,
              fileType: suffix,
              showMenu: true,
              success: function (res) {}
            })
          }
        })
      }else{
        wx.previewImage({
          urls: [IMG_BASE_URL + path] // 需要预览的图片http链接列表
        })
      }
    }
  },  
  /** 填充所有图片 **/
  imageAll(e) {
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定选取图片后填充所有图片？',
      complete: (res) => {
        if (res.confirm) {
          wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            success(resImage) {
              wx.showLoading({
                title: '选择中',
              })
              wx.uploadFile({
                url: API_BASE_URL + 'common/weChat/uploadImage',
                filePath: resImage.tempFiles[0].tempFilePath,
                name: 'file',
                complete: function (res) {
                  wx.hideLoading()
                  if (res.statusCode == 200) {
                    for (let i in that.data.photo) {
                      let arr = [];
                      arr.push({
                        name: res.data,
                        url: IMG_BASE_URL + res.data
                      });
                      that.setData({
                        [`photo.${i}`]: arr,
                      })
                    }
                    wx.showToast({
                      title: '填充成功',
                      icon: 'none'
                    })
                  } else {
                    wx.showToast({
                      title: '填充失败',
                      icon: 'none'
                    })
                  }
                }
              })
            }
          })
        }
      }
    })
  },
  //选择预计投放日
  // bindLeaseDate(e) {
  //   this.setData({
  //     leaseDate: e.detail.value
  //   })
  // },
  /** 设计审核-不通过 **/
  noPass(e) {
    if (!this.data.auditOpinion) {
      wx.showToast({
        title: '请输入不通过审核意见',
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: "提交中"
    })
    appletsFailed({
      id: this.data.entryId,
      remarks: this.data.auditOpinion ? this.data.auditOpinion : "",
      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.msg || res.errMsg,
          icon: res.code
        })
      }
    })
  },
  /** 设计审核-通过 **/
  pass(ee) {
    var CustomerEntry = {
      id: this.data.id ? this.data.id : "",      
      examineRemarks: this.data.auditOpinion ? this.data.auditOpinion : "", //审核意见
    }
    console.log("CustomerEntry", CustomerEntry)
    // return
    var data = {
      userId: wx.getStorageSync('userId'),
      CustomerEntry: CustomerEntry,
    }

    wx.showLoading({
      title: "提交中"
    })
    appletsToExamine(
      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.msg || res.errMsg,
          icon: 'none'
        })
      }
    })
  },
})