<template>
  <div style="background: #f5f5f5" class="select-product-container">
    <div v-if="isFrom == 'sale'">
      <index-bar :key="renovate"></index-bar>
    </div>
    <div class="mt8"></div>
    <div v-for="(item, index) in chooseProducts" :key="index" class="mb20 bg-white mh15 pv15 pr15 pl10 radius5">
      <div class="flex mv10 align-items-c">
        <div class="fs14 w45">
          <van-tag plain type="danger">主险</van-tag>
        </div>
        <div class="fs15 c-gray-dark">{{ item.riskName }}</div>
      </div>
      <div class="pl45 flex mv10" v-for="(addtion, addIndex) in item.addtion" :key="addIndex">
        <div class="w50">
          <van-tag mark color="#DDF2EF" text-color="#E9332E">附加</van-tag>
        </div>
        <div class="fs13">{{ addtion.riskName }}</div>
      </div>
      <div class="flex fs15 justify-content-s align-items-b pb5">
        <div class="c-gray-darker fwb">首期保费（元）</div>
        <div class="yellow fwb">{{ item.prem.toFixed(2) | moneyFormat }}</div>
      </div>

      <div class="text-right pv5">
        <van-button v-if="isFrom == 'proposal'" size="small" round @click="editInsure(index,item)" class="mr5" type="danger">编辑</van-button>
        <van-button size="small" round @click="deteleInsure(index)" plain type="danger">删除</van-button>
      </div>
    </div>
    <div class="pt30 bg-white pb50">
      <div class="text-center m20 pv15 border-dotted c-gray-base bg-white" @click="addProduct" v-if="isShow == true">
        <span class="v-middle mr10" style="font-size:32px">+</span>添加产品
      </div>
    </div>

    <van-dialog v-model="active_show" :show-confirm-button="false" class="dialog_class" style="position: relative; overflow: visible;">
      <img class="icon_image" src="@/assets/images/kmh/close_bg.png" @click="active_show = false" />
      <div class="pl20 pr20 mt30">
        <!-- <div class="flex justify-content-c align-items-c">
          <img class="icon_title_image" src="@/assets/images/kmh/title_bg.png" />
        </div> -->
        <van-radio-group v-model="active_radio" style="align-items: center;padding-top: 140px">
          <van-radio name="1" class="radio_class ml50">
            <template #icon="props">
              <img class="img-icon radio_icon_image" :src="props.checked ? checkedUrl : noCheckedUrl" />
            </template>
            <div class="flex justify-content-fs align-items-c pl5">
              <img class="icon_select_image" src="@/assets/images/kmh/kmh_pro.png" />
            </div>
          </van-radio>
          <van-radio name="0" class="radio_class ml50">
            <template #icon="props">
              <img class="img-icon radio_icon_image" :src="props.checked ? checkedUrl : noCheckedUrl" />
            </template>
            <div class="flex justify-content-fs align-items-c pl5">
              <img class="icon_select_image" src="@/assets/images/kmh/normal_pro.png" />
            </div>
          </van-radio>
        </van-radio-group>
        <div class="flex justify-content-c align-items-c click_buttons">
          <img class="icon_click_image" src="@/assets/images/kmh/click_bg.png" @click="comfirmCheckActive('KMH')" />
          <!-- <img class="icon_click_image" src="@/assets/images/kmh/click_bg.png" @click="comfirmCheckActive('KMH')" /> -->
          <!--<van-button type="danger" class="dialog-comfirm-button" @click="comfirmCheckActive" v-no-more-click="1000">确认</van-button>-->
        </div>
      </div>
    </van-dialog>
    <van-dialog v-model="active_sqy_show" :show-confirm-button="false" style="overflow: visible;">
      <img class="icon_image_close" src="@/assets/images/kmh/close_bg.png" @click="active_sqy_show = false" />
      <div class="pl20 pr20 mt30 mb10">
        <div style="font-weight: bolder;padding-top: 20px;">请选择：</div>
        <van-radio-group v-model="active_sqy_radio" style="align-items: center;height: 350px;overflow-y: scroll;">
          <!-- 普通产品页面写死，不加入数据循环，目的解决默认选择普通产品 -->
          <van-radio name="0" class="radio_class ml60">
            <template #icon="props">
              <img class="img-icon radio_icon_image" :src="props.checked ? checkedUrl : noCheckedUrl" />
            </template>
            <div class="flex justify-content-fs align-items-c pl5">
              普通产品
            </div>
          </van-radio>
          <div v-for="(item, index) in activityList" :value="item.activityName" :key="index">
             <van-radio :name="index" class="radio_class ml60" v-if="index != 0">
                <template #icon="props">
                  <img class="img-icon radio_icon_image" :src="props.checked ? checkedUrl : noCheckedUrl" />
                </template>
                <div class="flex justify-content-fs align-items-c pl5">
                  {{item.activityName}}
                </div>
             </van-radio>
          </div>
          
          <!-- <van-radio name="2" class="radio_class ml60">
            <template #icon="props">
              <img class="img-icon radio_icon_image" :src="props.checked ? checkedUrl : noCheckedUrl" />
            </template>
            <div class="flex justify-content-fs align-items-c pl5">
              普通产品
            </div>
          </van-radio> -->
        </van-radio-group>
        <div class="flex justify-content-c align-items-c click_buttons">
          <!--<img class="icon_click_image" src="@/assets/images/kmh/click_bg.png" @click="comfirmCheckActive" />-->
          <!-- <van-button type="danger" class="dialog-comfirm-button" @click="comfirmCheckActive('SQY')" v-no-more-click="1000">确认</van-button> -->
          <van-button type="danger" class="dialog-comfirm-button" @click="comfirmCheckActive('PRODUCT')" v-no-more-click="1000">确认</van-button>
        </div>
      </div>
    </van-dialog>
    <div>
      <van-submit-bar button-text="下一步" @submit="nextStep" :disabled="nextStepFlag">
        <div class="fs15 ml15 fwb" style="flex:1" slot="default">
          合计：
          <span class="yellow mr5">￥{{ (total / 100).toFixed(2) | moneyFormat }}</span
          >元
        </div>
      </van-submit-bar>
    </div>
  </div>
