<template>
  <cr-form
    scroll-to-error
    @submit="onSubmit"
    @failed="onFailed"
    class="container"
    ref="subForm"
    :scroll-offset="100"
  >
    <nav-tab :nav-list="navBarOptions" ref="navTab" @show="e => (goodActionShow = e)" />
    <detail-header :det="headerInfo" />
    <div class="det-body">
      <card title="保险计划" :option="['查看详情']" @option-click="openIframePupop(4)">
        <cr-radio-btn v-model="formData.amountInsured" :radio-data="planOptions" />
        <compactCellGroup :cell-data="planCellData" :text-bold="true" :font-size="14" />
        <plan-tip :tip-list="planTipOptions" />
      </card>
      <div id="det_insure">
        <insure-person-form
          v-model="formData"
          :radio-options="personFormOptions"
          ref="insureForm"
          :detail-type="type"
        />
        <auto-deduct
          v-model="formData.autoRenewPolicy"
          :cell-data="autoCellInfo"
          @cell-click="openIframePupop"
        />
        <protocol-read
          v-model="formData.read"
          :cell-data="noticeCellData"
          :protocol-data="protocolData"
          @cell-click="openIframePupop"
        />
      </div>
      <card class="intro" id="det_intro">
        <cr-image
          :src="item"
          v-for="(item, index) in introImg"
          :key="index"
          width="100%"
          height="auto"
        />
      </card>
      <cps-case :case-data="caseInfo" />
      <div id="det_process">
        <cps-process :process-data="processDetail" @click="openIframePupop(5)" :more="false" />
      </div>
      <cps-qa :qa-data="qaInfo" />
    </div>
    <detail-footer :company-info="companyInfo" />
    <copyright />
    <good-action :content="goodActionInfo" v-show="goodActionShow" />
    <popup-with-iframe
      v-model="popupShow"
      :title="pupopData.title"
      :content="pupopData.content"
      :url="pupopData.url"
    >
      <cps-process-detail v-if="currentPupopIndex === 5" :process-data="processDetail" />
      <cps-rate v-if="currentPupopIndex === 6" :rate-data="rateInfo" :is-ai="true" />
    </popup-with-iframe>
    <go-insure-dialog
      v-model="goInsureState"
      :title="headerInfo.title"
      :pay-data="goodBuyModalInfo"
      @confirm="nextStep"
      @read-protocol="openIframePupop"
      :protocol-data="protocolData"
    />
    <pay-wait-layer :value="isPayWait" />
  </cr-form>
</template>

<script>
/**
 * @description: 华太轻重疾险 Critical illness insurance
 */
import CrRadioBtn from "@/components/CrRadioBtn";
import Card from "@/components/Card";
import Copyright from "@/components/Copyright";
import GoodAction from "@/components/GoodAction";
import Collapse from "@/components/Collapse";

import DetailHeader from "./modules/DetailHeader";
import DetailFooter from "./modules/DetailFooter";
import CompactCellGroup from "@/components/CompactCellGroup";
import CpsCase from "./modules/CpsCase";
import CpsProcess from "./modules/CpsProcess";
import CpsQa from "./modules/CpsQA";
import PopupWithIframe from "@/components/PopupWithIframe";
import GoInsureDialog from "./modules/GoInsureDialog";
import CpsProcessDetail from "./modules/CpsProcessDetail";
import CpsRate from "./modules/CpsRate";
import PlanTip from "./modules/PlanTip";
import InsurePersonForm from "./modules/InsurePersonForm";
import AutoDeduct from "./modules/AutoDeduct";
import ProtocolRead from "./modules/ProtocolRead";
import NavTab from "./modules/NavTab";
import detailPayMixin from "./modules/detailPay.mixin";
import detailLoginMixin from "./modules/detailLogin.mixin";

import localStorage from "@/service/localStorage";
import Detail from "@/api/detail.zhongan.yiwai";
import { trail, list } from "@/api/product";
import { isIdNo } from "@/service/validation";
import { getRealAge, getBirthDate } from "@/service/utils";
import { checkOpenId } from "@/service/wxJsSdk";

