<template>
  <cr-form scroll-to-error @submit="onSubmit" @failed="onFailed" class="container">
    <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" />
        <plan-tip :tip-list="planTipOptions" />
      </card>
      <div id="det_insure">
        <insure-person-form
          v-model="formData"
          :radio-options="personFormOptions"
          ref="insureForm"
        />
        <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" @click="openIframePupop(5)" />
      </div>
      <cps-qa :qa-data="qaInfo" />
    </div>
    <detail-footer :company-info="companyInfo" />
    <copyright />
    <good-action
      @leftClick="goInsureState = true"
      :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" />
    </popup-with-iframe>
    <go-insure-dialog
      v-model="goInsureState"
      :title="headerInfo.title"
      :pay-data="goodBuyModalInfo"
      @confirm="nextStep"
      @read-protocol="openIframePupop"
    />
  </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 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 { trail, list } from "@/api/product";
import localStorage from "@/service/localStorage";
import Detail from "@/api/detail.taikang.yiliaobaozhang";

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,
    CpsProcessDetail,
    CpsRate,
    PlanTip,
    InsurePersonForm,
    AutoDeduct,
    ProtocolRead,
    NavTab
  },
  data() {
    return {
      ...Detail,
      goodId: "",
      calTimer: null,
      goodActionInfo: {},
      goodBuyModalInfo: [],
      popupShow: false,
      currentPupopIndex: null,
      formData: {
        name: "",
        idNo: "",
        socialSecurity: "1",
        relation: "1",
        payType: "1",
        planValue: "3",
        autoRenewPolicy: false,
        read: true
      },
      goodActionShow: false,
      goInsureState: 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]}` }
        ];
      }
    },
    formDataCpu: {
      deep: true,
      handler(val, oldVal) {
        if (this.calTimer) {
          clearTimeout(this.calTimer);
        }
        const { idNo, socialSecurity, payType } = val;
        const { idNo: oldNo, socialSecurity: oldSocialSecurity, payType: oldType } = oldVal;
        if (idNo === oldNo && socialSecurity === oldSocialSecurity && payType === oldType) return;
        this.calTimer = setTimeout(() => {
          this.calFee();
        }, 600);
      }
    }
  },
  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 (localStorage.get("mongoToken")) {
        this.goInsureState = true;
        this.$refs.insureForm.getFamilyList();
      } else {
        const { selfPhone, selfCode } = this.formData;
        this.login(selfPhone, selfCode).then(() => {
          this.goInsureState = true;
          this.$refs.insureForm.getFamilyList();
        });
      }
      // sessionStorage.setItem("policyFormData", JSON.stringify(this.formData));
    },
    onFailed(errorInfo) {
      const { errors } = errorInfo;
      setTimeout(() => {
        this.$refs.navTab.showNavBar = false;
      }, 0);
      this.$notify({ type: "warning", message: errors[0].message });
    },
    nextStep() {
      this.generateFormData();
      this.generateOrder();
    },
    generateFormData() {
      const {
        userInfoSecId,
        name,
        idNo,
        relation,
        socialSecurity,
        selfSocialSecurity,
        selfName,
        selfIdNo,
        selfPhone,
        selfSecId,
        payType,
        autoRenewPolicy
      } = this.formData;
      this.subFromData = {
        productNo: this.goodId,
        holderUserInfo: {
          phoneNo: selfPhone,
          userInfoSecId: selfSecId ? selfSecId : null,
          name: selfName,
          idNo: selfIdNo
        },
        productItem: {
          payType
        },
        autoRenewPolicy: autoRenewPolicy
      };
      if (relation === "1") {
        this.subFromData.holderUserInfo.socialSecurity = !!Number(selfSocialSecurity);
        this.subFromData.productItem.socialSecurity = !!Number(selfSocialSecurity);
      } else {
        this.subFromData.insuredUserInfo = {
          userInfoSecId: userInfoSecId ? userInfoSecId : undefined,
          name,
          idNo,
          relation,
          socialSecurity: !!Number(socialSecurity)
        };
        this.subFromData.productItem.socialSecurity = !!Number(socialSecurity);
      }
    },
    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 } = this.formData;
      if (!idNo || !socialSecurity || !payType) return;
      const _param = {
        productNo: this.goodId,
        productUserInfo: {
          userInfo: {
            idNo,
            socialSecurity: !!Number(socialSecurity),
            userInfoSecId: userInfoSecId ? userInfoSecId : undefined
          },
          productItem: {
            payType
          }
        }
      };
      const res = await trail(_param);
      if (res) {
        price[0] = res.downPayPrice;
        subPrice[0] = res.regularPrice;
        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]}` }
        ];
      }
    }
  }
};
</script>
<style lang="less" src="./index.less" scoped></style>
