<template>
  <div>
    <van-search v-model="searchName" placeholder="请输入保单号/投保人姓名/被保险人姓名" />
    <van-sticky>
      <van-tabs v-model="active" @change="tabChange">
        <van-tab name="uncommit" title="未提交" />
        <van-tab name="commit" title="已提交" />
      </van-tabs>
    </van-sticky>
    <div class="container" v-if="isShow">
      <van-pull-refresh @refresh="onRefresh" v-model="isLoading">
        <div v-if="NewItems.length > 0">
          <Order v-for="(order, index) in NewItems" :key="index" :order="order">
            <p v-if="active === 'uncommit'" class="name mb8">
              <van-tag plain color="#999999">保单保障日截止日期</van-tag>
              <span class="ml5 span">{{ order.endDate }}</span>
            </p>
            <div v-if="active === 'commit'">
              <p class="name mb8">
                <van-tag plain color="#999999">重新投保单号</van-tag>
                <span class="ml5 span">{{ order.newOrderNo }}</span>
              </p>
              <p class="name">
                <van-tag plain color="#999999">状态</van-tag>
                <span class="ml5 span">{{ order.newOrderStatus | idToText('insureAgainState') }}</span>
              </p>
            </div>

            <template #btns>
              <div v-if="active === 'uncommit'">
                <van-button size="small" round type="danger" @click="uncommitInsureDetail(order)" plain>查看详情</van-button>
                <van-button v-if="canRevoke[order.newOrderStatus]" class="ml10" size="small" round type="danger" @click="revokeOrder(order)">撤单</van-button>
                <van-button class="ml10" size="small" round type="danger" @click="insureAgain(order)">{{
                  order.newOrderStatus == '02' ? '待支付' : '重新投保'
                }}</van-button>
              </div>
              <div v-if="active === 'commit'">
                <van-button v-if="canRevoke[order.newOrderStatus]" class="ml10" size="small" round type="danger" @click="revokeOrder(order)">撤单</van-button>
                <van-button v-if="order.newOrderStatus == '19'" class="ml10" size="small" round type="danger" @click="againPay(order)">重新支付</van-button>
                <van-button class="ml10" size="small" round type="danger" @click="commitInsureDetail(order)">查看投保单</van-button>
              </div>
            </template>
          </Order>
        </div>
        <div v-else class="text-center">
          <img class="mt40" src="@/assets/images/pic_page-non.png" />
          <div class="mt20" v-if="errMessage != ''">{{ errMessage }}</div>
        </div>
      </van-pull-refresh>
      <van-dialog
        class="dialog-delete"
        @confirm="checkCaptchaCode"
        @cancel="cancelCaptchaCode"
        :before-close="beforeClose"
        confirm-button-color="#fff"
        v-model="revokePanelShow"
        title="短信验证"
        show-cancel-button
      >
        <p class="captchaReceiver">投保人手机号: {{ captchaReceiver | phoneNumFilter }}</p>
        <van-field v-model="sms" center clearable placeholder="请输入短信验证码">
          <template #button>
            <van-button :disabled="sendTime !== 0" v-no-more-click="1000" @click="getCaptchaCode" size="small" type="danger">{{
              sendTime ? `${sendTime}s后获取` : '获取验证码'
            }}</van-button>
          </template>
        </van-field>
      </van-dialog>
    </div>

    <van-popup v-model="isAgreementShow" position="right" :style="{ height: '100vh', width: '100vw' }">
      <ReadingAgreement :needTime="false">
        <h3 class="p10" style="text-align: center">重新投保声明提示</h3>
        <p style="text-indent: 28px">尊敬的{{ orderInfo.appntName }}{{ orderInfo.sex == 0 ? '先生' : '女士' }}：</p>
        <div class="p10 mb90" v-if="orderInfo.riskCode !== 'GFRS_A0008'">
          <p style="text-indent: 28px">
            您好！感谢您选择购买国富人寿保险股份有限公司（以下简称我们）保险产品，您于{{ orderInfo.cvaliDate }}投保的旧保单{{
              orderInfo.policyNo
            }}，产品名称为{{
              orderInfo.riskName
            }}即将到期或已到期（到期日期详见保单），为保护您的权益，您可向我们提交重新投保申请。以下是申请重新投保的注意事项和声明，请您仔细阅读和确认：
          </p>
          <p style="text-indent: 28px">1.{{ orderInfo.riskName }}保险期间为一年，到期后需要您重新投保。</p>
          <p style="text-indent: 28px">
            2.本次重新投保，我们将按照{{ orderInfo.riskName }}费率表中的“在上一保险期间届满后60日内申请重新投保时对应的费率”计算保费。
          </p>
          <p style="text-indent: 28px">3.若本次重新投保成功，新保单免除等待期。</p>
          <p style="text-indent: 28px">
            4.本次重新投保仅限于无其他补充告知的情况，若您有其他补充告知，您的条件不符合本次重新投保流程。您可联系保单服务专员，通过其他途径进行投保申请。
          </p>
          <p style="text-indent: 28px">
            5.若您于旧保单满期前申请重新投保，且于旧保单满期前成功支付保险费，则新保单在旧保单保险期满日对应日的次日零时生效，旧保单在保险期满日24时终止。若您于旧保单满期后重新投保申请，且成功支付保险费，则新保单于支付次日零时生效，旧保单在保险期满日24时终止。
          </p>
          <!-- <p style="text-indent: 28px">
              6.若您未在旧保单满期后60天（包含）内申请重新投保，则您的重新投保资格将被取消。后续您可再次申请投保，但新单不再与旧保单关联，需重新计算等待期。具体详情，可咨询保单服务专员。
            </p> -->
        </div>
        <div class="p10 mb90" v-else>
          <p style="text-indent: 28px">
            您好！感谢您选择购买国富人寿保险股份有限公司（以下简称我们）保险产品，您于{{ orderInfo.cvaliDate }}投保的旧保单{{
              orderInfo.policyNo
            }}，产品名称为：{{
              orderInfo.riskName
            }}即将到期或已到期（到期日期详见保单），为保护您的权益，您可向我们提交重新投保申请。以下是申请重新投保的注意事项和声明，请您仔细阅读和确认：
          </p>
          <p style="text-indent: 28px">1.{{ orderInfo.riskName }}保险期间为一年，到期后需要您重新投保。</p>
          <p style="text-indent: 28px">
            2.本次重新投保，我们将按照{{ orderInfo.riskName }}费率表中的“在上一保险期间届满后60日内申请重新投保时对应的费率”计算保费。
          </p>
          <p style="text-indent: 28px">3.若本次重新投保成功，新保单免除等待期。</p>
          <p style="text-indent: 28px">
            4.本次重新投保仅限于无其他补充告知的情况，若您有其他补充告知，您的条件不符合本重新投保申请。您可联系保单服务专员，通过其他途径进行投保申请。
          </p>
          <p style="text-indent: 28px">
            5.若您于旧保单满期前申请重新投保，且于旧保单满期前成功支付保险费，则新保单在旧保单保险期满日对应日的次日零时生效，旧保单在保险期满日24时终止。若您于旧保单满期后重新投保申请，且成功支付保险费，则新保单于支付次日零时生效，旧保单在保险期满日24时终止。
          </p>
          <!-- <p style="text-indent: 28px">
              6.若您未在旧保单满期后60天（包含）内申请重新投保，则您的重新投保资格将被取消。后续您可再次申请投保，但新单不再与旧保单关联，需重新计算等待期。具体详情，可咨询保单服务专员。
            </p> -->
          <p style="text-indent: 28px">
            6.国富人寿附加住院医疗保险已停售，您可选择投保同类产品国富人寿附加住院医疗保险（B款），我们将按照国富人寿附加住院医疗保险（B款）费率表中的“在上一保险期间届满后60日内申请重新投保时对应的费率”计算保费。
          </p>
        </div>
        <template #action>
          <van-radio-group class="m10" v-model="radio">
            <van-radio :name="false">
              <span style="font-size: 14px">本人已阅读、知晓本投保声明内容，同意重新投保</span>
            </van-radio>
          </van-radio-group>
          <div class="btns">
            <van-button type="danger" :disabled="radio" block @click="nextStep">下一步</van-button>
          </div>
        </template>
      </ReadingAgreement>
    </van-popup>
  </div>