</template>
<script>
import { Tag, SubmitBar, Icon, Dialog, RadioGroup, Radio, Image } from 'vant'
import FieldPicker from '@/components/ebiz/FieldPicker'
import { orderDetail, deleteOrderInfo, mainRiskList, mainRiskListProposal, calculatePremium } from '@/api/ebiz/common/common'
import { formatAllRisk } from '@/assets/js/utils/formatRiskList'
import { getDetail, deleteProposal } from '@/api/ebiz/proposal/proposal.js'
import { saveOrderActiveType,getActivityList } from '@/api/ebiz/sale/sale.js'
import utilsAge from '@/assets/js/utils/age'
import IndexBar from '@/components/ebiz/sale/IndexBar'
import riskRules from './risk-rules'

export default {
  name: 'selectedProduct',
  data() {
    return {
      chooseProducts: [],
      total: 0,
      nextStepFlag: true,
      isShow: true,
      appntDTO: {},
      isFrom: localStorage.isFrom,
      salePageFlag: '3',
      active_show: false,
      active_sqy_show:false,
      activityList:[
      ], //活动列表
      active_radio: '1',
      active_sqy_radio: '0',
      checkedUrl: require('@/assets/images/kmh/checked.png'),
      noCheckedUrl: require('@/assets/images/kmh/no_checked.png'),
      proposalOrderNo:'',
      renovate:'',//刷新子组件
      isCrossChannel: 0,   // 是否选择交叉渠道列表 0-否 1-是
    }
  },
  components: {
    [Tag.name]: Tag,
    [FieldPicker.name]: FieldPicker,
    [SubmitBar.name]: SubmitBar,
    [Icon.name]: Icon,
    [IndexBar.name]: IndexBar,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Image.name]: Image
  },
  mounted() {
    this.$jump({
      flag: 'navigation',
      extra: {
        title: '已选产品列表'
      },
    })
    if (localStorage.isFrom == 'sale') {
      // 清除活动标志
      // localStorage.removeItem('active_type')
      setTimeout(() => {
        // eslint-disable-next-line no-undef
        EWebBridge.webCallAppInJs('webview_left_button', {
          img: this.$assetsUrl + 'images/del-close-btn@3x.png',
          intercept: '1' //是否拦截原生返回事件 1是 其他否
        })
      }, 100)
    }
    //建议书--右上角为退出流程键(到建议书列表)×,并清除浏览记录
    if (localStorage.isFrom == 'proposal') {
      // eslint-disable-next-line no-undef
      setTimeout(() => {
        EWebBridge.webCallAppInJs('webview_right_button', {
          btns: [
            {
              img: this.$assetsUrl + 'images/del-close.png',
              route: { flag: '', extra: {} }
            }
          ]
        })
      }, 500)
      getDetail({
        orderNo: this.$route.query.proposalOrderNo
      }).then(res => {
        if (res.result == '0') {
          this.recommendType = res.content[0].recmdDTO?res.content[0].recmdDTO.recommendType:'';
          if (this.recommendType == '02' || this.recommendType == '11') {
            // 电投 团险渠道产品  均为交叉渠道销售
            this.isCrossChannel = '1';
          }
        }
      })
    }

    window.appCallBack = this.appCallBack
    document.body.style.backgroundColor = '#fff'
    this.getProductList()
    if (!this.$route.query.edit) {
      //如果不是编辑/导航条跳转进来的
      localStorage.setItem('salePageFlag', this.salePageFlag)
    } else if (this.$route.query.edit && !this.$route.query.salePageFlag) {
      //如果从保单列表点击编辑按钮进入
      this.salePageFlag = '3'
      localStorage.setItem('salePageFlag', this.salePageFlag)
    } else if (this.$route.query.salePageFlag) {
      //如果是从导航栏点击进入
      this.salePageFlag = localStorage.salePageFlag
    }

    // localStorage.orderNo = '19090510425500178912'
    // localStorage.saleInsuredPersonInfo = JSON.stringify({
    //   birthday: '2015-08-31',
    //   name: '张四四',
    //   sex: '0',
    //   occupationName: '工业自动化仪器仪表与装置修理工',
    //   relationToAppnt: 4,
    //   insuredId: '10',
    //   idType: '1',
    //   age: 4
    // })
    // localStorage.saleInsuredInfo = JSON.stringify({ birthday: '2012-08-31', name: '张三三', sex: '0', idType: '1', age: 7 })
  },
  beforeRouteLeave(to, from, next) {
    document.body.style.backgroundColor = ''
    next()
  },
  methods: {
    appCallBack(data) {
      if (data.trigger == 'left_button_click' && localStorage.isFrom == 'sale') {
        return this.$dialog
          .confirm({
            className: 'dialog-delete',
            title: '提示',
            message: '退出流程可能会丢失部分数据，是否确认退出？',
            cancelButtonColor: '#E9332E',
            confirmButtonColor: '#FFFFFF'
          })
          .then(() => {
            this.$jump({
              flag: 'h5',
              extra: {
                title: '电子投保单列表',
                forbidSwipeBack: 1, //当前页面禁止右滑返回
                url: location.origin + `/#/sale/list`
              },
              routerInfo: {
                path: `/sale/list`,
                type: '1'
              }
            })
          })
          .catch(() => {
            return
          })
      }else if (data.trigger == 'right_button_click' && localStorage.isFrom == 'proposal') {
        return this.$dialog
          .confirm({
            className: 'dialog-delete',
            title: '提示',
            message: '退出流程可能会丢失部分数据，是否确认退出？',
            cancelButtonColor: '#E9332E',
            confirmButtonColor: '#FFFFFF'
          })
          .then(() => {
            this.$jump({
              flag: 'h5',
              extra: {
                title: '建议书列表',
                forbidSwipeBack: 1, //当前页面禁止右滑返回
                url: location.origin + `/#/proposal/list`
              },
              routerInfo: {
                path: `/proposal/list`,
                type: '1'
              }
            })
        })
          .catch(() => {
            return
        })
      }
    },
    //获取已选产品列表
    async getProductList() {
      //建议书、电投详情
      let resultData
      let isProposal = localStorage.isFrom == 'proposal' ? true : false
      if (isProposal) {
        let saleInsuredPersonInfo = this.$CacheUtils.getLocItem('saleInsuredPersonInfo') && JSON.parse(this.$CacheUtils.getLocItem('saleInsuredPersonInfo'))

        let insuredId
        if (saleInsuredPersonInfo && saleInsuredPersonInfo.insuredId) {
          insuredId = saleInsuredPersonInfo.insuredId
        }
        this.$toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          loadingType: 'spinner',
          message: '加载中……'
        })
        if (this.$route.query.proposalOrderNo) {
          this.$CacheUtils.setLocItem('proposalNo',this.$route.query.proposalOrderNo)
          this.proposalOrderNo = this.$route.query.proposalOrderNo
        }
        let pOrderNo = this.proposalOrderNo?this.proposalOrderNo:this.$CacheUtils.getLocItem('proposalNo')
        console.log(pOrderNo,'pOrderNo')
        resultData = await getDetail({
          orderNo: pOrderNo,
          isMerge: '1',
          orderType: 'proposalInsuredInfo',
          orderDTO: { insuredDTOs: [{ insuredId: insuredId }] }
        })
      } else {
        this.$toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          loadingType: 'spinner',
          message: '加载中……'
        })
        resultData = await orderDetail({ orderNo: this.$route.query.orderNo, isMerge: '1' })
      }
      if (resultData.result == 0) {
        if( resultData.orderDTO ) {
          //判断是否显示风险测评tab
         this.renovate = new Date().getTime()
        }
        let riskDTOLst
        if (isProposal) {
          this.$CacheUtils.setLocItem('saleInsuredInfo',JSON.stringify(resultData.content[0].appntDTO))//存储投保人信息
          this.appntDTO = resultData.content[0].appntDTO
          resultData = resultData.content[0]
          riskDTOLst = resultData.insuredDTOs && resultData.insuredDTOs[0] && resultData.insuredDTOs[0].riskDTOLst
          this.total =
            resultData.insuredDTOs && resultData.insuredDTOs.length > 0 ? Number(resultData.insuredDTOs[0] && resultData.insuredDTOs[0].totalPrem) * 100 : 0
        } else {
          this.appntDTO = resultData.orderDTO.appntDTO
          //总保费
          this.total = resultData.orderDTO.orderInfoDTO.orderAmount * 100
          //险种数据格式化
          riskDTOLst = resultData.orderDTO.insuredDTOs[0].riskDTOLst
        }
        this.$CacheUtils.setLocItem('appntDTO',JSON.stringify(this.appntDTO))

        if (!riskDTOLst) riskDTOLst = []

        this.$utils.intLocalStorage(resultData, isProposal)

        this.chooseProducts = formatAllRisk(riskDTOLst)
        if (riskDTOLst.length > 0) {
          this.nextStepFlag = false
        }
        if (!isProposal) {
          if (this.chooseProducts.length > 0) {
            if (this.chooseProducts[0].mainRiskCode == 'GFRS_M0026' && this.chooseProducts.length == 1) {
              this.isShow = true
            } else {
              this.isShow = false
            }
          } else {
            this.isShow = true
          }
        }
        this.$toast.clear()
      } else {
        this.$toast(resultData.resultMessage)
      }
    },
    //删除已选产品列表
    deteleInsure(index) {
      Dialog.confirm({
        className: 'dialog-delete',
        title: '提示',
        message: '您确认要删除该产品信息吗?',
        cancelButtonColor: '#E9332E',
        confirmButtonColor: '#FFFFFF'
      })
        .then(() => {
          this.delProduct(index)
          this.isShow = true
        })
        .catch(() => {
          /*this.$toast('删除失败！')*/
        })
    },
    async delProduct(index) {
      let isProposal = localStorage.isFrom == 'proposal' ? true : false
      let resultData = ''

      if (isProposal) {
        resultData = await deleteProposal({
          orderDTO: {
            orderInfoDTO: {
              orderNo: this.$route.query.proposalOrderNo
            },
            insuredDTOs: [
              {
                riskDTOLst: [
                  {
                    insuanceId: this.chooseProducts[index].insuanceId
                  }
                ]
              }
            ]
          },
          type: '3'
        })
      } else {
        resultData = await deleteOrderInfo({
          orderType: 'RISK_ORDER',
          id: this.chooseProducts[index].insuanceId,
          orderDTO: {
            orderInfoDTO: {
              orderNo: this.$route.query.orderNo
            }
          }
        })
      }

      if (resultData.result == 0) {
        this.getProductList()
      } else {
        this.$toast(resultData.resultMessage)
      }
    },
    //获取主险列表--普通产品
    async getMainRiskList(riskProductCode) {
      let mainRiskCodes = localStorage.mainRiskCodes && JSON.parse(localStorage.mainRiskCodes)
      let mainListDate = { platform: 'app' }
      switch (this.isFrom) {
        case 'proposal':
          mainListDate.platform = 'proposal'
          break
        case 'sale':
          mainListDate.platform = 'app'
          break
      }
      if (this.isCrossChannel == '1') {
        mainListDate.platform = 'cross'
      }
      let resultData
      if(this.isFrom == 'proposal'){
        resultData = await mainRiskListProposal(mainListDate)
      }else{
        resultData = await mainRiskList(mainListDate)
      }
      if (resultData.result == 0) {
        if (resultData.mainRiskDTOS && resultData.mainRiskDTOS.length > 0){
          resultData.mainRiskDTOS.forEach(item=>{
            if (item.riskProductCode == riskProductCode) {
              this.result = item
            }
          })
          this.addMainRisk()
        }
      }
    },
    //储存主险
    async addMainRisk() {
      localStorage.setItem('isTrial', '1')
      let riskProductCode = this.result.riskProductCode
      let resultData = await calculatePremium({ productCodes: [riskProductCode], platform: 'app', type: '1' })
      if (resultData.result == 0) {
        resultData = resultData.trialDTOS[0]
        localStorage.isTrial = resultData.productTrialInfoDTO.productTrialYearDTOS != null ? '0' : '1'
        localStorage.hint = resultData.hint
        if (resultData.productTrialInfoDTO.dutyGroup != null) {
          resultData.productTrialInfoDTO.dutyGroup.map(item => {
            if (item.dutyName == '意外身故/伤残保险金') {
              item.defaultDutyAmt = item.minDutyAmt
            }
          })
        }

        if (resultData.productTrialInfoDTO.ruleExpression) {
          let ruleExpression = localStorage.ruleExpression ? JSON.parse(localStorage.ruleExpression) : {}
          ruleExpression[resultData.productCode] = resultData.productTrialInfoDTO.ruleExpression
          localStorage.ruleExpression = JSON.stringify(ruleExpression)
        }

        /********start 主险选择限制 start******/

        // 检验投被人关系  惠企保特殊校验
        if (riskProductCode == 'GFRS_M0040') {
          if (riskRules.relationLimit(resultData, JSON.parse(this.$CacheUtils.getLocItem('saleInsuredPersonInfo')).relationToAppnt, this)) {
            return
          }
        }
        // 检验投被人关系  国富人寿特定疾病药品费用医疗保险特殊校验
        if (riskProductCode == 'GFRS_M0045') {
          if (riskRules.relationCommonLimit(resultData, JSON.parse(this.$CacheUtils.getLocItem('saleInsuredPersonInfo')).relationToAppnt, this)) {
            return
          }
        }

        if (riskRules.ageLimit(resultData, this, null,riskProductCode)) {
          return
        }

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

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

        let flagPermission = await riskRules.getProductSellPermissionList(resultData.productCode, this,this.isCrossChannel)
        if (flagPermission.flag && localStorage.isFrom != 'proposal') {
          //校验该代理人是否有该产品的售卖权限
          return this.$toast(flagPermission.resultMessage)
        }
        let flagCompany = await riskRules.checkCompany(resultData.productCode, JSON.parse(this.$CacheUtils.getLocItem('saleInsuredInfo')).workcompany,  JSON.parse(this.$CacheUtils.getLocItem('saleInsuredInfo')).isAsync,this)
        if (flagCompany && localStorage.isFrom != 'proposal') {
          //校验该投保人的工作单位是否能够投保该产品
          return this.$toast('该投保人工作单位不能投保该产品')
        }
        /********end 主险选择限制 end******/

        //保存附加险
        localStorage.addtionRiskLst = JSON.stringify(resultData.productTrialInfoDTO.addtionRiskLst)
        localStorage.isAutoPay = resultData.isAutoPay
        localStorage.isRenew = resultData.isRenew
        localStorage.isForceRenew = resultData.isForceRenew
        localStorage.isRelated = resultData.isRelated

        let calFactorLst = this.getFactorList(resultData)
        let productTrialYearDTOS = resultData.productTrialInfoDTO.productTrialYearDTOS != null ? resultData.productTrialInfoDTO.productTrialYearDTOS : null
        let hasAddtionRisk = (resultData.productTrialInfoDTO.addtionRiskLst != null && resultData.productTrialInfoDTO.addtionRiskLst.length) ? true : false
        let currentProductInfo = localStorage.isTrial == '1' ? {
          isCrossChannel:this.isCrossChannel,
          calFactorLst,
          hasAddtionRisk,
          isMainRisk: 0,
          hint: resultData.hint,
          riskType: resultData.riskType,
          riskName: this.result.riskName,
          productCode: this.result.riskProductCode,
          mainRiskCode: this.result.riskProductCode,
          documentDTOS: resultData.productTrialInfoDTO.documentDTOS,
          influences: resultData.productTrialInfoDTO.influences,
          isRemit: resultData.productTrialInfoDTO.isRemit,
          hasPredictTransferPrem: resultData.productTrialInfoDTO.hasPredictTransferPrem, //建议书使用 是否展示预计转入保费
          predictTransferPrem: null //建议书使用  预计转入保费字段
        } : {
          isCrossChannel:this.isCrossChannel,
          productTrialYearDTOS,
          calFactorLst,
          hasAddtionRisk,
          isMainRisk: 0,
          hint: resultData.hint,
          riskType: resultData.riskType,
          riskName: this.result.riskName,
          productCode: this.result.riskProductCode,
          mainRiskCode: this.result.riskProductCode,
          documentDTOS: resultData.productTrialInfoDTO.documentDTOS,
          influences: resultData.productTrialInfoDTO.influences,
          isRemit: resultData.productTrialInfoDTO.isRemit,
          hasPredictTransferPrem: resultData.productTrialInfoDTO.hasPredictTransferPrem, //建议书使用 是否展示预计转入保费
          predictTransferPrem: null //建议书使用  预计转入保费字段
        }

        //构建险种数组
        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(this.thisEditIndex,this.thisEditData)
      }
    },
    //构建险种因子列表
    getFactorList(resultData) {
      let productTrialInfoDTO = resultData.productTrialInfoDTO
      console.log(productTrialInfoDTO, 'wode')
      let calFactorLst = resultData.productTrialInfoDTO.calFactorLst
      console.log('calFactorLst', calFactorLst)

      calFactorLst.forEach(item => {
        item['isMainRisk'] = 0
        item.columns = []
        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 if(item.code == 'pensionAge'){
                //养老保险金领取年龄
                item[item.code] = factor[item.code]
                item['sex'] = factor.sex
              }else {
                item[item.code] = factor[item.code]
              }
            }
            let itemColumns = { text: factor.showContent, value: factor[item.code], flag: factor[item.code + 'Flag'],sex:factor.sex}
            if (factor.medical !== undefined) {
              itemColumns.medical = factor.medical
            }
            item.columns.push(itemColumns)
          })
        } else if (item.type == 1) {
          //按年龄选择
          if (productTrialInfoDTO[item.code] != null) {
            productTrialInfoDTO[item.code].forEach(factor => {
              // item = Object.assign(item, factor)
              if(JSON.parse(this.$CacheUtils.getLocItem('saleInsuredPersonInfo')).insuredAge >= Number(factor.minAge) && JSON.parse(this.$CacheUtils.getLocItem('saleInsuredPersonInfo')).insuredAge <= Number(factor.maxAge)){
                // if(JSON.parse(this.$CacheUtils.getLocItem('saleInsuredPersonInfo')).age >= Number(factor.minAge) && JSON.parse(this.$CacheUtils.getLocItem('saleInsuredPersonInfo')).age <= Number(factor.maxAge)){
                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['rules'] = productTrialInfoDTO[item.code]
      })
      // // 用于意外险初始化保额
      // calFactorLst.map(item => {
      //   if (item.code == '"dutyGroup"') {
      //     item.rules.map(factor => {
      //       factor[0].defaultDutyAmt = 50
      //     })
      //   }
      // })
      return calFactorLst
    },
    jumpTo(index,data){
      let insuanceIdInfo = [{insuanceId: data.insuanceId, riskCode: data.riskCode, isMainRisk: 0 }]
      if(data.addtion && data.addtion.length != 0){
        data.addtion.forEach(item=>{
          insuanceIdInfo.push({
            insuanceId: item.insuanceId,
            riskCode: item.riskCode,
            isMainRisk: 1
          })
        })
      }
      let isProposal = localStorage.isFrom == 'proposal' ? true : false
      let thismyurl = ''
      if (this.$route.query.orderNo) {
        thismyurl = '/common/calculatePremium/?orderNo=' + this.$route.query.orderNo + '&insuanceIdInfo='+JSON.stringify(insuanceIdInfo)
      } else if (this.$route.query.proposalOrderNo) {
        thismyurl = '/common/calculatePremium?proposalOrderNo=' + this.$route.query.proposalOrderNo + '&insuanceIdInfo='+JSON.stringify(insuanceIdInfo)
      }
      if (isProposal) {
        window.localStorage.removeItem("editproposaladdrisk")
        this.$jump({
          flag: 'h5',
          extra: {
            url: location.origin + '/#' + thismyurl
          },
          routerInfo: {
            path: thismyurl
          }
        })
      }
    },
    //编辑
    editInsure(index,data){
      this.thisEditIndex = index
      this.thisEditData = data
      this.getMainRiskList(data.riskCode)
    },
    //下一步
    async nextStep() {
      if (!this.$route.query.salePageFlag) {
        //如果从保单列表编辑按钮进入
        localStorage.salePageFlag = '4'
      }
      console.log('this.chooseProducts', this.chooseProducts)
      if (this.chooseProducts.length == 0) {
        return this.$toast('请添加产品')
      }
      //重新校验该产品是否需要为协同单位
      let flagCompany = await riskRules.checkCompany(this.chooseProducts[0].riskCode, JSON.parse(this.$CacheUtils.getLocItem('saleInsuredInfo')).workcompany,  JSON.parse(this.$CacheUtils.getLocItem('saleInsuredInfo')).isAsync,this)
      if (flagCompany && localStorage.isFrom != 'proposal') {
        //校验该投保人的工作单位是否能够投保该产品
        return this.$toast('该投保人工作单位不能投保该产品')
      }
      //930折中方案，豁免险选择
      let oldAddRiskCodes = JSON.parse(localStorage.oldAddRiskCodes)
      if (oldAddRiskCodes.includes('DCRS_A0001')) {
        let chooseProducts = this.chooseProducts
        for (let i = 0; i < chooseProducts.length; i++) {
          if (chooseProducts[i].addtion.length > 0) {
            let remitRisk = chooseProducts[i].addtion.find(riskInfo => {
              return riskInfo.riskCode == 'DCRS_A0001'
            })
            if (!remitRisk) {
              this.$toast('请针对所有主险搭配豁免险！')
              return
            }
          } else {
            this.$toast('请针对所有主险搭配豁免险！')
            return
          }
        }
      }
      if (localStorage.isFrom == 'proposal') {
        let url = `/proposal/chooseInsuredPerson`
        if (this.$route.query.proposalOrderNo || this.$CacheUtils.getLocItem('proposalNo')) {
          let proposalOrderNo = this.$route.query.proposalOrderNo || this.$CacheUtils.getLocItem('proposalNo')
          url = `/proposal/chooseInsuredPerson?proposalOrderNo=${proposalOrderNo}`
        }
        let page = this.$route.query.proposalEdit == '1' ? '-1' : '-2'
        // this.$router.push({ path: url })
        this.$jump({
          flag: 'h5',
          extra: {
            url: location.origin + `/#${url}`
          },
          routerInfo: {
            path: url
          }
        })
      } else {
        let showFlag = this.showTipForDoubleRecord()
        if (showFlag) {
          this.$dialog
            .alert({
              message: '年龄≥60周岁投保人，如果投保一年期以上产品，请根据监管要求对销售过程进行录音录像！',
              confirmButtonColor: '#000000'
            })
            .then(() => {
              this.nextPageShow()
            })
        } else {
          this.nextPageShow()
        }
      }
    },
    //添加产品
    async addProduct() {
      // 1、处理判断活动  1、电投流程  2、后端接口提供弹出判断
      if (localStorage.isFrom == 'sale') {
        // let param = {
        //   activeType: 'KMH'
        // }
        // let resultData = await getOrderActiveInfo(param)
        // if (resultData.result == 0) {
        //   if (resultData.content.activeFlag != '1') {
        //     this.active_show = true
        //     return
        //   }
        //   //正常后续跳转流程
        // } else {
        //   this.$toast(resultData.resultMessage)
        //   return
        // }

        // // 司庆月活动
        // let paramSQY = {
        //   activeType: 'SQY'
        // }
        // let SQYResultData = await getOrderActiveInfo(paramSQY)
        // if (SQYResultData.result == 0) {
        //   if (SQYResultData.content.activeFlag != '1') {
        //     this.active_sqy_show = true
        //     return
        //   }
        //   //正常后续跳转流程
        // } else {
        //   this.$toast(SQYResultData.resultMessage)
        //   return
        // }
        
        let resultData = await getActivityList({})
        if (resultData.result == 0) {
          if (resultData.content.length) {
            this.activityList = [
                {
                  activityCode:'',
                  activityName:'普通产品',
                  isKmh:'',
                  cvaildateStr:'',
                }
              ]
              this.activityList = this.activityList.concat(resultData.content)
            if(resultData.content[0].isKmh == 'KMH'){
              this.active_show = true
            }else{
              this.active_sqy_show = true  //代表其他产品
            }           
            return
          }
          //正常后续跳转流程
        } else {
          this.$toast(resultData.resultMessage)
          return
        }
      }
      let thismyurl = ''
      if (this.$route.query.orderNo) {
        thismyurl = '?orderNo=' + this.$route.query.orderNo
      } else if (this.$route.query.proposalOrderNo) {
        thismyurl = '?proposalOrderNo=' + this.$route.query.proposalOrderNo
      }
      this.$jump({
        flag: 'h5',
        extra: {
          url: location.origin + '/#/common/mainRiskList' + thismyurl
        },
        routerInfo: {
          path: '/common/mainRiskList' + thismyurl
        }
      })
    },
    //选择活动还是普通产品，弹框确认按钮
    comfirmCheckActive(type) {
      let param
      if(type == 'KMH'){
        param = {
          orderDTO: {
            orderInfoDTO: {
              orderNo: this.$route.query.orderNo?this.$route.query.orderNo:this.$route.query.proposalOrderNo,
              activeType: this.activityList[this.active_radio].isKmh,
              activityCode: this.activityList[this.active_radio].activityCode,
              cvaliDate : this.activityList[this.active_radio].cvaildateStr
              // activeType: type=='KMH'?this.active_radio == '1'?'KMH':'':type=='SQY'?this.active_sqy_radio=='1'?'SQY':'':''
            }
          }
        }
      }else{
        param = {
          orderDTO: {
            orderInfoDTO: {
              orderNo: this.$route.query.orderNo?this.$route.query.orderNo:this.$route.query.proposalOrderNo,
              activeType: this.activityList[this.active_sqy_radio].isKmh,
              activityCode: this.activityList[this.active_sqy_radio].activityCode,
              cvaliDate : this.activityList[this.active_sqy_radio].cvaildateStr
              // activeType: type=='KMH'?this.active_radio == '1'?'KMH':'':type=='SQY'?this.active_sqy_radio=='1'?'SQY':'':''
            }
          }
        }
      }
      
      
      // 获取订单活动信息
      saveOrderActiveType(param).then(res => {
        this.active_show = false
        this.active_sqy_show = false
        // localStorage.setItem('active_type', type=='KMH'?this.active_radio == '1'?'KMH':'':type=='SQY'?this.active_sqy_radio=='1'?'SQY':'':'')
        // localStorage.setItem('active_type', this.activityList[this.active_sqy_radio].isKmh)
        if (res.result == 0) {
          let thismyurl = ''
          if (this.$route.query.orderNo) {
            thismyurl = '?orderNo=' + this.$route.query.orderNo
          } else if (this.$route.query.proposalOrderNo) {
            thismyurl = '?proposalOrderNo=' + this.$route.query.proposalOrderNo
          }
          this.$jump({
            flag: 'h5',
            extra: {
              url: location.origin + '/#/common/mainRiskList' + thismyurl
            },
            routerInfo: {
              path: '/common/mainRiskList' + thismyurl
            }
          })
        } else {
          this.$toast(res.resultMessage)
        }
      })
    },
    showTipForDoubleRecord() {
      //判断投保人年龄是否大于等于60岁
      let showFlag = false
      let age = this.appntDTO.birthday?utilsAge.getAge(this.appntDTO.birthday, new Date()):this.appntDTO.age
      if (age >= 60) {
        this.chooseProducts.map(item => {
          if (item.insuYearFlag == 'A' || (item.insuYearFlag == 'Y' && item.insuYear != '1')) {
            showFlag = true
            return true
          }
        })
      }
      return showFlag
    },
    nextPageShow() {
      let thismyurl = ''
      if (this.$route.query.orderNo) {
        thismyurl = '/sale/beneficiary?orderNo=' + this.$route.query.orderNo
      } else if (this.$route.query.proposalOrderNo) {
        thismyurl = '/sale/beneficiary?proposalOrderNo=' + this.$route.query.proposalOrderNo
      }
      localStorage.beneficiaryInfo = ''
      localStorage.fromAddBeneficiaryInfo = ''
      localStorage.removeItem('applicant')
      this.$jump({
        flag: 'h5',
        extra: {
          forbidSwipeBack: '1',
          url: location.origin + '/#' + thismyurl,
          needRefresh: '1'
        },
        routerInfo: {
          path: thismyurl
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/sass/variables.scss';
.select-product-container {
  .border-dotted {
    border: 1px dashed #999;
  }
  .van-submit-bar {
    border-top: 1px solid #dadada;
    box-sizing: border-box;
  }
  .van-submit-bar__text {
    text-align: left;
    padding-left: 20px;
  }
  /deep/.van-submit-bar__price {
    color: #f56123;
    font-weight: bold;
    font-size: 15px;
  }
  .radio_class {
    height: 47px;
    margin-bottom: 10px;
  }
  .dialog-comfirm-button {
    width: 167px;
    height: 36px;
    line-height: 36px;
    border-radius: 6px;
    text-align: center;
    vertical-align: center;
  }
  .icon_image {
    width: 19px;
    height: 19px;
    position: absolute;
    right: 15px;
    top: -30px;
  }
  .icon_image_close {
    width: 19px;
    height: 19px;
    position: absolute;
    right: 4px;
    top: -22px;
  }
  .icon_title_image {
    width: 50px;
    padding-top: 45px;
  }
  .icon_select_image {
    width: 167px;
    height: 47px;
  }
  .icon_click_image {
    width: 107px;
  }
  /deep/ .van-radio-group .van-radio__icon {
    height: 1.3em;
    line-height: 1.3em;
  }
  .radio_icon_image {
    width: 20px;
    height: 20px;
    padding-top: 3px;
  }
  .dialog_class {
    width: 330px;
    height: 335px;
    background: url('../../../assets/images/kmh/dialog_bg.png');
    background-size: 100% 100%;
  }
  .click_buttons {
    padding-top: 5px;
    padding-right: 0px;
    padding-bottom: 10px;
  }
}
</style>
