<template>
  <div class="calculate-premium-container pb50 pt10">
    <div class="bg-white ph10 pt10">
      <div class="flex justify-content-s align-items-c border-bottom pb10">
        <span class="mr10">{{ saleInsuredPersonInfo.name }}</span>
        <span class="mr10">{{ saleInsuredPersonInfo.sex == 0 ? '男' : '女' }}</span>
        <span class="mr10">{{ saleInsuredPersonInfo.age }}岁</span>
        <span class="mr10 flex1 van-ellipsis"> {{ saleInsuredPersonInfo.occupationName }}</span>
      </div>
    </div>
    <div v-for="(item, index) in chooseProducts" :key="index" class="ph10 bg-white">
      <div class="flex justify-content-s align-items-c border-bottom pv10">
        <van-tag type="primary" v-if="item.isMainRisk == 0" class="mr5 green" plain>主险</van-tag>
        <van-tag type="primary" v-else class="mr5 green" plain>附加险</van-tag>
        <span class="ml5 center fs13 flex1"> {{ item.riskName }} </span>
        <van-tag type="primary" v-if="item.isMainRisk == 0 && item.hasAddtionRisk" plain @click="selectAddtionRisk" class="green mr8">附</van-tag>
        <van-icon name="search" size="20" v-if="item.documentDTOS && item.documentDTOS.length > 0" @click="seeDocument(index)" class="green mr5" />
        <van-icon name="delete" size="22" @click="deleteRisk(index)" class="green" />
      </div>
      <!-- 险种条件-->
      <div v-if="item.isRemit == 1">
        <div v-for="(riskFactor, riskFactorIndex) in item.calFactorLst" :key="riskFactorIndex">
          <div class="flex justify-content-s pv10 border-bottom" v-if="riskFactor.type == 1">
            <div class="flex align-items-c">
              <span v-if="riskFactor.suffix" class="fs14"> {{ riskFactor.name + '(' + riskFactor.suffix + ')' }} </span>
              <span v-else class="fs14"> {{ riskFactor.name }} &nbsp;&nbsp; &nbsp;&nbsp;</span>
              <!-- {{riskFactorIndex}} -->
              <van-stepper
                v-model="defalutAmt"
                :min="riskFactor.minAmt || riskFactor.minPrem"
                :max="riskFactor.maxAmt || riskFactor.maxPrem"
                :show-plus="false"
                :show-minus="false"
                class="ml30"
                @change="stepperChange(defalutAmt,item.calFactorLst[riskFactorIndex].defaultValue, index, riskFactorIndex)"
                input-width="100"
                :integer="false"
              />
            </div>
          </div>
          <div
            class="flex justify-content-s pv10 border-bottom"
            v-if="riskFactor.type == 0"
            :class="{ hidden: riskFactor.code == 'payEndYear' && item.isHidden }"
          >
            <van-field
              v-model="riskFactor.showContent"
              readonly
              :label="riskFactor.name"
              right-icon="arrow"
              placeholder="请选择"
              @click="toSelect(index, riskFactorIndex, riskFactor.columns)"
            />
          </div>
          <div class="border-bottom" v-if="riskFactor.type == 3">
            <div class="pv12 border-bd">{{ riskFactor.name }}</div>
            <div class="duty">
              <div class="flex justify-content-s border-bd pv10 align-items-c" v-for="(dutyItem, dutyItemIndex) in riskFactor.rules" :key="dutyItemIndex">
                <span class="fs14 w100">{{ dutyItem.dutyName }}({{ dutyItem.suffix }})</span>
                <div class="flex">
                  <van-stepper
                    v-model="dutyItem.defaultDutyAmt"
                    :min="dutyItem.minDutyAmt"
                    :max="dutyItem.maxDutyAmt"
                    :show-plus="false"
                    :show-minus="false"
                    class="ml10 mr10"
                    @focus="focusStep"
                    @blur="blurStep"
                    @change="
                      dutyStepperChange(
                        item.calFactorLst[riskFactorIndex].rules[dutyItemIndex].defaultDutyAmt,
                        index,
                        riskFactorIndex,
                        dutyItemIndex,
                        dutyItem.necess,
                        dutyItem.minDutyAmt,
                        dutyItem.maxDutyAmt
                      )
                    "
                    input-width="200"
                    :integer="false"
                  />
                  <van-checkbox
                    v-model="dutyItem.necess"
                    :disabled="dutyItem.defaultValue == '0'"
                    shape="square"
                    @change="changeChecked(index, riskFactorIndex, dutyItemIndex)"
                  ></van-checkbox>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 豁免险条件 -->
      <div v-if="item.isRemit == 0">
        <div v-for="(riskFactor, riskFactorIndex) in item.calFactorLst" :key="riskFactorIndex">
          <div class="flex justify-content-s pv10 border-bottom">
            <div class="flex">
              <van-field v-if="riskFactor.type == 0" v-model="riskFactor.showContent" readonly :label="riskFactor.name" />
              <van-field v-if="riskFactor.type == 1" v-model="riskFactor.defaultValue" readonly :label="riskFactor.name + '(' + riskFactor.suffix + ')'" />
            </div>
          </div>
        </div>
      </div>
      <!-- 只有万能险且只有建议书才展示 -->
      <van-field class="pv10" v-if="item.hasPredictTransferPrem === '0'" v-model="item.predictTransferPrem" label="预计转入保费" placeholder="请输入" />
      <div class="flex justify-content-s pv10 border-bottom" v-if="isRelated && isFrom != 'proposal'">
        <van-field v-model="policyNo" clearable label="关联保单" name="关联保单号" maxlength="20" placeholder="请输入保单号/投保单号" />
      </div>
      <div class="flex justify-content-s pv10 border-bottom prem">
        <span
          style="font-weight:bold"
          v-if="(trialList.length > 0 && trialList[index].trialType == 0) || (trialList.length > 0 && trialList[index].trialType == 2)"
        >
          首期保费(元）：
        </span>
        <span style="font-weight:bold" v-else>
          保额(元）：
        </span>
        <span class="fee red" v-if="trialList && trialList.length > 0">{{ trialList[index].prem.toFixed(2) | moneyFormat }}</span>
      </div>
    </div>
    <div class="bottom-btn bg-white">
      <van-button type="danger" size="large" @click="nextStep" :disabled="nextStepFlag" v-no-more-click="1000">完成</van-button>
    </div>
    <van-action-sheet v-model="show" cancel-text="取消" :actions="policyInfo" @select="openDocument" />

    <!-- 字段选择 -->
    <van-popup v-model="popupShow" position="bottom">
      <van-picker show-toolbar :columns="columns" @confirm="onConfirm" @cancel="onCancel" />
    </van-popup>
  </div>
</template>
<script>
import { Tag, Icon, Dialog, ActionSheet, Popup, Picker, Stepper, Field, Checkbox } from 'vant'
import { trial } from '@/api/ebiz/common/common'
import { saveOrUpdateOrderInfo } from '@/api/ebiz/sale/sale'
import { saveProposal } from '@/api/ebiz/proposal/proposal.js'
export default {
  name: 'calculatePremium',
  components: {
    [Tag.name]: Tag,
    [Icon.name]: Icon,
    [ActionSheet.name]: ActionSheet,
    [Popup.name]: Popup,
    [Picker.name]: Picker,
    [Stepper.name]: Stepper,
    [Field.name]: Field,
    [Checkbox.name]: Checkbox
  },
  data() {
    return {
      chooseProducts: [],
      productIndex: '',
      calFactorIndex: '',
      premiumData: [], //试算
      saleInsuredInfo: {},
      saleInsuredPersonInfo: {}, //投保人信息
      trialList: [],
      popupShow: false,
      columns: [],
      pickerType: '',
      show: false,
      policyInfo: [],
      currentIndex: '', //当前操作产品
      trialInfos: [],
      influenceAddRiskCodes: [],
      influences: [],
      nextStepFlag: false,
      isRelated: localStorage.isRelated === '0',
      policyNo: '', //关联保单号
      // 份数
      mult: '',
      isFrom: '',
      // 默认钱数
      defalutAmt: ''
    }
  },
  mounted() {
    this.init()
    Array.prototype.min = function() {
      var min = this[0]
      var len = this.length
      for (var i = 1; i < len; i++) {
        if (this[i] < min) {
          min = this[i]
        }
      }
      return min
    }
  },
  methods: {
    //初始化数据
    init() {
      // 获取是否从建议书过来的
      this.isFrom = localStorage.isFrom 
      //获取投保人信息
      if (localStorage.saleInsuredInfo) {
        this.saleInsuredInfo = JSON.parse(localStorage.saleInsuredInfo)
      }
      //获取被保人信息
      if (localStorage.saleInsuredPersonInfo) {
        this.saleInsuredPersonInfo = JSON.parse(localStorage.saleInsuredPersonInfo)
      }
      //构建提交数据、渲染险种
      this.chooseProducts = JSON.parse(localStorage.chooseProducts)
      this.chooseProducts.map(item => {
        if (item.mainRiskCode == 'GFRS_M0006') {
          item.isHidden = true
        }
        if(item.mainRiskCode != 'GFRS_M0008') {
            item.calFactorLst.map(i => {
              this.defalutAmt = i.displayAmount
              console.log(i.displayAmount)
              console.log(i.defaultValue)
              this.mult = Number(i.displayAmount) / Number(i.defaultValue)
            })
          }
        })

      // this.influenceAddRiskCodes

      if (this.chooseProducts[0].influences && this.chooseProducts[0].influences.length > 0) {
        this.influences = this.chooseProducts[0].influences
        this.chooseProducts[0].influences.forEach(item => {
          this.influenceAddRiskCodes.push(item.productCode)
        })
      }

      this.mainRiskInfluenceAddRisk()
      //初始化数据试算
      this.getTrial()
    },
    // 责任保额份数变化
    dutyStepperChange(value, productIndex, calFactorIndex, dutyItemIndex, isChecked, min, max) {
      if (value < min || value > max) {
        this.nextStepFlag = true
        this.changeFlag = false
      } else {
        this.changeFlag = true
      }
      if (isChecked) {
        ;[this.productIndex, this.calFactorIndex] = [productIndex, calFactorIndex]
        let currentEle = this.chooseProducts[productIndex].calFactorLst[calFactorIndex].rules
        currentEle.forEach(item => {
          item.amt = Number(item.minDutyAmt) * Number(item.moneyUnit)
        })
        this.mainRiskInfluenceAddRisk()
        this.getTrial()
      } else {
        ;[this.productIndex, this.calFactorIndex] = [productIndex, calFactorIndex]
        let currentEle = this.chooseProducts[productIndex].calFactorLst[calFactorIndex].rules
        currentEle.forEach(item => {
          item.amt = Number(item.minDutyAmt) * Number(item.moneyUnit)
        })
      }
      let currentEle = this.chooseProducts[productIndex].calFactorLst[calFactorIndex].rules[dutyItemIndex]
      if ((Number(value) * 10000) % (Number(currentEle.limit) * 10000) != 0) {
        currentEle.defaultDutyAmt = currentEle.minDutyAmt
        console.log()
        Dialog.alert({
          message: localStorage.hint
        }).then(() => {
          // on close
        })
      } else {
        this.mainRiskInfluenceAddRisk()
        // currentEle['amt'] = Number(currentEle.defaultValue) * Number(currentEle.moneyUnit)
        this.getTrial()
      }
    },
    //弹框选择
    toSelect(index, index1, columns) {
      console.log(index, index1, columns)
      ;[this.popupShow, this.productIndex, this.calFactorIndex] = [true, index, index1]
      this.columns = columns
    },
    //取消picker
    onCancel() {
      this.columns = []
      this.popupShow = false
    },
    //确认选择字段
    onConfirm(value) {
      this.columns = []
      let currentFactor = this.chooseProducts[this.productIndex].calFactorLst
      let currentEle = currentFactor[this.calFactorIndex]
      console.log('value', value)
      console.log('currentFactor', currentFactor)
      console.log('currentEle', currentEle)
      if (currentEle.showContent != value.text) {
        //通用规则校验
        if (this.payExceedInsured(currentEle, currentFactor, value.value)) {
          this.popupShow = false
          return false
        }
        if (currentEle.code == 'payEndYear' && this.ageInfluencePayEndYear(value.value, currentEle)) {
          this.popupShow = false
          return false
        }
        if (currentEle.code == 'insuYear' && this.ageInfluenceInsuYear(value.value, currentEle)) {
          this.popupShow = false
          return false
        }

        currentEle.showContent = value.text
        let name = currentEle.code
        currentEle[name] = value.value
        if (currentEle.hasFlag) {
          currentEle[name + 'Flag'] = value.flag
        }
        this.hiddenPayEndYear(currentEle)
        //特殊规则：设置豁免险
        this.getTrial()
      }

      this.popupShow = false
    },
    // 交通责任险复选框变化
    changeChecked(productIndex, calFactorIndex, dutyItemIndex) {
      let isChecked = this.chooseProducts[productIndex].calFactorLst[calFactorIndex].rules.some(item => {
        return item.necess == true
      })
      if (!isChecked) {
        this.chooseProducts[productIndex].calFactorLst[calFactorIndex].rules[dutyItemIndex]['necess'] = !this.chooseProducts[productIndex].calFactorLst[
          calFactorIndex
        ].rules[dutyItemIndex]['necess']
        return false
      }
      this.mainRiskInfluenceAddRisk()
      this.getTrial()
    },
    // 计步器聚焦
    focusStep() {
      this.nextStepFlag = true
    },
    blurStep() {
      this.nextStepFlag = false
    },
    /********start 通用规则、特殊规则处理 start******/
    //通用规则1：交费方式为一次交情，无交费期限
    hiddenPayEndYear(currentEle) {
      if (currentEle.code == 'payIntv') {
        this.chooseProducts[this.productIndex]['isHidden'] = currentEle.payIntv == '0' ? true : false
      }
    },
    //通用规则2：交费期限不能超过保险期间
    payExceedInsured(currentEle, currentFactor, currentVale) {
      let payEndYearVal, insuYearVal
      if (currentEle.code == 'payEndYear') {
        payEndYearVal = Number(currentVale)
        insuYearVal = this.getPayEndYearOrInsuYear('insuYear', currentFactor)
      }
      if (currentEle.code == 'insuYear') {
        insuYearVal = Number(currentVale)
        payEndYearVal = this.getPayEndYearOrInsuYear('payEndYear', currentFactor)
      }
      if (payEndYearVal > insuYearVal) {
        this.$toast('交费期间不能超过保险期间')
        return true
      } else {
        return false
      }
    },
    getPayEndYearOrInsuYear(flag, currentFactor) {
      let returnVal
      currentFactor.forEach(item => {
        if (item.code == flag) {
          returnVal = item[flag]
        }
      })
      return Number(returnVal)
    },
    //特殊规则1、交费期间跟年龄的关系
    ageInfluencePayEndYear(value, currentEle) {
      let age = Number(this.saleInsuredPersonInfo.age)
      for (let i = 0; i < currentEle.rules.length; i++) {
        if (currentEle.rules[i].payEndYear == value && age > currentEle.rules[i].maxAge) {
          this.$toast('被保人年龄不适合该交费期间！')
          return true
        }
      }
      return false
    },
    //年龄对保险期间的影响
    ageInfluenceInsuYear(value, currentEle) {
      let age = Number(this.saleInsuredPersonInfo.age)
      for (let i = 0; i < currentEle.rules.length; i++) {
        if (currentEle.rules[i].insuYear == value && age > currentEle.rules[i].maxAge) {
          this.$toast('被保人年龄不适合该保险期间！')
          return true
        }
      }
      return false
    },
    //特殊规则2、主险对附加险的影响,主要是保额之间的影响  mainAddRelation：0-小于，1-大于，2-等于，3-小于等于,4-大于等于
    mainRiskInfluenceAddRisk() {
      if (this.productIndex == 0) {
        this.chooseProducts.forEach((item, index) => {
          if (this.influenceAddRiskCodes.includes(item.productCode)) {
            let influences = this.getInfluencesItem(item.productCode)
            let mainAddRelation = influences.amtInfluence[0].mainAddRelation
            let amtTimes = influences.amtInfluence[0].amtTimes
            let mainRiskAmt = this.getMainRiskAmt()
            if (mainAddRelation == 3 && (amtTimes == 1 || amtTimes == 5)) {
              this.setInputAddtionRiskMaxAmt(mainRiskAmt * amtTimes, index)
            } else if (mainAddRelation == 3 && amtTimes == 0.2) {
              this.setAddtionRiskMaxAmt(mainRiskAmt * amtTimes, index)
            }
          }
        })
      }
    },
    setAddtionRiskMaxAmt(mainRiskAmt, index) {
      this.chooseProducts[index].calFactorLst.forEach(item => {
        if (item.code == 'amt' || item.code == 'planCode') {
          let columnsValArr = []
          item.columns.forEach(option => {
            columnsValArr.push(Number(option.amt))
            if (Number(option.amt) > mainRiskAmt * 10000) {
              option.disabled = true
            } else {
              option.disabled = false
            }
          })
          //主险减，附加险变化，取最小

          let currentAmt = this.getAmtByPlanCode(item.columns, item.planCode)
          if (mainRiskAmt * 10000 < currentAmt) {
            let minVal = columnsValArr.min()
            item.columns.forEach(option => {
              if (option.amt == minVal) {
                item.showContent = option.text
                item.planCode = option.value
                item.amt = option.amt
              }
            })
          }
        }
      })
    },
    getAmtByPlanCode(columns, planCode) {
      let amt = ''
      columns.forEach(item => {
        if (item.value == planCode) {
          amt = item.amt
        }
      })
      return amt
    },
    setInputAddtionRiskMaxAmt(mainRiskAmt, index) {
      this.chooseProducts[index].calFactorLst.forEach(item => {
        if (item.type == 1) {
          item.maxAmt = Math.min(mainRiskAmt, item.oldMaxAmt)
          //减保额份数
          if (item.maxAmt < item.defaultValue) {
            item.defaultValue = item.maxAmt
          }
        }
      })
    },
    getMainRiskAmt() {
      let mainRiskAmt
      this.chooseProducts[0].calFactorLst.forEach(item => {
        if (item.type == 1) {
          mainRiskAmt = item.defaultValue
        }
      })
      return mainRiskAmt
    },
    getInfluencesItem(productCode) {
      let currentInfluences
      this.chooseProducts[0].influences.forEach(item => {
        if (item.productCode == productCode) {
          currentInfluences = item
        }
      })

      return currentInfluences
    },
    //特殊规则3、设置豁免险
    setRemitRisk() {
      //1、一次性交清和交费期间单位为A时，删除豁免险
      let mainRiskInfo = this.getMainRiskInfo()
      console.log(mainRiskInfo)
      let mainRiskPayIntv = mainRiskInfo.payIntv.payIntv
      let mainRiskPayEndYearFlag = mainRiskInfo.payEndYear.payEndYearFlag
      if (mainRiskPayIntv == 0 || mainRiskPayEndYearFlag == 'A') {
        //删除已选或互斥险种
        for (let i = 0; i < this.chooseProducts.length; i++) {
          if (this.chooseProducts[i].isRemit == 0) {
            this.chooseProducts.splice(i, 1)
            i--
          }
        }
      }

      //2、豁免险跟主险联动，值减一
      let remitIndex = this.getRemitIndex()
      if (!remitIndex) return

      this.chooseProducts[remitIndex].calFactorLst.forEach(item => {
        if (item.code == 'payIntv') {
          for (let key in mainRiskInfo.payIntv) {
            item[key] = mainRiskInfo.payIntv[key]
          }
        }
        if (item.code == 'payEndYear') {
          item.hasFlag = '1'
          item.payEndYearFlag = 'Y'
          item.payEndYear = Number(mainRiskInfo.payEndYear.payEndYear) - 1
          item.showContent = item.payEndYear + '年交'
        }
        if (item.code == 'insuYear') {
          item.hasFlag = '1'
          item.insuYearFlag = 'Y'
          item.insuYear = Number(mainRiskInfo.payEndYear.payEndYear) - 1
          item.showContent = item.insuYear + '年'
        }
        if (item.code == 'amt') {
          let trialList = JSON.parse(localStorage.trialList)
          item.amt = trialList[0].prem
          item.defaultValue = trialList[0].prem
          item.moneyUnit = 1
          item.suffix = '元'
        }
      })
    },
    getRemitIndex() {
      let remitIndex
      this.chooseProducts.forEach((item, index) => {
        if (item.isRemit == 0) {
          remitIndex = index
        }
      })
      return remitIndex
    },
    getMainRiskInfo() {
      let mainRiskInfo = {}
      this.chooseProducts[0].calFactorLst.forEach(item => {
        mainRiskInfo[item.code] = item
      })
      return mainRiskInfo
    },

    /********end 通用规则、特殊规则处理 end******/

    //查看文档列表
    seeDocument(index) {
      this.show = true
      this.policyInfo = this.chooseProducts[index].documentDTOS
    },
    //打开文档
    openDocument(item) {
      let pdfUrl = encodeURIComponent(item.url)
      this.$jump({
        flag: 'h5',
        extra: {
          title: item.name,
          // url: 'http://47.96.143.111/pdfjs/web/viewer.html?file=' + item.url //测试代码
          url: location.origin + '/pdfjs/web/viewer.html?file=' + pdfUrl
        }
      })
      // localStorage.documentInfo = JSON.stringify({ documentUrl: item.url, documentType: item.type })
      // this.$jump({
      //   flag: 'h5',
      //   extra: {
      //     url: location.origin + '/#/product/productDocument'
      //   },
      //   routerInfo: {
      //     path: `/product/productDocument`
      //   }
      // })
    },
    //删除所选产品
    deleteRisk(index) {
      Dialog.confirm({
        title: '提示',
        message: '确认删除该险种?',
        cancelButtonColor: '#E9332E',
        confirmButtonColor: '#FFFFFF',
        className: 'dialog-delete'
      })
        .then(() => {
          if (this.chooseProducts[index].isMainRisk == 0) {
            this.chooseProducts = []
            this.$jump({
              flag: 'goBack',
              extra: {
                refresh: '1',
                index: '-2'
              },
              routerInfo: {
                type: 2,
                index: -2,
                path: '/common/selectedProduct'
              }
            })
          } else {
            this.chooseProducts.splice(index, 1)
          }

          localStorage.chooseProducts = JSON.stringify(this.chooseProducts)
          this.getTrial()
        })
        .catch(() => {})
    },
    //试算
    async getTrial() {
      this.setRemitRisk()
      let params = this.getParams()
      let resultData = await trial(params)

      //试算成功，信息返显
      if (resultData.result == 0) {
        this.trialList = resultData.trialList
        console.log(resultData.trialList)
        localStorage.trialList = JSON.stringify(resultData.trialList)
        //设置豁免险保额
        this.setRemitRisk()
        this.nextStepFlag = false
      } else {
        this.nextStepFlag = true
        this.$toast(resultData.resultMessage)
      }
      localStorage.chooseProducts = JSON.stringify(this.chooseProducts)
    },
    //获取试算参数
    getParams() {
      let params = {
        trialInfos: []
      }

      this.chooseProducts.forEach((item, index) => {
        let trialInfo = {}
        item.calFactorLst.forEach(factor => {
          if (factor.type == 0) {
            if (factor.hasFlag == '1') {
              trialInfo[factor.code] = factor[factor.code]
              trialInfo[factor.code + 'Flag'] = factor[factor.code + 'Flag']
              // trialInfo[factor.payEndYear] = factor[factor.payEndYear]
            } else {
              trialInfo[factor.code] = factor[factor.code]
            }
          } else if (factor.type == 1) {
            if (factor.code == 'inputPrem') {
              trialInfo['prem'] = Number(this.defalutAmt) * Number(factor.moneyUnit)
            } else {
              trialInfo['amt'] = Number(this.defalutAmt) * Number(factor.moneyUnit)
            }
          } else if (factor.type == 2) {
            trialInfo.jobLevel = this.saleInsuredPersonInfo[factor.code]
          } else if (factor.type == 3) {
            let result = []
            factor.rules.forEach(dutyItem => {
              if (dutyItem.necess) {
                // trialInfo['amt'] = this.trialList[index].amt
                result.push({
                  amt: Number(dutyItem.defaultDutyAmt) * Number(dutyItem.moneyUnit),
                  dutyCode: dutyItem.duty,
                  dutyName: dutyItem.dutyName
                })
              }
            })
            trialInfo.duty = result
          }
        })

        //通用规则1：交费方式为一次交情，无交费期限
          if (trialInfo['payIntv'] == '0') {
          trialInfo['payEndYear'] = '1000'
          trialInfo['payEndYearFlag'] = 'Y'
          // 福宝宝和万能险传A
          if (item.mainRiskCode != 'GFRS_M0006' && item.mainRiskCode != 'GFRS_M0003') {
            trialInfo['insuYearFlag'] = 'Y'
          }
        }
        //责任险参数构建
        // if (trialInfo.duty) {
        //   trialInfo.duty = [{ dutyCode: trialInfo.duty }]
        // }
        //获取投被保生日、性别
        let birthday, sex
        if (item.isRemit == '0' && item.remitType == '0') {
          ;[birthday, sex] = [this.saleInsuredInfo.birthday, this.saleInsuredInfo.sex]
        } else {
          ;[birthday, sex] = [this.saleInsuredPersonInfo.birthday, this.saleInsuredPersonInfo.sex]
        }
        trialInfo = Object.assign(trialInfo, {
          birthday,
          sex,
          platformType: 'app',
          productCode: item.productCode,
          medical: JSON.parse(localStorage.getItem('saleInsuredPersonInfo')).medical
        })
        params.trialInfos.push(trialInfo)
      })
      this.trialInfos = params.trialInfos
      return params
    },

    //选择附加险
    selectAddtionRisk() {
      //存储附加险列表
      let addRiskCodes = []
      this.chooseProducts.forEach(item => {
        if (item.isMainRisk == 1) {
          addRiskCodes.push(item.productCode)
        }
      })
      if (localStorage.oldAddRiskCodes && JSON.parse(localStorage.oldAddRiskCodes)) {
        addRiskCodes = addRiskCodes.concat(JSON.parse(localStorage.oldAddRiskCodes))
      }
      //930折中方案，豁免险挂订单
      addRiskCodes = addRiskCodes.filter(riskCode => {
        return riskCode != 'DCRS_A0001'
      })

      localStorage.addRiskCodes = JSON.stringify(addRiskCodes)
      this.$jump({
        flag: 'h5',
        extra: {
          url: location.origin + '/#/common/addRiskList'
        },
        routerInfo: {
          path: '/common/addRiskList'
        }
      })
    },
    //保额份数变化
     stepperChange( value, defalutValue, productIndex, calFactorIndex ) {
      // let currentEle = this.chooseProducts[this.productIndex].calFactorLst[this.calFactorIndex]
      // currentEle.defaultValue = value
      console.log('进来几次')
      this.mult = Number(value) / Number(defalutValue)
      let currentEle = this.chooseProducts[productIndex].calFactorLst[calFactorIndex]
      if ((Number(value) * 10000) % (Number(currentEle.limit) * 10000) != 0) {
        Dialog.alert({
          message: localStorage.hint
        }).then(() => {
          currentEle.defaultValue = currentEle.rules[productIndex].defaultValue
          // this.nextStepFlag = true
        })
      } else {
        this.mainRiskInfluenceAddRisk()
        currentEle['amt'] = Number(currentEle.defaultValue) * Number(currentEle.moneyUnit)
        this.getTrial()
      }
    },
    //下一步
    async nextStep() {
      //组装险种提交数据
      let [mainRiskCode, riskDTOLst] = ['', []]
      let rollInResult = '' //校验预计转入保费结果
      this.chooseProducts.forEach((item, index) => {
        if (item.isMainRisk == 0) {
          mainRiskCode = item.productCode
        }
        // this.trialInfos.map(trial=>{
        //   trial.duty.map(dutylist=> {
        //     dutylist.dutyname
        //   })
        // })
        let riskItem = {
          isMainRisk: item.isMainRisk,
          riskName: item.riskName,
          riskType: item.riskType,
          riskCode: item.productCode,
          mainRiskCode: mainRiskCode,
          prem: this.trialList[index] && this.trialList[index].prem,
          standPrem: this.trialList[index] && this.trialList[index].standPrem,
          predictTransferPrem: item.predictTransferPrem,
          thirdInsuraceNo: this.policyNo,
          mult: this.mult
        }
        if (item.hasPredictTransferPrem && item.hasPredictTransferPrem === '0') {
          //增加万能险 预计转入保费校验
          rollInResult = this.rollInCheck(item.predictTransferPrem)
        } else {
          rollInResult = true
        }
        //责任险保存参数构建
        if (this.trialList[index].duty) {
          riskItem['dutyLst'] = this.trialList[index].duty
          //930折中方案，责任险分档
          riskItem['amt'] = this.trialList[index].amt
        }
        //保费算保额
        console.log('this.trialList', this.trialList[index].trialType)
        // debugger
        if (this.trialList[index].trialType == '1' || this.trialList[index].trialType == '2') {
          // console.log('11111111111111111')
          // console.log(this.trialList[index].amt)
          riskItem['amt'] = this.trialList[index].amt
        }
        // console.log(riskItem)
        //万能型产品保费赋值给保额
        if (this.trialList[index].productCode == 'GFRS_M0003') {
          // console.log('2222222222')
          riskItem['amt'] = this.trialList[index].prem
        }
        //豁免险保额处理
        if (item.isRemit == '0') {
          // console.log('33333333')
          this.trialInfos[index].amt = this.trialList[0].prem
        }
        // console.log(riskItem)
        console.log(this.trialInfos[index])
        riskItem = Object.assign(riskItem, this.trialInfos[index])
        // console.log(riskItem)
        riskDTOLst.push(riskItem)
      })
      if (!rollInResult) {
        return
      }
      // console.log('riskDTOLst', riskDTOLst)
      //建议书需要添加全部投保人信息，电投只需要投保人ID
      let insuredDTOItem = Object.assign(this.saleInsuredPersonInfo, { riskDTOLst: riskDTOLst })
      let params = {
        orderType: 'RISK_ORDER',
        orderDTO: {
          orderInfoDTO: {
            orderNo: localStorage.orderNo
          },
          // appntDTO: {},
          insuredDTOs: [insuredDTOItem]
        }
      }

      let resultData
      if (localStorage.isFrom == 'proposal') {
        resultData = await saveProposal(params)
      } else {
        resultData = await saveOrUpdateOrderInfo(params)
      }

      if (resultData.result == 0) {
        //建议书
        if (localStorage.isFrom == 'proposal' && resultData.content.id) {
          this.saleInsuredPersonInfo.insuredId = resultData.content.id
          localStorage.saleInsuredPersonInfo = JSON.stringify(this.saleInsuredPersonInfo)
        }
        this.$jump({
          flag: 'goBack',
          extra: {
            refresh: '1',
            index: '-2'
          },
          routerInfo: {
            type: 2,
            index: -2,
            path: '/common/selectedProduct'
          }
        })
      } else {
        this.$toast(resultData.resultMessage)
      }
    },
    rollInCheck(value) {
      let regExp = /^[1-9]+[0-9]*$/
      let result = regExp.test(value)
      if (result) {
        return true
      } else {
        this.$toast.fail('请输入正确的预计转入保费')
        return false
      }
    }
  },
  watch: {
    chooseProducts: {
      deep: true,
      handler: function(newVal) {
        // console.log('xin', newVal)
        this.chooseProducts = newVal
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.calculate-premium-container {
  .border-bottom {
    border-bottom: 1px solid #dadada;
  }
  .van-cell {
    padding: 0px;
  }
  .prem:last-child {
    border: none;
  }
  /deep/.van-action-sheet__name {
    font-size: 12px;
  }
}
</style>
