<template>
  <cr-form
    scroll-to-error
    :scroll-offset="100"
    @submit="onSubmit"
    @failed="onFailed"
    class="container"
    ref="subForm"
  >
    <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)">
        <compactCellGroup :cell-data="planCellInfo" :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="noticeCellInfo"
          @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" :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-rate v-if="currentPupopIndex === 6" :rate-data="rateInfo" :is-mi="true" />
    </popup-with-iframe>
    <go-insure-dialog
      v-model="goInsureState"
      :title="headerInfo.title"
      :pay-data="goodBuyModalInfo"
      @confirm="nextStep"
      @read-protocol="openIframePupop"
    />
    <pay-wait-layer :value="isPayWait" />
  </cr-form>
</template>

<script>
/**
 * @description: 泰康600万医疗保障 medical 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 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 fromNow from "date-fns/formatDistanceToNowStrict";
import { trail, list } from "@/api/product";
import localStorage from "@/service/localStorage";
import { getRealAge, getBirthDate } from "@/service/utils";
import Detail from "@/api/detail.taikang.yiliaobaozhang";
import { isIdNo } from "@/service/validation";

let socialSecurityCache = "";
export default {
  name: "GoodsDetail-MI",
  mixins: [detailPayMixin, detailLoginMixin],
  components: {
    DetailHeader,
    DetailFooter,
    CompactCellGroup,
    // eslint-disable-next-line
    CrRadioBtn,
    Card,
    // eslint-disable-next-line
    Collapse,
    CpsCase,
    CpsProcess,
    CpsQa,
    Copyright,
    PopupWithIframe,
    GoodAction,
    GoInsureDialog,
    CpsRate,
    PlanTip,
    InsurePersonForm,
    AutoDeduct,
    ProtocolRead,
    NavTab
  },
  data() {
    return {
      ...Detail,
      goodId: "",
      calTimer: null,
      goodActionInfo: {},
      goodBuyModalInfo: [],
      popupShow: false,
      currentPupopIndex: null,
      formData: {
        name: "",
        idNo: "",
        socialSecurity: "",
        relation: "1",
        payType: "1",
        planValue: "3",
        autoRenewPolicy: false,
        read: false
      },
      goodActionShow: false,
      goInsureState: false,
      isCalPrice: false
    };
  },
  watch: {
    headerInfo: {
      deep: true,
      immediate: true,
      handler(val) {
        const { price, subPrice } = val;
        this.goodActionInfo = {
          title: price,
          sub: subPrice
        };
        this.goodBuyModalInfo = [
          { title: `${price[2]}保费`, value: `${price[0]}${price[1]}` },
          {
            title: `${subPrice[2]}保费`,
            value: `${subPrice[0]}${subPrice[1]}${subPrice[3]}`
          }
        ];
        this.noticeCellInfo[3].value.tpl = `<strong>保费与被保人年龄、有无社保有关<br />${price[2] +
          price[0] +
          price[1]}，${subPrice[0] ? subPrice[2] + subPrice[0] + subPrice[1] : ""}</strong>`;
      }
    },
    formDataCpu: {
      deep: true,
      handler(val, oldVal) {
        if (this.calTimer) {
          clearTimeout(this.calTimer);
        }
        const { idNo, relation, selfIdNo } = val;
        const { idNo: oldidNo, selfIdNo: oldselfIdNo } = oldVal;
        let idNoWho = !relation || relation === "1" ? selfIdNo : idNo;
        let oldidNoWho = !relation || relation === "1" ? oldselfIdNo : oldidNo;
        this.isCalPrice = this.checkAgeInRange();
        if (
          !this.isCalPrice ||
          !relation ||
          !idNoWho ||
          (idNoWho.indexOf("************") === -1 && !isIdNo(idNoWho) && idNoWho === oldidNoWho)
        )
          return;
        this.calTimer = setTimeout(() => {
          this.calFee();
        }, 1000);
      }
    }
  },
  computed: {
    pupopData() {
      const { popupArray, currentPupopIndex } = this;
      return popupArray[currentPupopIndex] || {};
    },
    personFormOptions() {
      const { insuredOptions, paywayOptions, medicalOptions } = this;
      return {
        insuredOptions,
        paywayOptions,
        medicalOptions
      };
    },
    formDataCpu() {
      return JSON.parse(JSON.stringify(this.formData));
    }
  },
  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: "warning", message: "被保人年龄不在可投保范围，请仔细核对" });
        return;
      }
      if (localStorage.get("mongoToken")) {
        socialSecurityCache = this.formData.socialSecurity;
        this.$refs.insureForm.getFamilyList(true).then(() => {
          setTimeout(() => {
            this.getIsRead();
          }, 500);
        });
      } else {
        socialSecurityCache = this.formData.socialSecurity;
        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(this.formData));
    },
    getIsRead() {
      if (this.formData.read) {
        this.nextStep();
      } else {
        this.goInsureState = true;
      }
    },
    onFailed(errorInfo) {
      const { errors } = errorInfo;
      const noMsgArr = [
        "selfName",
        "selfIdNo",
        "selfPhone",
        "selfCode",
        "relativeName",
        "relativeIdNo"
      ];
      console.log(errorInfo);
      if (!noMsgArr.includes(errors[0].name)) {
        this.$notify({ type: "warning", message: errors[0].message });
      }
    },
    nextStep() {
      this.generateFormData();
      this.goInsureState = false;
      this.generateOrder("mi");
    },
    generateFormData() {
      if (!this.formData.socialSecurity) {
        this.formData.socialSecurity = socialSecurityCache;
      }
      const subFormData = JSON.parse(JSON.stringify(this.formData));
      const {
        userInfoSecId,
        name,
        idNo,
        relation,
        socialSecurity,
        selfSocialSecurity,
        selfName,
        selfIdNo,
        selfPhone,
        selfSecId,
        payType,
        autoRenewPolicy
      } = subFormData;
      this.subFormData = {
        productNo: this.goodId,
        holderUserInfo: {
          phoneNo: selfPhone,
          userInfoSecId: selfSecId ? selfSecId : null,
          name: selfName,
          idNo: selfIdNo
        },
        productItem: {
          payType
        },
        autoRenewPolicy: autoRenewPolicy
      };
      if (relation === "1") {
        this.subFormData.holderUserInfo.socialSecurity = !Number(
          selfSocialSecurity || socialSecurityCache
        );
        this.subFormData.productItem.socialSecurity = !Number(
          selfSocialSecurity || socialSecurityCache
        );
      } else {
        this.subFormData.insuredUserInfo = {
          userInfoSecId: userInfoSecId ? userInfoSecId : undefined,
          name,
          idNo,
          relation,
          socialSecurity: !!Number(socialSecurity)
        };
        this.subFormData.productItem.socialSecurity = !!Number(socialSecurity);
      }
      if (relation === "1") {
        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 isOverMonth = birthday && parseInt(fromNow(new Date(birthday), { unit: "day" })) >= 30;
      return isOverMonth && getRealAge(birthday) <= 60;
    },
    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.subPrice[0] = item.regularPrice;
            this.headerInfo.insuredNum = item.sellCount;
          }
        });
      }
    },
    async calFee() {
      let { price, subPrice } = this.headerInfo;
      const {
        idNo,
        socialSecurity,
        payType,
        userInfoSecId,
        selfSecId,
        relation,
        selfIdNo
      } = 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 (!idNoWho || !payType || !socialSecurity || !this.isCalPrice) return;
      const _param = {
        productNo: this.goodId,
        productUserInfo: {
          insuredUserInfo: {
            idNo: idNoWho,
            socialSecurity: socialSecurity ? !!Number(socialSecurity) : undefined,
            userInfoSecId: idWho
          },
          productItem: {
            payType: payType || undefined,
            socialSecurity: socialSecurity ? !!Number(socialSecurity) : undefined
          }
        }
      };
      try {
        const res = await trail(_param);
        if (res) {
          price[2] = payType === "2" ? "" : "首月";
          price[0] = res.downPayPrice;
          subPrice[0] = payType === "2" ? "" : res.regularPrice;
          subPrice[1] = "元/月";
          this.goodActionInfo = {
            title: price,
            sub: subPrice[0] ? subPrice : ""
          };
          this.goodBuyModalInfo = [
            { title: `${price[2]}保费`, value: `${price[0]}${price[1]}` },
            {
              title: `${subPrice[2]}保费`,
              value: subPrice[0] ? `${subPrice[0]}${subPrice[1]}${subPrice[3]}` : ""
            }
          ];
          this.noticeCellInfo[3].value.tpl = `<strong>保费与被保人年龄、有无社保有关<br />${price[2] +
            price[0] +
            price[1]}，${subPrice[0] ? subPrice[2] + subPrice[0] + subPrice[1] : ""}</strong>`;
        }
        this.isCalPrice = true;
      } catch (error) {
        this.isCalPrice = false;
      }
    }
  }
};
</script>
<style lang="less" src="./index.less" scoped></style>
