<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="li-header">
        <plan-tip :tip-list="planTipOptions" />
        <cr-divider :hairline="false" :style="{ color: '#ECE9E9' }" />
        <h5>什么样的人需要定期寿险？</h5>
        <p>有房贷、有车贷的家庭顶梁柱</p>
        <p>有子女抚养、老人赡养的家庭依靠</p>
        <p>家庭主要收入来源的贡献者</p>
      </div>
    </detail-header>
    <div class="det-body">
      <card
        title="保险计划"
        footer="true"
        :option="['查看详情']"
        @option-click="openIframePupop(4)"
      >
        <compactCellGroup :cell-data="planCellInfo" :text-bold="true" :font-size="14" />
        <div class="cal-footer" slot="footer">
          <div class="cal-footer-num">
            <h4>
              {{ headerInfo.price[0] }}<small>{{ headerInfo.price[1] }}</small>
            </h4>
          </div>
          <cr-button type="warning" @click="openIframePupop(6)">算一算保费</cr-button>
        </div>
      </card>
      <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>
      <div id="det_notice">
        <protocol-read
          title="投保须知"
          :options="[]"
          :text-bold="true"
          v-model="read"
          :show-radio="false"
          :cell-data="noticeCellInfo"
          @cell-click="openIframePupop"
        >
          <div class="important-intro">
            <h6 class="important-intro-title">重点说明</h6>
            <ul class="important-intro-list">
              <li class="important-intro-item">
                投保人可以为父母、配偶、子女，但是必须获得被保险人的同意并认可保险金额，如果未经被保险人同意并认可金额的，合同无效。
              </li>
              <li class="important-intro-item">
                等待期内，被保险人如因非意外导致身故或身体全残，保险公司返还合同实际交纳的保险费，保险合同终止。
              </li>
              <li class="important-intro-item">本产品为消费型，保险期满后不返还保费。</li>
              <li class="important-intro-item">
                本产品有20天犹豫期，在犹豫期内退保不收取任何费用，无息返还所交保费。犹豫期过后退保将承担保费损失。如需退保，请拨打华贵保险，客服电话400-684-1888。
              </li>
            </ul>
          </div>
        </protocol-read>
      </div>
      <div id="det_qa"><cps-qa :qa-data="qaInfo" /></div>
    </div>
    <detail-footer :company-info="companyInfo" />
    <copyright />
    <good-action :content="goodActionInfo" :class="{ 'cal-fee': currentPupopIndex === 6 }" />
    <popup-with-iframe
      v-model="popupShow"
      :title="pupopData.title"
      :content="pupopData.content"
      :url="pupopData.url"
    >
      <cal-insured-fee
        v-model="formData"
        @select-date="showBirthPickerHandler"
        v-if="currentPupopIndex === 6"
      />
    </popup-with-iframe>
    <div style="position: relative;z-index: 204;">
      <cr-popup v-model="showCalDate" position="bottom">
        <date-picker
          v-model="calBirth"
          type="date"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onBirthConfirm"
          @cancel="showCalDate = false"
        />
      </cr-popup>
    </div>
  </cr-form>
</template>

<script>
/**
 * @description: 华贵大麦2020定期寿险 Life insurance
 */
import DatePicker from "vant/lib/datetime-picker";
import "vant/lib/datetime-picker/style";
import { subYears, format as dateFormat } from "date-fns";
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 CalInsuredFee from "./modules/CalInsuredFee";
import PlanTip from "./modules/PlanTip";
import ProtocolRead from "./modules/ProtocolRead";
import NavTab from "./modules/NavTab";
import detailLoginMixin from "./modules/detailLogin.mixin";

import Detail from "@/api/detail.huagui.shouxian";
import { trail, list } from "@/api/product";