</template>

<script>
import { Search, Sticky, PullRefresh, list, Tag, Popup, Radio, RadioGroup, Toast } from 'vant'
import { getPolicyListAgent, revokeOrder, getAuthCode } from '@/api/ebiz/insureAgain/insureAgain'
import Order from '@/components/ebiz/insureAgain/Order'
import ReadingAgreement from '@/components/ebiz/insureAgain/ReadingAgreement'
import CacheUtils from '@/assets/js/utils/cacheUtils'
import { getReAppntPolicy } from '@/api/ebiz/insureAgain/insureAgain'
import { getWhitelist } from '@/api/ebiz/whitelist'
export default {
  name: 'InsureAgain',
  components: {
    Order,
    ReadingAgreement,
    [Search.name]: Search,
    [Sticky.name]: Sticky,
    [PullRefresh.name]: PullRefresh,
    [list.name]: list,
    [Tag.name]: Tag,
    [Popup.name]: Popup,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio
  },
  filters: {
    expiryDateFilter(val) {
      if (!val) return ''
      console.log(new Date(val).getTime() + 60 * 24 * 60 * 60 * 1000)
      let date = new Date(new Date(val).getTime() + 60 * 24 * 60 * 60 * 1000)
      let month = date.getMonth() + 1
      if (month <= 9) {
        month = '0' + month
      }
      return date.getFullYear() + '-' + month + '-' + date.getDate()
    },
    phoneNumFilter(phoneNum) {
      let num = phoneNum.split('')
      num.splice(3, 4, '****')
      return num.join('')
    }
  },
  data() {
    return {
      searchName: '', //搜索名
      active: 'uncommit',
      policyListDTOList: [],
      isAgreementShow: false,
      radio: '',
      isLoading: false,
      isShow: false,
      orderInfo: {},
      canRevoke: {
        19: true,
        '02': true,
        48: true,
        49: true,
        55: true,
        58: true,
        46: true,
        50: true,
        51: true
      },
      revokePanelShow: false,
      sms: '',
      smsId: '',
      sendTime: 0,
      getCaptcha: false,
      captchaTimer: null,
      captchaReceiver: '',
      revokeOrderNo: '',
      src: this.$assetsUrl + 'images/background.png',
      errMessage: '暂无保单'
    }
  },
  computed: {
    NewItems() {
      var NewItems = []
      this.policyListDTOList.map((item) => {
        if (
          item.riskName.search(this.searchName) != -1 ||
          item.policyNo.search(this.searchName) != -1 ||
          item.appntName.search(this.searchName) != -1 ||
          item.insuredName.search(this.searchName) != -1
        ) {
          if (item.reInsuranceState != null && item.reInsuranceState != '') {
            if (this.active === 'uncommit') {
              if (
                item.newOrderStatus === null ||
                item.newOrderStatus === '01' ||
                item.newOrderStatus === '02' ||
                item.newOrderStatus === '38' ||
                item.newOrderStatus === '39' ||
                item.newOrderStatus === '40'
              ) {
                NewItems.push(item)
              }
            } else if (this.active === 'commit') {
              if (item.newOrderStatus === '07' || item.newOrderStatus === '19' || item.newOrderStatus === '55' || item.newOrderStatus === '08') {
                NewItems.push(item)
              }
            }
          }
        }
      })
      console.log(NewItems, '======================NewItems===================')
      return NewItems
    }
  },
  created() {
    let data = {}
    this.getPolicyListAgent(data)
  },
  mounted() {
    setTimeout(() => {
      window.EWebBridge.webCallAppInJs('webview_left_button', {
        intercept: '1' //是否拦截原生返回事件 1是 其他否
      })
    }, 100)
    window.appCallBack = this.appCallBack
  },
  methods: {
    appCallBack(data) {
      if (data.trigger == 'left_button_click') {
        if (this.isAgreementShow) {
          this.isAgreementShow = false
          setTimeout(() => {
            window.EWebBridge.webCallAppInJs('webview_left_button', {
              intercept: '1'
            })
          }, 100)
        } else {
          this.$jump({
            flag: 'service'
          })
        }
      }
    },
    tabChange(name) {
      this.active = name
    },
    //初始化保单列表
    getPolicyListAgent(pageInfo) {
      this.$toast.loading({
        // 持续展示 toast
        duration: 0,
        // 禁用背景点击s
        forbidClick: true,
        loadingType: 'spinner',
        message: '加载中……'
      })
      getPolicyListAgent(pageInfo).then((res) => {
        if (res.result == '0') {
          this.policyListDTOList = res.policyListDTOList
          this.isShow = true
        } else {
          this.errMessage = res.resultMessage || '暂无保单'
        }
      })
    },
    insureAgain(order) {
      this.orderInfo = order
      CacheUtils.setLocItem('policyNo', order.policyNo)
      setTimeout(() => {
        window.EWebBridge.webCallAppInJs('webview_left_button', {
          img: this.$assetsUrl + 'images/del-close-btn@3x.png',
          intercept: '1' //是否拦截原生返回事件 1是 其他否
        })
      }, 100)
      getReAppntPolicy({ policyNo: order.policyNo }).then(async (res) => {
        if (res.result == 0) {
          // 待支付订单 不需再次人脸识别
          if (order.newOrderStatus == '02') {
            this.goUrl(res, order)
            return
          } else {
            this.orderInfo.sex = res.orderDTO.appntDTO.sex
            if (res.orderDTO.appntDTO.idType == '1') {
              // 白名单校验
              const resData = await getWhitelist({
                idNo: res.orderDTO.appntDTO.idNo,
                name: res.orderDTO.appntDTO.name,
                whiteType: 'reOrder_face_show'
              })
              if (resData.result === '0') {
                // 在白名单内
                if (resData.content && resData.content.length) {
                  this.goUrl(res, order)
                  return
                } else {
                  // 人脸识别
                  window.EWebBridge.webCallAppInJs('face_auth', {
                    businessSource: '1', //业务来源:1-电投，2-入司，3-理赔，4-保全
                    number: res.orderDTO.appntDTO.idNo, //身份证号码
                    name: res.orderDTO.appntDTO.name, //姓名,
                    orderNo: CacheUtils.getLocItem('orderNo') //订单号
                  }).then((data) => {
                    if (JSON.parse(data).state == '1') {
                      this.goUrl(res, order)
                    } else {
                      return this.$toast('人脸识别，验证失败！')
                    }
                  })
                }
              } else {
                this.$toast(resData.resultMessage)
              }
            } else {
              return this.$toast('人脸识别，证件类型不为身份证！')
            }
          }
        } else {
          this.$toast(res.resultMessage)
        }
      })
    },
    goUrl(res, order) {
      let url
      //投保人信息返显
      CacheUtils.setLocItem('orderDetailData', JSON.stringify(res))
      let appntDTO = res.orderDTO.appntDTO
      let insuredDTOs = res.orderDTO.insuredDTOs[0]
      let orderInfoDTO = res.orderDTO.orderInfoDTO
      let riskDTOLst = insuredDTOs.riskDTOLst
      this.orderInfo.appntName = appntDTO.name
      this.orderInfo.cvaliDate = orderInfoDTO.cvaliDate
      this.orderInfo.expiryDate = orderInfoDTO.expiryDate
      this.orderInfo.riskCode = ''
      CacheUtils.setLocItem('orderNo', orderInfoDTO.orderNo)
      riskDTOLst.forEach((element, index) => {
        if (element.riskCode === 'GFRS_A0008') {
          this.orderInfo.riskCode = 'GFRS_A0008'
        }
      })
      if (order.newOrderStatus === '38') {
        url = '/insureAgain/ProductInformation'
      } else if (order.newOrderStatus === '39') {
        url = '/insureAgain/Notification'
      } else if (order.newOrderStatus === '40') {
        url = '/insureAgain/SignatureConfirmation'
      } else if (order.newOrderStatus === '01') {
        url = '/insureAgain/SignatureConfirmation'
      } else if (order.newOrderStatus === '02') {
        url = '/insureAgain/Payment'
      } else {
        this.isAgreementShow = true
        return false
      }

      this.$jump({
        flag: 'h5',
        extra: {
          url: location.origin + '/#' + url
        },
        routerInfo: {
          path: url
        }
      })
    },
    uncommitInsureDetail(order) {
      CacheUtils.setLocItem('policyNo', order.policyNo)
      this.$jump({
        flag: 'h5',
        extra: {
          url: location.origin + '/#/insureAgain/UncommitInsureDetail'
        },
        routerInfo: {
          path: '/insureAgain/UncommitInsureDetail'
        }
      })
    },
    commitInsureDetail(order) {
      CacheUtils.setLocItem('orderNo', order.newOrderNo)
      this.$jump({
        flag: 'h5',
        extra: {
          url: location.origin + '/#/insureAgain/CommitInsureDetail'
        },
        routerInfo: {
          path: '/insureAgain/CommitInsureDetail'
        }
      })
    },
    nextStep() {
      this.$jump({
        flag: 'h5',
        extra: {
          url: location.origin + `/#/insureAgain/InsureInformation`,
          forbidSwipeBack: '1',
          needRefresh: '1'
        },
        routerInfo: { path: `/insureAgain/InsureInformation` }
      })
    },
    onRefresh() {
      this.isLoading = false
      this.policyListDTOList = []
      let data = {}
      this.getPolicyListAgent(data)
    },
    async getCaptchaCode() {
      if (this.sendTime !== 0) return
      this.getCaptcha = true
      this.sendTime = 60
      let data = {
        operateType: 'appntInfoEntry',
        type: 'H5',
        operateCode: this.captchaReceiver,
        system: 'agentApp',
        operateCodeType: '0'
      }
      let res = await getAuthCode(data)
      if (res.result === '0') {
        this.$toast('获取验证码成功')
      }
      this.smsId = res.sessionId
      this.captchaTimer = setInterval(() => {
        this.sendTime--
        if (this.sendTime === 0) {
          clearInterval(this.captchaTimer)
          this.captchaTimer = null
        }
      }, 1000)
    },
    async checkCaptchaCode() {
      if (!this.getCaptcha) {
        return this.$toast('请先获取验证码')
      }
      if (!this.sms.trim()) {
        return this.$toast('请输入验证码')
      }
      clearInterval(this.captchaTimer)
      this.captchaTimer = null
      let revokeResult = await revokeOrder({
        id: this.revokeOrderNo,
        smsId: this.smsId,
        code: this.sms
      })
      if (revokeResult.result == 0) {
        this.$toast('撤单成功!')
        setTimeout(() => {
          this.saleList = []
          this.isSuccess = false
          ;[this.loading, this.finished] = [true, false]
          this.onRefresh()
        }, 1000)
      } else {
        Toast.fail(revokeResult.resultMessage)
      }
      this.cancelCaptchaCode()
      this.sms = ''
    },
    beforeClose(action, done) {
      this.captchaMaped ? done() : done(false)
    },
    cancelCaptchaCode() {
      this.sendTime = 0
      this.revokePanelShow = false
      clearInterval(this.captchaTimer)
      this.captchaTimer = null
      this.getCaptcha = false
      this.captchaMaped = false
      this.captchaReceiver = ''
    },
    //再次支付
    againPay(order) {
      CacheUtils.setLocItem('orderNo', order.newOrderNo)
      // 再次支付 salelist为 0
      CacheUtils.setLocItem('salelist', '0')
      CacheUtils.removeLocItem('changeCard')
      this.$jump({
        flag: 'h5',
        extra: {
          url: location.origin + '/#/insureAgain/payMent'
        },
        routerInfo: { path: '/insureAgain/payMent' }
      })
    },
    revokeOrder(order) {
      this.$dialog
        .confirm({
          className: 'dialog-delete',
          title: '提示',
          message: '撤单后,数据将不可恢复,您确定要撤单吗?',
          cancelButtonColor: '#E9332E',
          confirmButtonColor: '#FFFFFF'
        })
        .then(() => {
          this.revokePanelShow = true
          this.captchaReceiver = order.appntMobile
          this.revokeOrderNo = order.newOrderNo
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.captchaReceiver {
  margin-left: 1em;
  padding-bottom: 1em;
  border-bottom: 1px solid #eaeaea;
  font-size: 14px;
}
</style>
