<template>
  <div class="addtion-risk-list-container pb50 pt10 redRadioCheckbox">
    <van-radio-group v-model="result">
      <van-cell-group>
        <van-cell v-for="(item, index) in list" clickable @click="result = item" :key="index" :class="{ hidden: item.isHidden }">
          <p slot="default" class="flex">
            <van-tag plain class="green fs12 mr10 bg-green-base h20">{{ item.productType }}</van-tag>
            <span class="c-gray-dark fs14 flex1">{{ item.riskName }}</span>
          </p>
          <van-radio checked-color="red" slot="right-icon" :name="item" />
        </van-cell>
      </van-cell-group>
    </van-radio-group>

    <van-button class="bottom-btn" type="danger" @click="nextStep">完成</van-button>
  </div>
</template>
<script>
import { Cell, CellGroup, Tag, Radio, RadioGroup } from 'vant'
import { calculatePremium } from '@/api/ebiz/common/common'
import riskRules from './risk-rules'
import { getAgentInfo } from '@/api/ebiz/my/my.js'

export default {
  name: 'addtionRiskList',
  components: {
    [Radio.name]: Radio,
    [RadioGroup.name]: RadioGroup,
    [CellGroup.name]: CellGroup,
    [Tag.name]: Tag,
    [Cell.name]: Cell
  },
  data() {
    return {
      branchTypeVal: '', //个险渠道G  中介渠道Z
      list: [],
      result: '',
      saleInsuredPersonInfo: null, //投保人信息
      mainRiskCode: ''
    }
  },
  mounted() {
    this.$jump({
      flag: 'navigation',
      extra: {
        title: '附加险选择列表'
      },
    })
    //获取投保人信息
    if (this.$CacheUtils.getLocItem('saleInsuredPersonInfo')) {
      this.saleInsuredPersonInfo = JSON.parse(this.$CacheUtils.getLocItem('saleInsuredPersonInfo'))
    }
    getAgentInfo({}).then(res => {
      // branchType N1、1代表个险渠道 和 N5、5 代表中介渠道，N代表内勤
      if (res.branchType == 'N1' || res.branchType == '1') {
        this.branchTypeVal = 'G'
      } else if (res.branchType == 'N5' || res.branchType == '5') {
        this.branchTypeVal = 'Z'
      }
    })

    //获取主产品code
    let chooseProducts = JSON.parse(window.localStorage.getItem('chooseProducts'))
    chooseProducts.forEach(item => {
      if (item.isMainRisk == '0') {
        this.mainRiskCode = item.mainRiskCode
      }
    })
    this.filterAddRisk()
  },
  methods: {
    //过滤已选附加险
    filterAddRisk() {
      if (localStorage.addtionRiskLst) {
        let addRiskCodes = localStorage.addRiskCodes && JSON.parse(localStorage.addRiskCodes)
        let addtionRiskLst = JSON.parse(localStorage.addtionRiskLst)
        let currentMainRiskInfo = this.getCurrentMainRiskInfo()
        addtionRiskLst.forEach(item => {
          if (addRiskCodes.includes(item.productCode)) {
            item.isHidden = 1
          } else {
            if (
              currentMainRiskInfo.mainRiskPayEndYearFlag == 'Y' &&
              currentMainRiskInfo.mainRiskPayEndYear == '1000' &&
              (item.productCode == 'GFRS_A0007' || item.productCode == 'GFRS_A0009'|| item.productCode == 'GFRS_A0010'|| item.productCode == 'GFRS_A0013' || item.productCode == 'GFRS_A0014'
                  || item.productCode == 'GFRS_A0015' || item.productCode == 'GFRS_A0016')
            ) {
              item.isHidden = 1
            }
          }
        })
        this.list = addtionRiskLst
      }
    },
    //下一步
    nextStep() {
      if (!this.result) {
        this.$toast('请选择产品')
        return
      }

      //添加附加险
      this.addAddtionRisk()
    },
    //储存附加险
    async addAddtionRisk() {
      let riskProductCode = this.result.productCode
      let resultData = await calculatePremium({ productCodes: [riskProductCode], platform: 'app', type: '1' })
      if (resultData.result == 0) {
        resultData = resultData.trialDTOS[0]
        localStorage.isAutoPay = localStorage.isAutoPay == '0' ? '0' : resultData.isAutoPay //自动垫交
        localStorage.isRenew = localStorage.isRenew == '0' ? '0' : resultData.isRenew //自动续保
        localStorage.isForceRenew = localStorage.isForceRenew == '0' ? '0' : resultData.isForceRenew //自动续保默认是否选中 0-是 1-否
        if (resultData.productTrialInfoDTO.ruleExpression) {
          let ruleExpression = localStorage.ruleExpression ? JSON.parse(localStorage.ruleExpression) : {}
          ruleExpression[resultData.productCode] = resultData.productTrialInfoDTO.ruleExpression
          localStorage.ruleExpression = JSON.stringify(ruleExpression)
          let ttThis = this
          for (let item of ruleExpression[resultData.productCode]) {
            let config = JSON.parse(item.ruleExpression)
            switch (config.eventType) {
              case 'loadFormat':
                let initFn = new Function(...config.funPar, config.funBody.join(''))
                let str = initFn.call(ttThis, resultData)
                if (str) {
                  return this.$toast(str)
                }
                break
              case 'checkMainRisk':
                let checkMainRiskFn = new Function(...config.funPar, config.funBody.join(''))
                let checkMainRiskStr = checkMainRiskFn.call(ttThis)
                if (checkMainRiskStr) {
                  return this.$toast(checkMainRiskStr)
                }
                break
              default:
                break
            }
            // if(config.eventType == 'loadFormat'){
            //     let initFn = new Function(...config.funPar, config.funBody.join(''))
            //     let str = initFn(resultData)
            //     if(str){
            //       return this.$toast(str)
            //     }
            // }
          }
        }
        // let checkMainRiskFn = function(){
        // config = {
        //   eventName: "CheckMainRiskPayEndYear",
        //   eventType: "checkMainRisk",
        //   funPar: [],
        //   funBody : [
        //   'let mainRisk = JSON.parse(localStorage.chooseProducts)[0];',
        //   'let mainRiskCode = mainRisk.productCode;',
        //   'let checkMianRishCode = {',
        //   '  "GFRS_M0023" : true',
        //   '};',
        //   'if(! checkMianRishCode[mainRiskCode]){',
        //   '   return ""',
        //   '};',
        //   ' ',
        //   'let payEndYearObj = mainRisk.calFactorLst.find(item =>{',
        //   '   return item.code == "payEndYear"',
        //   '});',
        //   'let payEndYearVal = payEndYearObj.payEndYear;',
        //   'let payEndYearFlag = payEndYearObj.payEndYearFlag;',
        //   'let payEnd = payEndYearVal+ payEndYearFlag;',
        //   'let age =  JSON.parse(localStorage.saleInsuredInfo).age;',
        //   'switch (payEndYearVal+payEndYearFlag){',
        //   '   case "15Y":',
        //   '     if(age-0 > 55){',
        //   '       return "当前投保人年龄无法在保险期间为15年交时，添加当前附加险";',
        //   '     };',
        //   '     break;',
        //   '   case "20Y":',
        //   '     if(age-0 > 50){',
        //   '       return "当前投保人年龄无法在保险期间为20年交时，添加当前附加险";',
        //   '     };',
        //   '     break;',
        //   '}'
        //   ]
        // }
        // switch (payEndYearVal+payEndYearFlag){
        //   case "15Y":
        //     if(age-0 > 55){
        //       return "当前投保人年龄无法在保险期间为15年交时，添加当前附加险";
        //     }
        //     break;
        //   case "20Y":
        //     if(age-0 > 50){
        //       return "当前投保人年龄无法在保险期间为20年交时，添加当前附加险";
        //     }
        //     break;
        // }

        /********start 附加险选择限制 start******/
        //判断被保 八桂D
       /* let mainRisk = JSON.parse(this.$CacheUtils.getLocItem('chooseProducts'))[0];
        let mainRiskCode = mainRisk.productCode;
        let addRiskCodes = localStorage.addRiskCodes && JSON.parse(localStorage.addRiskCodes)
        if(mainRiskCode =='GFRS_M0044'||mainRiskCode =='GFRS_M0051'){
          if(this.result.productCode=='GFRS_A0010'&&(addRiskCodes.length==0||addRiskCodes[0]=='GFRS_A0010')){
            this.$toast('当前未投保其他长险附加险，不可附加该险种！')
            return true
          }
        }*/
        //豁免险与其他附加险年龄险种
        if (resultData.productTrialInfoDTO.isRemit == '0' && resultData.productTrialInfoDTO.remitType == '0') {
          if (riskRules.ageLimit(resultData, this, 1)) {
            return
          }
        } else {
          if (riskRules.ageLimit(resultData, this)) {
            return
          }
        }

        if (riskRules.medicalLimit(resultData, this)) {
          return
        }

        if (riskRules.healthGradeLimit(resultData, this)) {
          return
        }
        // if (riskRules.lifeGradeLimit(resultData, this)) {
        //   return
        // }

        if (this.remitLimit(resultData)) {
          return
        }

        //validateAppntFlag 0-职业寿险等级需校验主合同的投保人；1-职业寿险等级无需校验主合同的投保人
        if (resultData.productInsuredDTO.validateAppntFlag == '0') {
          //校验主合同投保人寿险职业等级
          if (riskRules.lifeGradeLimitForBaby(resultData, this)) {
            return
          }
        } else {
          //校验主合同的被保险人寿险职业等级
          console.log(1111, resultData)
          if (riskRules.lifeGradeLimit(resultData, this)) {
            return
          }
        }

        /********end 附加险选择限制 end******/

        let calFactorLst = this.getFactorList(resultData)
        let currentProductInfo = {
          calFactorLst,
          isMainRisk: 1,
          hint: resultData.hint,
          riskType: resultData.riskType,
          riskName: this.result.riskName,
          productCode: this.result.productCode,
          documentDTOS: resultData.productTrialInfoDTO.documentDTOS,
          isRemit: resultData.productTrialInfoDTO.isRemit,
          remitType: resultData.productTrialInfoDTO.remitType
        }
        // 这个规则统一用后端配置的规则表达式，目前先注释掉
        /******八桂D中介渠道校验短险规则*******/
        // let risks = JSON.parse(localStorage.chooseProducts);
        // let checkRisk = true;
        // if(risks[0].productCode =="GFRS_M0051"||risks[0].productCode == 'GFRS_M0044') {
        //   if(this.result.productCode=="GFRS_A0010"){
        //     for (let i = 1; i < risks.length; i++) {
        //       for(let j = 0; j < risks[i].calFactorLst.length; j++){
        //         if (risks[i].calFactorLst[j].code=== 'insuYear') {
        //           if (((risks[i].calFactorLst[j].insuYearFlag == 'Y' && risks[i].calFactorLst[j].insuYear > 1) || risks[i].calFactorLst[j].insuYearFlag == 'A')
        //           &&risks[i].productCode!='GFRS_A0009') {
        //             checkRisk=false;
        //           }
        //         }
        //       }
        //     }
        //     if(checkRisk){
        //       this.$toast('当前未投保其他长险附加险，不可附加该险种！')
        //       return true
        //     }
        //   }
        // }
           /*"let risks = JSON.parse(localStorage.chooseProducts);",
           "let checkRisk = true;",
           "for (let i = 1; i < risks.length; i++) {",
            "for(let j = 0; j < risks.calFactorLst.length; j++){",
             "if (risks.calFactorLst[j].code === \"insuYear\") {",
            "if ((risks.calFactorLst[j].insuYearFlag == \"Y\" && risks.calFactorLst[j].insuYear > 1) || risks.calFactorLst[j].insuYearFlag == \"A\") {",
            "checkRisk=false;",
                 "}",
                "}",
                "}",
                "}",
             "if(checkRisk){",
                "return \"当前未投保其他长险附加险，不可附加该险种！\";",
                "}",*/

        //构建险种数组
        let productsData
        if (localStorage.chooseProducts) {
          productsData = JSON.parse(localStorage.chooseProducts)
          productsData.push(currentProductInfo)
        } else {
          productsData = [currentProductInfo]
        }
        productsData = this.$utils.unrepeatObj(productsData, 'productCode') //产品数组去重,跳转试算页面未成功重复添加同一产品的情况
        localStorage.chooseProducts = JSON.stringify(productsData)
        this.jumpTo()
      } else {
        this.$toast(resultData.resultMessage)
      }
    },
    //构建险种因子列表
    getFactorList(resultData) {
      let productTrialInfoDTO = resultData.productTrialInfoDTO
      let calFactorLst = resultData.productTrialInfoDTO.calFactorLst
      calFactorLst.forEach(item => {
        item['isMainRisk'] = 1
        item.columns = []
        if (!productTrialInfoDTO[item.code]) return
        if (item.type == 0) {
          //1、type=0 select 2、type=1 input+stepper
          productTrialInfoDTO[item.code].forEach(factor => {
            if (factor.defaultValue == 0) {
              item.showContent = factor.showContent
              if (factor[item.code + 'Flag'] != undefined) {
                item[item.code] = factor[item.code]
                item[item.code + 'Flag'] = factor[item.code + 'Flag']
                item.hasFlag = '1'
              } else {
                item[item.code] = factor[item.code]
                item['amt'] = factor['amt']
              }
            }
            let itemColumns = { text: factor.showContent, value: factor[item.code], flag: factor[item.code + 'Flag'], amt: factor['amt'] }
            if (factor.medical !== undefined) {
              itemColumns.medical = factor.medical
            }
            item.columns.push(itemColumns)
          })
        } else if (item.type == 1) {
          //按年龄选择
          productTrialInfoDTO[item.code].forEach(factor => {
            item = Object.assign(item, factor)
          })
          if (item.code == 'inputPrem') {
            item['inputPrem'] = Number(item.minPrem) * Number(item.moneyUnit)
          } else {
            item['amt'] = Number(item.minAmt) * Number(item.moneyUnit)
            item['oldMaxAmt'] = item.maxAmt
          }
        }
        //规则储存
        item['rules'] = productTrialInfoDTO[item.code]
      })
      return calFactorLst
    },
    //豁免险影响
    remitLimit(resultData) {
      //isRemit 0是豁免险 1非豁免险  remitType 0投保人 1被保险人  relationToAppnt 投被关系
      let isRemit = resultData.productTrialInfoDTO.isRemit
      let currentMainRiskInfo = this.getCurrentMainRiskInfo()
      // 世纪无忧重疾(GFRS_M0046)交费至60/70周岁时，不可附加两全险(GFRS_A0011)
      if (resultData.productCode == 'GFRS_A0011' && this.mainRiskCode == 'GFRS_M0046') {
        if (currentMainRiskInfo.mainRiskPayEndYearFlag == 'A') {
          this.$toast('目前主险交费期间类型，不适合选取此款险种！')
          return true
        }
      }
      if (isRemit == 1) return false
      let remitType = resultData.productTrialInfoDTO.remitType
      let remitTypeLimit = resultData.productTrialInfoDTO.remitTypeLimit
      let relationToAppnt = this.saleInsuredPersonInfo.relationToAppnt
      // let currentMainRiskInfo = this.getCurrentMainRiskInfo()
      let productCode = resultData.productCode
      if (relationToAppnt == 1 && remitType == '0' && !remitTypeLimit) {
        this.$toast('投被同人不能选取此款险种！')
        return true
      }
      if (currentMainRiskInfo.mainRiskPayIntv == 0) {
        this.$toast('目前主险交费方式类型，不适合选取此款险种！')
        return true
      }
      if (currentMainRiskInfo.mainRiskPayEndYearFlag == 'A') {
        this.$toast('目前主险交费期间类型，不适合选取此款险种！')
        return true
      }
      // branchTypeVal: '', //个险渠道G  中介渠道Z
      //国富人寿附加投保人豁免保险费定期寿险（B款） GFRS_A0007
      //国富人寿附加豁免保险费重大疾病保险（B款）   GFRS_A0009
      //国富人寿鑫享年年终身寿险--只针对这款产品
      if (this.mainRiskCode == 'GFRS_M0036') {
        if (this.branchTypeVal == 'Z' && (productCode == 'GFRS_A0007' || productCode == 'GFRS_A0009'|| productCode == 'GFRS_A0010'||productCode == 'GFRS_A0013'|| productCode == 'GFRS_A0014')) {
          if (relationToAppnt == 1) {
            this.$toast('投被同人不能选取此款险种！')
            return true
          }
        }
      }

      return false
    },
    //获取主险的保险期间、交费方式
    getCurrentMainRiskInfo() {
      let mainRiskPayIntv, mainRiskPayEndYearFlag, mainRiskPayEndYear
      let chooseProducts = JSON.parse(localStorage.chooseProducts)
      chooseProducts[0].calFactorLst.forEach(item => {
        if (item.code == 'payIntv') {
          mainRiskPayIntv = item.payIntv
        }
        if (item.code == 'payEndYear') {
          mainRiskPayEndYearFlag = item.payEndYearFlag
          mainRiskPayEndYear = item.payEndYear
        }
      })
      return {
        mainRiskPayIntv,
        mainRiskPayEndYearFlag,
        mainRiskPayEndYear
      }
    },
    //页面跳转
    jumpTo() {
      this.$jump({
        flag: 'goBack',
        extra: {
          refresh: '1'
        },
        routerInfo: {
          type: 2,
          path: '/common/calculatePremium'
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.addtion-risk-list-container {
  .van-hairline--surround::after {
    border: none;
  }
}
</style>