export default {
  name: "GoodsDetail-LI",
  components: {
    DetailHeader,
    DetailFooter,
    CompactCellGroup,
    // eslint-disable-next-line
    CrRadioBtn,
    Card,
    // eslint-disable-next-line
    Collapse,
    CpsCase,
    CpsProcess,
    CpsQa,
    Copyright,
    PopupWithIframe,
    GoodAction,
    PlanTip,
    NavTab,
    ProtocolRead,
    CalInsuredFee,
    DatePicker
  },
  mixins: [detailLoginMixin],
  data() {
    return {
      ...JSON.parse(JSON.stringify(Detail)),
      goodId: "",
      calTimer: null,
      goodActionInfo: {},
      goodActionShow: false,
      popupShow: false,
      currentPupopIndex: null,
      formData: {
        payType: "1"
      },
      minDate: subYears(new Date(), 60),
      maxDate: subYears(new Date(), 18),
      read: true,
      showLayer: false,
      showCalDate: false,
      calBirth: new Date("1990-01-01")
    };
  },
  watch: {
    popupShow(val) {
      if (!val && this.currentPupopIndex === 6) this.currentPupopIndex = null;
    },
    headerInfo: {
      deep: true,
      immediate: true,
      handler(val) {
        const { price } = val;
        this.goodActionInfo = { title: price };
      }
    },
    formDataCpu: {
      deep: true,
      handler(val, oldVal) {
        if (this.calTimer) {
          clearTimeout(this.calTimer);
        }
        const { read } = val;
        const { read: oldread } = oldVal;
        if (read !== oldread) return;
        this.calTimer = setTimeout(() => {
          this.calFee();
        }, 1200);
      }
    }
  },
  computed: {
    pupopData() {
      const { popupArray, currentPupopIndex } = this;
      return popupArray[currentPupopIndex] || {};
    },
    formDataCpu() {
      return JSON.parse(JSON.stringify(this.formData));
    }
  },
  mounted() {
    this.getDetail();
  },
  methods: {
    showBirthPickerHandler() {
      this.showCalDate = true;
    },
    onBirthConfirm(val) {
      this.showCalDate = false;
      this.$set(this.formData, "birth", val ? dateFormat(new Date(val), "yyyy-MM-dd") : "");
    },
    openIframePupop(index) {
      if (index === 4) {
        this.$router.push({ path: "/goods/plan", query: { type: this.type } });
        return;
      }
      this.currentPupopIndex = index;
      this.popupShow = true;
    },
    onSubmit() {
      // const { payPeriod, payType, policyPeriod, birth } = this.formData;
      // if (!payPeriod || !payType || !policyPeriod || !birth) {
      //   this.$notify({ type: "warning", message: "请选择保费方案" });
      //   this.popupShow = true;
      //   this.currentPupopIndex = 6;
      //   return;
      // }
      this.showLoginPopup();
      this.popupShow = false;
    },
    onFailed(errorInfo) {
      const { errors } = errorInfo;
      this.$notify({ type: "warning", message: errors[0].message });
    },
    nextStep() {
      sessionStorage.setItem(
        "policyFormData",
        JSON.stringify(Object.assign(this.formData, { productNo: this.goodId }))
      );
      const { userInfoSecId } = this.$route.query;
      this.$router.push({
        path: "/goods/inform",
        query: { url: this.popupArray[1].url, userInfoSecId, noOrder: true }
      });
      // this.$router.push({ path: "/policy/add", query: { queryId } });
    },
    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 { birth, gender, amountInsured, policyPeriod, payPeriod, payType } = this.formData;
      if (!birth || !gender || !amountInsured || !policyPeriod || !payPeriod || !payType) return;
      const _param = {
        productNo: this.goodId,
        productUserInfo: {
          insuredUserInfo: {
            birth,
            gender
          },
          productItem: {
            amountInsured,
            policyPeriod,
            payPeriod,
            payType
          }
        }
      };
      const res = await trail(_param);
      if (res) {
        price[1] = "元/年";
        price[0] = res.regularPrice;
        this.goodActionInfo = { title: price };
      }
    }
  }
};
</script>
<style lang="less" src="./index.less" scoped></style>
