<template>
  <div style="background: #f5f5f5" class="select-product-container">
    <div v-if="isFrom == 'sale'">
      <index-bar></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 size="small" round 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>

    <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 } from 'vant'
import FieldPicker from '@/components/ebiz/FieldPicker'
import { orderDetail, deleteOrderInfo } from '@/api/ebiz/common/common'
import { formatAllRisk } from '@/assets/js/utils/formatRiskList'
import { getDetail, deleteProposal } from '@/api/ebiz/proposal/proposal.js'
import utilsAge from '@/assets/js/utils/age'
import IndexBar from '@/components/ebiz/sale/IndexBar'

export default {
  name: 'selectedProduct',
  data() {
    return {
      chooseProducts: [],
      total: 0,
      nextStepFlag: true,
      isShow: true,
      appntDTO: {},
      isFrom: localStorage.isFrom,
      salePageFlag: '3'
    }
  },
  components: {
    [Tag.name]: Tag,
    [FieldPicker.name]: FieldPicker,
    [SubmitBar.name]: SubmitBar,
    [Icon.name]: Icon,
    [IndexBar.name]: IndexBar
  },
  mounted() {
    if (localStorage.isFrom == 'sale') {
      setTimeout(() => {
        // eslint-disable-next-line no-undef
        EWebBridge.webCallAppInJs('webview_left_button', {
          img: this.$assetsUrl + 'images/images/del-close@3x.png',
          intercept: '1' //是否拦截原生返回事件 1是 其他否
        })
      }, 100)
    }
    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
          })
      }
    },
    //获取已选产品列表
    async getProductList() {
      //建议书、电投详情
      let resultData
      let isProposal = localStorage.isFrom == 'proposal' ? true : false
      if (isProposal) {
        let saleInsuredPersonInfo = localStorage.saleInsuredPersonInfo && JSON.parse(localStorage.saleInsuredPersonInfo)
        console.log(saleInsuredPersonInfo)

        let insuredId
        if (saleInsuredPersonInfo && saleInsuredPersonInfo.insuredId) {
          insuredId = saleInsuredPersonInfo.insuredId
        }
        this.$toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          loadingType: 'spinner',
          message: '加载中……'
        })
        resultData = await getDetail({
          orderNo: localStorage.orderNo,
          isMerge: '1',
          orderType: 'proposalInsuredInfo',
          orderDTO: { insuredDTOs: [{ insuredId: insuredId }] }
        })
      } else {
        this.$toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          loadingType: 'spinner',
          message: '加载中……'
        })
        resultData = await orderDetail({ orderNo: localStorage.orderNo, isMerge: '1' })
      }
      if (resultData.result == 0) {
        let riskDTOLst
        if (isProposal) {
          localStorage.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
        }
        localStorage.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) {
            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: localStorage.orderNo
            },
            insuredDTOs: [
              {
                riskDTOLst: [
                  {
                    insuanceId: this.chooseProducts[index].insuanceId
                  }
                ]
              }
            ]
          },
          type: '3'
        })
      } else {
        resultData = await deleteOrderInfo({
          orderType: 'RISK_ORDER',
          id: this.chooseProducts[index].insuanceId,
          orderDTO: {
            orderInfoDTO: {
              orderNo: localStorage.orderNo
            }
          }
        })
      }

      if (resultData.result == 0) {
        this.getProductList()
      } else {
        this.$toast(resultData.resultMessage)
      }
    },
    //下一步
    nextStep() {
      if (!this.$route.query.salePageFlag) {
        //如果从保单列表编辑按钮进入
        localStorage.salePageFlag = '4'
      }
      console.log('this.chooseProducts', this.chooseProducts)
      if (this.chooseProducts.length == 0) {
        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
          }
        }
      }
      let routerUrl
      if (localStorage.isFrom == 'proposal') {
        routerUrl = '/proposal/chooseInsuredPerson'
        let page = this.$route.query.proposalEdit == '1' ? '-1' : '-2'

        this.$jump({
          flag: 'goBack',
          extra: {
            refresh: '1',
            index: page
          },
          routerInfo: {
            path: routerUrl
          }
        })
      } else {
        let showFlag = this.showTipForDoubleRecord()
        if (showFlag) {
          this.$dialog
            .alert({
              message: '年龄≥60周岁投保人，如果投保一年期以上产品，请根据监管要求对销售过程进行录音录像！',
              confirmButtonColor: '#000000'
            })
            .then(() => {
              this.nextPageShow()
            })
        } else {
          this.nextPageShow()
        }
      }
    },
    //添加产品
    addProduct() {
      this.$jump({
        flag: 'h5',
        extra: {
          url: location.origin + '/#/common/mainRiskList'
        },
        routerInfo: {
          path: '/common/mainRiskList'
        }
      })
    },
    showTipForDoubleRecord() {
      //判断投保人年龄是否大于等于60岁
      let showFlag = false
      let age = utilsAge.getAge(this.appntDTO.birthday, new Date())
      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 routerUrl = '/sale/beneficiary'
      localStorage.beneficiaryInfo = ''
      localStorage.fromAddBeneficiaryInfo = ''
      localStorage.removeItem('applicant')
      this.$jump({
        flag: 'h5',
        extra: {
          forbidSwipeBack: '1',
          url: location.origin + '/#' + routerUrl,
          needRefresh: '1'
        },
        routerInfo: {
          path: routerUrl
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.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;
  }
}
</style>