export default {
  name: "GoodsDetail-AI",
  mixins: [detailPayMixin, detailLoginMixin],
  components: {
    DetailHeader,
    DetailFooter,
    CompactCellGroup,
    CrRadioBtn,
    Card,
    // eslint-disable-next-line
    Collapse,
    CpsCase,
    CpsProcess,
    CpsQa,
    Copyright,
    PopupWithIframe,
    GoodAction,
    GoInsureDialog,
    CpsProcessDetail,
    CpsRate,
    PlanTip,
    InsurePersonForm,
    AutoDeduct,
    ProtocolRead,
    NavTab
  },
  data() {
    return {
      ...Detail,
      goodId: "",
      goodActionInfo: {},
      goodBuyModalInfo: [],
      popupShow: false,
      currentPupopIndex: null,
      goodActionShow: false,
      calTimer: null,
      formData: {
        name: "",
        idNo: "",
        relation: "1",
        payType: "1",
        amountInsured: "1000000",
        autoRenewPolicy: false,
        read: false
      },
      goInsureState: false,
      isCalPrice: false
    };
  },
  watch: {
    headerInfo: {
      deep: true,
      immediate: true,
      handler(val) {
        const { amountInsured } = this.formData;
        const { price } = val;
        const _price = JSON.parse(JSON.stringify(price));
        _price[1] = "元/年起";
        this.goodActionInfo = { title: _price };
        this.goodBuyModalInfo = [{ title: `每年保费`, value: `${price[0]}元` }];
        this.noticeCellInfo[amountInsured][2].value = `${_price[0] + _price[1]}`;
      }
    },
    formDataCpu: {
      deep: true,
      handler(val, oldVal) {
        if (this.calTimer) {
          clearTimeout(this.calTimer);
        }
        const { idNo, amountInsured, relation, selfIdNo } = val;
        const { idNo: oldidNo, amountInsured: oldamountInsured, selfIdNo: oldselfIdNo } = oldVal;
        let idNoWho = !relation || relation === "1" ? selfIdNo : idNo;
        let oldidNoWho = !relation || relation === "1" ? oldselfIdNo : oldidNo;
        if (
          !relation ||
          !idNoWho ||
          !amountInsured ||
          (idNoWho.indexOf("************") === -1 &&
            !isIdNo(idNoWho) &&
            idNoWho === oldidNoWho &&
            amountInsured === oldamountInsured)
        ) {
          return;
        }
        this.calTimer = setTimeout(() => {
          this.calFee();
        }, 1000);
      }
    }
  },
  computed: {
    pupopData() {
      const { popupArray, currentPupopIndex, popupShow } = this;
      return popupShow ? popupArray[currentPupopIndex] || {} : {};
    },
    planCellData() {
      const { planCellInfo } = this;
      const { amountInsured } = this.formData;
      return planCellInfo[amountInsured];
    },
    noticeCellData() {
      const { noticeCellInfo } = this;
      const { amountInsured } = this.formData;
      return noticeCellInfo[amountInsured];
    },
    personFormOptions() {
      const { insuredOptions, paywayOptions } = this;
      return {
        insuredOptions,
        paywayOptions
      };
    },
    formDataCpu() {
      return JSON.parse(JSON.stringify(this.formData));
    }
  },
  created() {
    checkOpenId();
  },
  mounted() {
    this.getDetail();
  },
  methods: {
    openIframePupop(index) {
      if (index === 4) {
        this.$router.push({ path: "/goods/plan", query: { type: this.type } });
        return;
      }
      this.currentPupopIndex = index;
      this.popupShow = true;
    },
    onSubmit() {
      if (!this.isCalPrice) {
        this.$notify({ type: "warn", message: "被保人年龄不在可投保范围，请仔细核对" });
        return;
      }
      if (localStorage.get("mongoToken")) {
        this.$refs.insureForm.getFamilyList(true).then(() => {
          setTimeout(() => {
            this.getIsRead();
          }, 500);
        });
      } else {
        const { selfPhone, selfCode } = this.formData;
        this.login(selfPhone, selfCode).then(() => {
          this.$refs.insureForm.getFamilyList(true).then(() => {
            setTimeout(() => {
              this.getIsRead();
            }, 500);
          });
        });
      }
      // sessionStorage.setItem(
      //   "policyFormData",
      //   JSON.stringify(Object.assign(this.formData, { productNo: this.goodId }))
      // );
    },
    onFailed(errorInfo) {
      const { errors } = errorInfo;
      const noMsgArr = [
        "selfName",
        "selfIdNo",
        "selfPhone",
        "selfCode",
        "relativeName",
        "relativeIdNo"
      ];
      if (!noMsgArr.includes(errors[0].name)) {
        this.$notify({ type: "warning", message: errors[0].message });
      }
      this.$notify({ type: "warning", message: errors[0].message });
    },
    getIsRead() {
      if (this.formData.read) {
        this.nextStep();
      } else {
        this.goInsureState = true;
      }
    },
    nextStep() {
      this.generateFormData();
      this.goInsureState = false;
      this.generateOrder("ai");
    },
    generateFormData() {
      const {
        userInfoSecId,
        name,
        idNo,
        relation,
        selfName,
        selfIdNo,
        selfPhone,
        selfSecId,
        amountInsured,
        autoRenewPolicy
      } = this.formData;
      this.subFormData = {
        insuredUserInfo: {
          userInfoSecId: userInfoSecId ?? null,
          name,
          idNo,
          relation
        },
        productNo: this.goodId,
        holderUserInfo: {
          phoneNo: selfPhone,
          userInfoSecId: selfSecId ?? null,
          name: selfName,
          idNo: selfIdNo
        },
        productItem: {
          amountInsured
        },
        autoRenewPolicy: autoRenewPolicy
      };
      if (relation === "1") {
        this.subFormData.holderUserInfo.relation = relation;
        delete this.subFormData.insuredUserInfo;
      }
    },
    getRealIdNo() {
      const { relation, userInfoSecId: userId, idNo: idNoMask } = this.formData;
      const { selfSecId: holderUserId, selfIdNo: holderIdNoMask } = this.formData;
      let currentIdNo = !relation || relation === "1" ? holderIdNoMask : idNoMask;
      const currentUserId = !relation || relation === "1" ? holderUserId : userId;
      const familyList = this.$refs["insureForm"]?.familyList || [];
      if (!currentIdNo) return "";
      currentIdNo =
        currentIdNo.indexOf("**") > -1
          ? familyList.find(item => item.userInfoSecId === currentUserId).idNo
          : currentIdNo;
      return currentIdNo;
    },
    checkAgeInRange() {
      const currentIdNo = this.getRealIdNo();
      if (!currentIdNo) return;
      const birthday = getBirthDate(currentIdNo);
      const realAge = getRealAge(birthday);
      return realAge >= 18 && realAge <= 65;
    },
    async getDetail() {
      this.goodId = this.$route.query.id;
      const res = await list();
      if (res) {
        res.forEach(item => {
          if (item.productNo === this.goodId) {
            this.headerInfo.price[0] = item.downPayPrice;
            this.headerInfo.insuredNum = item.sellCount;
          }
        });
      }
    },
    async calFee() {
      let { price } = this.headerInfo;
      const { noticeCellInfo } = this;
      const { idNo, selfIdNo, relation, amountInsured, userInfoSecId, selfSecId } = this.formData;
      let idNoWho = !relation || relation === "1" ? selfIdNo : idNo;
      let idWho = !relation || relation === "1" ? selfSecId : userInfoSecId;
      idWho = idNoWho.indexOf("**") > -1 ? idWho || undefined : undefined;
      this.isCalPrice = this.checkAgeInRange();
      if (!this.isCalPrice || (!idNoWho && !amountInsured)) return;
      const _param = {
        productNo: this.goodId,
        productUserInfo: {
          insuredUserInfo: {
            idNo: idNoWho,
            userInfoSecId: idWho
          },
          productItem: {
            amountInsured
          }
        }
      };
      try {
        const res = await trail(_param);
        if (res) {
          price[0] = res.downPayPrice;
          price[1] = "元";
          price[3] = "/年";
          const _price = JSON.parse(JSON.stringify(price));
          _price[1] = "元/年";
          this.goodActionInfo = {
            title: _price
          };
          this.goodBuyModalInfo = [{ title: `每年保费`, value: `${price[0]}元` }];
          noticeCellInfo[amountInsured][2].value = `${_price[0] + _price[1]}`;
        }
        this.isCalPrice = true;
      } catch (error) {
        this.isCalPrice = false;
      }
    }
  }
};
</script>
<style lang="less" src="./index.less" scoped></style>
