<template>
  <div class="container" :class="{ 'ios-bottom': isIOS }">
    <div class="policy-tip-wrap">
      <div class="policy-tip">您所填写的数据，仅用于投保，平台将严格保密</div>
    </div>
    <cr-form
      ref="policyForm"
      class="policy-form"
      scroll-to-error
      :scroll-offset="100"
      @submit="onFormSubmit"
      @failed="onFormFailed"
    >
      <cr-cell-group title="投保人信息">
        <cr-field
          v-model="formData.holderUserInfo.name"
          name="holderUserInfo_name"
          label="姓名"
          placeholder="请填写投保人姓名"
          :readonly="selfInfoReadonly"
          :rules="[
            { required: true, message: '请填写投保人姓名' },
            {
              validator: isChineseNameMask,
              message: '请填写正确的投保人姓名，最少2个中文字符'
            }
          ]"
          @click.native="inputClick"
        />
        <cr-field
          v-model="formData.holderUserInfo.idNo"
          name="holderUserInfo_idNo"
          label="身份证号"
          placeholder="请填写投保人身份证号"
          :readonly="selfInfoReadonly"
          :rules="[
            { required: true, message: '请填写投保人身份证号' },
            {
              validator: isIdNoMask,
              message: '请填写正确的投保人身份证号'
            }
          ]"
          @click.native="inputClick"
        />
        <cr-field
          v-model="formData.holderUserInfo.phoneNo"
          name="holderUserInfo_phoneNo"
          type="tel"
          label="手机号"
          placeholder="请填写投保人手机号"
          :readonly="selfInfoReadonly"
          :rules="[
            { required: true, message: '请填写投保人手机号' },
            {
              validator: isPhoneMask,
              message: '请填写正确的投保人手机号'
            }
          ]"
          @click.native="inputClick"
        />
        <cr-field
          v-model="formData.holderUserInfo.email"
          name="holderUserInfo_email"
          type="email"
          label="电子邮箱"
          placeholder="用户接收电子保单"
          :rules="[
            { required: true, message: '请填写电子邮箱' },
            {
              validator: isEmail,
              message: '请填写正确的电子邮箱'
            }
          ]"
        />
        <cr-field
          v-model="formData.holderUserInfo.annualIncome"
          name="holderUserInfo_annualIncome"
          label="年收入"
          type="digit"
          placeholder="请填写投保人年收入"
          :rules="[{ required: true, message: '请填写投保人年收入' }]"
        >
          <div class="form-unit" slot="button">万元</div>
        </cr-field>
        <cr-field
          v-model="formData.holderUserInfo.addressCode"
          name="holderUserInfo_addressCode"
          label="居住省市"
          :rules="[{ required: true, message: '请选择投保人居住省市' }]"
        >
          <template #input>
            <popup-area-picker
              v-model="formData.holderUserInfo.addressCode"
              placeholder="请选择投保人居住省市"
            />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.holderUserInfo.addressDetail"
          name="holderUserInfo_addressDetail"
          label="详细地址"
          placeholder="请填写居住详细地址"
          :rules="[
            { required: true, message: '请填写投保人居住详细地址' },
            {
              validator: isChnAddress,
              message: '请填写正确的地址，至少于5个汉字，且必须有1位数字'
            }
          ]"
        />
        <cr-field
          v-model="formData.holderUserInfo.occupation"
          name="holderUserInfo_occupation"
          label="职业"
          :rules="[{ required: true, message: '请选择投保人职业' }]"
        >
          <template #input>
            <popup-cascade
              v-model="formData.holderUserInfo.occupation"
              placeholder="请选择投保人职业"
            />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.holderUserInfo.longTerm"
          name="holderUserInfo_longTerm"
          label="身份证有效期"
          :rules="[{ required: true, message: '请选择投保人身份证有效期' }]"
        >
          <template #input>
            <cr-radio-btn
              v-model="formData.holderUserInfo.longTerm"
              :radio-data="idCardInvaildOptions"
            />
          </template>
        </cr-field>
        <cr-field
          v-if="formData.holderUserInfo.longTerm === '1'"
          v-model="formData.holderUserInfo.validEnd"
          name="holderUserInfo_validEnd"
          label="有效期至"
          :rules="[
            { required: true, message: '请选择投保人身份证止期' },
            {
              validator: isFutureDate,
              message: '投保人身份证止期必须大于当前日期'
            }
          ]"
        >
          <template #input>
            <popup-date-picker
              v-model="formData.holderUserInfo.validEnd"
              :min-date="minDate"
              :max-date="maxDate"
              placeholder="请选择您的证件有效止期"
            />
          </template>
        </cr-field>
      </cr-cell-group>
      <cr-cell-group title="被保人信息">
        <cr-field
          v-model="formData.insuredUserInfo.relation"
          name="insuredUserInfo_relation"
          label="为谁投保"
        >
          <template #input>
            <cr-radio-btn
              v-model="formData.insuredUserInfo.relation"
              @input="relationOptionChange"
              :radio-data="insuredOptions"
            />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.insuredUserInfo.socialSecurity"
          name="insuredUserInfo_socialSecurity"
          label="有无社保"
          :rules="[{ required: true, message: '请选择社保状态' }]"
        >
          <template #input>
            <cr-radio-btn
              v-model="formData.insuredUserInfo.socialSecurity"
              :radio-data="socialSecOptions"
            />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.insuredUserInfo.height"
          name="insuredUserInfo_height"
          label="身高"
          type="number"
          placeholder="请填写被保人身高"
          :rules="[
            { required: true, message: '请填写被保人身高' },
            {
              validator: isIntegerHeight,
              message: '请填写正确的被保人身高，最多3个数字'
            }
          ]"
        >
          <div class="form-unit" slot="button">厘米</div>
        </cr-field>
        <cr-field
          v-model="formData.insuredUserInfo.weight"
          name="insuredUserInfo_weight"
          label="体重"
          type="number"
          placeholder="请填写被保人体重"
          :rules="[
            { required: true, message: '请填写被保人体重' },
            {
              validator: isIntegerHeight,
              message: '请填写正确的被保人体重，最多3个数字'
            }
          ]"
        >
          <div class="form-unit" slot="button">公斤</div>
        </cr-field>
        <template v-if="formData.insuredUserInfo.relation !== '1'">
          <cr-field
            v-model="formData.insuredUserInfo.name"
            name="insuredUserInfo_name"
            label="姓名"
            placeholder="请填写被保人姓名"
            :readonly="infoReadonly"
            :rules="[
              { required: true, message: '请填写投保人姓名' },
              {
                validator: isChineseNameMask,
                message: '请填写正确的被保人姓名，最少2个中文字符'
              }
            ]"
          >
            <cr-icon
              type="arrow"
              slot="button"
              v-if="relationList.length > 1"
              class="relation-select"
              @click="showRelations = true"
            />
          </cr-field>
          <cr-field
            v-model="formData.insuredUserInfo.idNo"
            name="insuredUserInfo_idNo"
            label="身份证号"
            placeholder="请填写被保人身份证号"
            :readonly="infoReadonly"
            :rules="[
              { required: true, message: '请填写被保人身份证号' },
              {
                validator: isIdNoMask,
                message: '请填写正确的被保人身份证号'
              }
            ]"
          />
          <cr-field
            v-model="formData.insuredUserInfo.phoneNo"
            name="insuredUserInfo_phoneNo"
            label="手机号"
            type="tel"
            placeholder="请填写被保人手机号"
            :rules="[
              { required: true, message: '请填写被保人手机号' },
              {
                validator: isPhoneMask,
                message: '请填写正确的被保人手机号'
              }
            ]"
          />
          <cr-field
            v-model="formData.insuredUserInfo.annualIncome"
            name="insuredUserInfo_annualIncome"
            label="年收入"
            type="digit"
            placeholder="请填写被保人年收入"
            :rules="[{ required: true, message: '请填写被保人年收入' }]"
          >
            <div class="form-unit" slot="button">万元</div>
          </cr-field>
          <cr-field
            v-model="formData.insuredUserInfo.addressCode"
            name="insuredUserInfo_addressCode"
            label="居住省市"
            :rules="[{ required: true, message: '请选择被保人居住省市' }]"
          >
            <template #input>
              <popup-area-picker
                v-model="formData.insuredUserInfo.addressCode"
                placeholder="请选择被保人居住省市"
              />
            </template>
          </cr-field>
          <cr-field
            v-model="formData.insuredUserInfo.addressDetail"
            name="insuredUserInfo_weigaddressDetailht"
            label="详细地址"
            placeholder="请填写被保人居住详细地址"
            :rules="[
              { required: true, message: '请填写被保人居住详细地址' },
              {
                validator: isChnAddress,
                message: '请填写正确的地址，至少于5个汉字，且必须有1位数字'
              }
            ]"
          />
          <cr-field
            v-model="formData.insuredUserInfo.occupation"
            name="insuredUserInfo_occupation"
            label="职业"
            :rules="[{ required: true, message: '请选择被保人职业' }]"
          >
            <template #input>
              <popup-cascade
                v-model="formData.insuredUserInfo.occupation"
                placeholder="请选择被保人职业"
                :is-lite="true"
              />
            </template>
          </cr-field>
          <cr-field
            v-model="formData.insuredUserInfo.longTerm"
            name="insuredUserInfo_longTerm"
            label="身份证有效期"
            :rules="[{ required: true, message: '请选择被保人身份证有效期' }]"
          >
            <template #input>
              <cr-radio-btn
                v-model="formData.insuredUserInfo.longTerm"
                :radio-data="idCardInvaildOptions"
              />
            </template>
          </cr-field>
          <cr-field
            v-if="formData.insuredUserInfo.longTerm === '1'"
            v-model="formData.insuredUserInfo.validEnd"
            name="insuredUserInfo_validEnd"
            label="有效期至"
            :rules="[
              { required: true, message: '请选择被保人身份证止期' },
              {
                validator: isFutureDate,
                message: '被保人身份证止期必须大于当前日期'
              }
            ]"
          >
            <template #input>
              <popup-date-picker
                v-model="formData.insuredUserInfo.validEnd"
                :min-date="minDate"
                :max-date="maxDate"
                placeholder="请选择您的证件有效止期"
              />
            </template>
          </cr-field>
        </template>
      </cr-cell-group>
      <cr-cell-group title="保障方案">
        <cr-field
          v-model="formData.productItem.amountInsured"
          name="productItem_insuredAmount"
          label="投保限额"
          :rules="[{ required: true, message: '请选择投保限额' }]"
        >
          <template #input>
            <stepper v-model="formData.productItem.amountInsured" :option="amountOptions" />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.productItem.policyPeriod"
          name="productItem_policyPeriod"
          label="保险期限"
          :rules="[{ required: true, message: '请选择保险期限' }]"
        >
          <template #input>
            <cr-radio-btn
              v-model="formData.productItem.policyPeriod"
              :radio-data="insureTermOptions"
            />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.productItem.payType"
          name="payPeriod"
          label="交费方式"
          :rules="[{ required: true, message: '请选择交费方式' }]"
        >
          <template #input>
            <cr-radio-btn v-model="formData.productItem.payType" :radio-data="paywayOptions" />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.productItem.payPeriod"
          name="productItem_paymentPeriod"
          label="交费期间"
          :rules="[{ required: true, message: '请选择交费期间' }]"
        >
          <template #input>
            <cr-radio-btn
              v-model="formData.productItem.payPeriod"
              :radio-data="insureBenefitOptions"
            />
          </template>
        </cr-field>
        <cr-field :value="formData.effectiveDate" name="effectiveDate" readonly label="生效日期" />
        <cr-field value="法定" name="beneficiaryUser" disabled label="受益人" />
      </cr-cell-group>
      <cr-cell-group title="续费银行账户">
        <cr-field
          :value="formData.holderUserInfo.name"
          name="insuredUserInfo_bankCardName"
          disabled
          label="持卡人"
          placeholder="请填写持卡人姓名"
        />
        <cr-field
          v-model="formData.holderUserInfo.bankCardCode"
          name="insuredUserInfo_bankCardCode"
          label="开户行"
          :rules="[{ required: true, message: '请选择开户行' }]"
        >
          <template #input>
            <popup-picker
              v-model="formData.holderUserInfo.bankCardCode"
              :picker-data="bankInfo"
              placeholder="请选择开户行"
            />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.holderUserInfo.bankCardNo"
          name="insuredUserInfo_bankCardNo"
          label="银行卡号"
          type="digit"
          placeholder="请填写银行卡号"
          :rules="[
            { required: true, message: '请填写银行卡号' },
            {
              validator: isBankNumber,
              message: '请填写正确的银行卡号'
            }
          ]"
        />
      </cr-cell-group>
      <cr-field
        name="pact"
        :rules="[{ required: true, message: '请阅读协议并确认' }]"
        class="protocol-radio"
      >
        <template #input>
          <cr-checkbox shape="round" icon-size="13px" v-model="pact" checked-color="#FFC842">
            投保前请阅读
          </cr-checkbox>
          <div class="pay-protocol-link">
            <a href="javascript:;" @click="openIframePupop(0)">保险条款</a>
            <i></i>
            <a href="javascript:;" @click="openIframePupop(2)">投保须知与声明</a>
            <i></i>
            <a href="javascript:;" @click="openIframePupop(3)">服务协议</a>
            <i></i>
            <a href="javascript:;" @click="openIframePupop(11)">转账授权书</a>
            <i></i>
            <a href="javascript:;" @click="openIframePupop(8)">人身保险投保提示书</a>
            <i></i>
            <a href="javascript:;" @click="openIframePupop(9)">税收居民身份证明</a>
            <i></i>
            <a href="javascript:;" @click="openIframePupop(10)">风控查询授权说明书</a>
            <i></i>
            <a href="javascript:;" @click="openIframePupop(12)">被保人同意声明</a>
          </div>
        </template>
      </cr-field>
      <good-action :content="goodActionInfo" />
    </cr-form>
    <go-insure-dialog
      v-model="goInsureState"
      :title="headerInfo.title"
      :pay-data="goodBuyModalInfo"
      @confirm="nextStep"
    >
      <div class="pay-protocol">
        <div class="pay-protocol-tip"><span>投保前请阅读</span><span>*犹豫期免费退保</span></div>
        <div class="pay-protocol-link">
          <a href="javascript:;" @click="openIframePupop(0)">保险条款</a>
          <i></i>
          <a href="javascript:;" @click="openIframePupop(2)">投保须知与声明</a>
          <i></i>
          <a href="javascript:;" @click="openIframePupop(3)">服务协议</a>
          <i></i>
          <a href="javascript:;" @click="openIframePupop(11)">转账授权书</a>
        </div>
        <div class="pay-protocol-link pay-protocol-link_wrap">
          <a href="javascript:;" @click="openIframePupop(8)">人身保险投保提示书</a>
          <a href="javascript:;" @click="openIframePupop(9)">税收居民身份证明</a>
          <a href="javascript:;" @click="openIframePupop(10)">风控查询授权说明书</a>
          <a href="javascript:;" @click="openIframePupop(12)">被保人同意声明</a>
        </div>
      </div>
    </go-insure-dialog>
    <popup-with-iframe
      v-model="popupShow"
      :title="pupopData.title"
      :content="pupopData.content"
      :url="pupopData.url"
    >
    </popup-with-iframe>
    <cr-popup v-model="showRelations" position="bottom" get-container="body">
      <cr-picker
        ref="relationsPicker"
        :columns="relationList"
        value-key="nameMask"
        show-toolbar
        @cancel="onRelationCancel"
        @confirm="onRelationConfirm"
      />
    </cr-popup>
    <pay-wait-layer :value="isPayWait" />
  </div>
</template>

<script>
import GoodAction from "@/components/GoodAction";
import CrRadioBtn from "@/components/CrRadioBtn";
import PopupAreaPicker from "@/components/PopupAreaPicker";
import PopupPicker from "@/components/PopupPicker";
import PopupDatePicker from "@/components/PopupDatePicker";
import PopupWithIframe from "@/components/PopupWithIframe";
import PopupCascade from "@/components/PopupCascade";
import Stepper from "@/components/Stepper";
import GoInsureDialog from "@/views/Goods/Detail/modules/GoInsureDialog";
import detailPayMixin from "@/views/Goods/Detail/modules/detailPay.mixin";
import autoSaveForm from "@/mixins/autoSaveForm.mixin";
import liCalFee from "@/views/Goods/Detail/modules/liCalFee.mixin";
import { addDays, addYears, format as dateFormat } from "date-fns";
import { debounce } from "lodash-es";
import { getRealAge, getBirthDate } from "@/service/utils";
import localStorage from "@/service/localStorage";
import { mapState, mapActions } from "vuex";
import Detail from "@/api/detail.huagui.shouxian";
import { list, trail } from "@/api/product";
import { getFamilyList } from "@/api/user";
import {
  isIdNo,
  isChineseName,
  isPhone,
  isEmail,
  isInteger,
  isBankNumber,
  isChnAddress,
  isIOS
} from "@/service/validation";

const AUTO_SAVE_KEY = "PolicyFormData";
const AUTO_SAVE_TARGET = "formData";
const {
  headerInfo,
  popupArray,
  paywayOptions,
  insuredAmountOptions,
  termOptions,
  benefitOptions,
  insuredOptions,
  idCardInvaildOptions,
  socialSecOptions,
  bankInfo
} = JSON.parse(JSON.stringify(Detail));
export default {
  name: "AddPolicy",
  mixins: [detailPayMixin, autoSaveForm, liCalFee],
  components: {
    GoodAction,
    CrRadioBtn,
    GoInsureDialog,
    PopupAreaPicker,
    PopupDatePicker,
    PopupWithIframe,
    PopupPicker,
    PopupCascade,
    Stepper
  },
  data() {
    return {
      popupArray,
      headerInfo,
      calTimer: null,
      minDate: addDays(new Date(), 1),
      maxDate: addYears(new Date(), 100),
      clearInsured: false,
      goInsureState: false,
      popupShow: false,
      currentPupopIndex: null,
      goodActionInfo: {},
      goodBuyModalInfo: [],
      mongoToken: localStorage.get("mongoToken"),
      policyFormData: JSON.parse(sessionStorage.getItem("policyFormData") || "{}"),
      pact: false,
      formData: {
        insuredUserInfo: {
          relation: "1",
          longTerm: "1"
        },
        holderUserInfo: {
          longTerm: "1"
        },
        productItem: {
          amountInsured: "500000",
          payType: "1"
        },
        payPeriod: "1"
      },
      subFormData: {},
      familyList: [],
      formMaskData: {},
      idCardInvaildOptions,
      socialSecOptions,
      insuredOptions,
      termOptions,
      paywayOptions,
      benefitOptions,
      countOptions: insuredAmountOptions,
      bankInfo,
      isIOS,
      selfInfoReadonly: false,
      infoReadonly: false,
      showRelations: false,
      refreshed: false,
      relationList: []
    };
  },
  watch: {
    showRelations(val) {
      if (val && !this.refreshed && this.$refs["relationsPicker"]) {
        const $relationsPicker = this.$refs["relationsPicker"];
        $relationsPicker.formattedColumns = $relationsPicker.formatColumns(this.relationList);
        setTimeout(() => {
          this.refreshed = true;
          $relationsPicker.refreshColumns();
        }, 500);
      } else {
        this.refreshed = false;
      }
    },
    popupShow(val) {
      if (!val && this.currentPupopIndex === 6) this.currentPupopIndex = null;
    },
    userInfo: {
      immediate: true,
      deep: true,
      handler(val) {
        this.formData.holderUserInfo.phoneNo =
          val.phoneNoMask && val.phoneNoMask !== "点击登录" ? val.phoneNoMask : "";
      }
    },
    headerInfo: {
      deep: true,
      handler(val) {
        const { price } = val;
        this.goodActionInfo = {
          title: price
        };
        this.goodBuyModalInfo = [{ title: `${price[2]}保费`, value: `${price[0]}${price[1]}` }];
      }
    },
    formDataCpu: {
      deep: true,
      handler(val, oldVal) {
        this.autoSaveHandler(AUTO_SAVE_TARGET, AUTO_SAVE_KEY);
        if (this.calTimer) {
          clearTimeout(this.calTimer);
        }
        const { relation, idNo } = val.insuredUserInfo;
        const { amountInsured, policyPeriod, payPeriod, payType } = val.productItem;
        const { idNo: oldIdNo } = oldVal.insuredUserInfo;
        const {
          amountInsured: oldamountInsured,
          policyPeriod: oldpolicyPeriod,
          payPeriod: oldpayPeriod,
          payType: oldpayType
        } = oldVal.productItem;
        let idNoWho = !relation || relation === "1" ? val.holderUserInfo.idNo : idNo;
        let oldidNoWho = !relation || relation === "1" ? oldVal.holderUserInfo.idNo : oldIdNo;
        this.setEffectiveDate();
        if (
          (idNoWho && idNoWho.indexOf("************") === -1 && !isIdNo(idNoWho)) ||
          (idNoWho === oldidNoWho &&
            amountInsured === oldamountInsured &&
            policyPeriod === oldpolicyPeriod &&
            payPeriod === oldpayPeriod &&
            payType === oldpayType)
        )
          return;
        this.calTimer = setTimeout(() => {
          this.calFee();
        }, 1000);
      }
    },
    showAuthXyqb: {
      immediate: true,
      handler(val) {
        if (val === 4) {
          const xyqbUserInfo = localStorage.get("xyqbUserInfo");
          this.formData.holderUserInfo.name = xyqbUserInfo.nameMask;
          this.formData.holderUserInfo.idNo = xyqbUserInfo.idNoMask;
          this.formData.holderUserInfo.phoneNo = xyqbUserInfo.phoneNoMask;
          this.selfInfoReadonly = true;
          this.$forceUpdate();
        }
      }
    }
  },
  computed: {
    ...mapState(["showAuthXyqb"]),
    ...mapState("user", ["userInfo"]),
    age() {
      const currentIdNo = this.getRealIdNo();
      if (!currentIdNo) return 18;
      const birthday = getBirthDate(currentIdNo);
      if (!birthday) return 18;
      const userAge = birthday ? getRealAge(birthday) : "";
      return isNaN(userAge) ? 18 : userAge;
    },
    pupopData() {
      const { popupArray, currentPupopIndex } = this;
      return popupArray[currentPupopIndex] || {};
    },
    socialSecurityReadonly() {
      const { relation } = this.formData.insuredUserInfo;
      const { selfInfoReadonly, infoReadonly } = this;
      return (relation === "1" && selfInfoReadonly) || (relation !== "1" && infoReadonly);
    },
    formDataCpu() {
      return JSON.parse(JSON.stringify(this.formData));
    }
  },
  mounted() {
    this.getParamFromSession();
    this.getDetail();
    this.getFamilyList();
  },
  methods: {
    isIdNoMask(str) {
      if (str && str.indexOf("************") > -1) {
        return true;
      } else {
        return isIdNo(str);
      }
    },
    isChineseNameMask(str) {
      if (str && str.indexOf("*") > -1) {
        return true;
      } else {
        return isChineseName(str);
      }
    },
    isPhoneMask(str) {
      if (str && str.indexOf("****") > -1) {
        return true;
      } else {
        return isPhone(str);
      }
    },
    isEmail,
    isBankNumber,
    isChnAddress,
    isIntegerHeight(str) {
      return isInteger(str) && str.length <= 3;
    },
    isFutureDate(str) {
      if (str) {
        const currentTimestamp = new Date().valueOf();
        const selectTimestamp = new Date(str).valueOf();
        return selectTimestamp > currentTimestamp;
      }
      return false;
    },
    ...mapActions(["setAuthXyqb"]),
    ...mapActions("user", ["setUserInfo"]),
    inputClick() {
      if (!localStorage.get("mongoToken") && this.showAuthXyqb === 1) {
        this.setAuthXyqb(2);
      }
    },
    onRelationCancel() {
      this.showRelations = false;
    },
    onRelationConfirm(picker, res) {
      // console.log(res[0]);
      const { idNoMask, nameMask, userInfoSecId, socialSecurity } = res[0];
      this.formData.insuredUserInfo = {
        ...this.formData.insuredUserInfo,
        ...{
          idNo: idNoMask,
          name: nameMask,
          userInfoSecId,
          socialSecurity:
            socialSecurity === "" || typeof socialSecurity === "undefined"
              ? ""
              : socialSecurity
              ? "1"
              : "0"
        }
      };
      this.onRelationCancel();
    },
    onFormSubmit() {
      this.getIsRead();
    },
    onFormFailed(errorInfo) {
      console.log(errorInfo);
      const { errors } = errorInfo;
      this.$notify({ type: "warning", message: errors[0].message });
    },
    getIsRead() {
      if (this.pact) {
        this.nextStep();
      } else {
        this.goInsureState = true;
      }
    },
    nextStep() {
      this.subFormData = JSON.parse(JSON.stringify(this.formData));
      const channel = localStorage.get("channelId");
      const { socialSecurity, longTerm, relation } = this.subFormData.insuredUserInfo;
      this.subFormData.insuredUserInfo.socialSecurity = socialSecurity === "1" ? true : false;
      this.subFormData.insuredUserInfo.longTerm = longTerm === "2" ? true : false;
      this.subFormData.holderUserInfo.longTerm = longTerm === "2" ? true : false;
      this.subFormData.channel = channel ? channel : undefined;
      if (relation === "1") {
        const selfInfo = this.familyList.find(item => item.relation === 1);
        const { weight, height, socialSecurity } = this.subFormData.insuredUserInfo;
        this.subFormData.holderUserInfo = {
          ...this.subFormData.holderUserInfo,
          ...{
            weight,
            height,
            socialSecurity
          }
        };
        if (selfInfo && selfInfo.idNo) {
          const { idNo, name, userInfoSecId, socialSecurity } = selfInfo;
          this.subFormData.holderUserInfo = {
            ...this.subFormData.holderUserInfo,
            ...{
              idNo,
              name,
              userInfoSecId
            }
          };
          if (socialSecurity) {
            this.formData.holderUserInfo.socialSecurity = socialSecurity;
          }
        }
        delete this.subFormData.insuredUserInfo;
      }
      sessionStorage.setItem("policyFormData", JSON.stringify(this.subFormData));
      // this.$router.push({ path: "/goods/inform", query: { url: popupArray[1].url } });
      this.goInsureState = false;
      this.generateOrder("li");
    },
    relationOptionChange(relation) {
      relation && this.relationChange(relation, true);
      this.clearInsured = true;
    },
    relationChange(relation, clear = false) {
      if (clear) {
        this.$set(this.formData, "insuredUserInfo", {
          relation,
          longTerm: "1"
        });
        this.$forceUpdate();
      }
      this.familyList.forEach(item => {
        const { relation, nameMask: name, idNoMask: idNo, userInfoSecId } = item;
        if (+relation === 1) {
          this.formData.holderUserInfo = {
            ...this.formData.holderUserInfo,
            ...{ name, idNo, userInfoSecId }
          };
          this.selfInfoReadonly = true;
        }
      });
      const userArray = this.familyList.filter(
        item => item.relation === +relation && item.relation !== 1
      );
      let [name, idNo, userInfoSecId, socialSecurity] = [undefined, undefined, undefined, ""];
      if (userArray.length) {
        let { nameMask, idNoMask, userInfoSecId: id, socialSecurity: ss } = userArray[0];
        [name, idNo, userInfoSecId, socialSecurity] = [nameMask, idNoMask, id, ss];
        this.infoReadonly = true;
      } else {
        if (relation === "1") {
          userInfoSecId = this.formData.holderUserInfo.userInfoSecId;
        }
        this.infoReadonly = false;
      }
      this.relationList = userArray.length > 1 ? userArray : [];
      this.formData.insuredUserInfo = {
        ...this.formData.insuredUserInfo,
        ...{
          name,
          idNo,
          userInfoSecId,
          socialSecurity:
            typeof socialSecurity === undefined || socialSecurity === ""
              ? ""
              : socialSecurity
              ? "1"
              : "0"
        }
      };
      if (!this.formData.insuredUserInfo.socialSecurity) {
        try {
          this.formData.insuredUserInfo.socialSecurity = this[
            AUTO_SAVE_TARGET + "Cache"
          ].insuredUserInfo.socialSecurity;
        } catch (e) {
          //
        }
      }
      if (relation) {
        this.formData.insuredUserInfo.relation = "" + relation;
      }
      this.calFee();
      this.$forceUpdate();
    },
    openIframePupop(index) {
      this.currentPupopIndex = index;
      this.popupShow = true;
    },
    getParamFromSession() {
      const { amountInsured, policyPeriod, payPeriod, payType, productNo } = this.policyFormData;
      this.formData.productNo = productNo;
      if (amountInsured && policyPeriod && payPeriod && payType) {
        this.formData.productItem = {
          ...this.formData.productItem,
          ...{ amountInsured, policyPeriod, payPeriod, payType }
        };
      }
      this.$forceUpdate();
    },
    getRealIdNo() {
      const { relation, userInfoSecId: userId, idNo: idNoMask } = this.formData.insuredUserInfo;
      const { userInfoSecId: holderUserId, idNo: holderIdNoMask } = this.formData.holderUserInfo;
      let currentIdNo = !relation || relation === "1" ? holderIdNoMask : idNoMask;
      const currentUserId = !relation || relation === "1" ? holderUserId : userId;
      if (!currentIdNo) return "";
      currentIdNo =
        currentIdNo.indexOf("**") > -1
          ? this.familyList.find(item => item.userInfoSecId === currentUserId).idNo
          : currentIdNo;
      return currentIdNo;
    },
    setEffectiveDate: debounce(function() {
      const currentIdNo = this.getRealIdNo();
      if (!currentIdNo) return;
      const birthday = getBirthDate(currentIdNo);
      const birthdayArr = birthday.split("-");
      const currentdayArr = dateFormat(new Date(), "yyyy-MM-dd").split("-");
      const nextDate =
        birthdayArr[1] === currentdayArr[1] && +currentdayArr[2] === +birthdayArr[2] - 1
          ? new Date()
          : addDays(new Date(), 1);
      this.formData.effectiveDate = dateFormat(nextDate, "yyyy-MM-dd") + " 00:00:00";
    }),
    resetFormItemVal(key, val) {
      const currentIdNo = this.getRealIdNo();
      const birthday = getBirthDate(currentIdNo);
      if (birthday && this.formData.productItem[key] === val && val) {
        switch (key) {
          case "amountInsured":
            this.$notify({ type: "warning", message: "已超出该年龄承保的最高保额，请重新选择" });
            break;
          case "policyPeriod":
          case "payPeriod":
            this.$notify({ type: "warning", message: "交费期间不应长于保障期间，请重新选择" });
            break;
          default:
            break;
        }
      }
      if (this.formData.productItem[key] === val) {
        this.$set(this.formData.productItem, key, "");
      }
    },
    async getDetail() {
      const res = await list();
      if (res) {
        res.forEach(item => {
          if (item.productNo === this.formData.productNo) {
            this.headerInfo.price[0] = item.downPayPrice;
            const price = this.headerInfo.price;
            price[1] = "元/起";
            this.goodActionInfo = {
              title: price
            };
            this.goodBuyModalInfo = [{ title: `保费`, value: `${price[0]}${price[1]}` }];
          }
        });
      }
    },
    async getFamilyList() {
      if (!this.mongoToken) return;
      this.setUserInfo();
      const res = await getFamilyList();
      if (res) {
        this.familyList = res;
        if (this.hasAutoSaveData(AUTO_SAVE_KEY)) {
          this.getSaveInfoHandler(AUTO_SAVE_KEY, AUTO_SAVE_TARGET);
          const { relation, idNo, userInfoSecId, selfIdNo } = this.formData.insuredUserInfo;
          const selfUserInfo = this.familyList.find(item => item.relation === 1);
          if (selfUserInfo && selfUserInfo.idNo && selfIdNo) {
            const { idNoMask, nameMask, socialSecurity, userInfoSecId } = selfUserInfo;
            this.formData = {
              ...this.formData,
              ...{
                selfIdNo: idNoMask,
                selfName: nameMask,
                selfSecId: userInfoSecId,
                selfSocialSecurity:
                  typeof socialSecurity === undefined || socialSecurity === ""
                    ? ""
                    : socialSecurity
                    ? "1"
                    : "0"
              }
            };
            this.selfInfoReadonly = true;
          }
          if (relation) {
            const userArray = this.familyList.filter(item => item.relation === +relation);
            this.relationList = userArray.length > 1 ? userArray : [];
            if (idNo && !userInfoSecId) {
              this.familyList.forEach(item => {
                if (item.idNo === idNo) {
                  const { idNoMask, nameMask, socialSecurity, userInfoSecId } = item;
                  this.formData.insuredUserInfo = {
                    ...this.formData.insuredUserInfo,
                    ...{
                      idNo: idNoMask,
                      name: nameMask,
                      userInfoSecId,
                      socialSecurity:
                        typeof socialSecurity === undefined || socialSecurity === ""
                          ? ""
                          : socialSecurity
                          ? "1"
                          : "0"
                    }
                  };
                }
              });
            }
          }
          if (!this.formData.holderUserInfo.name) {
            const selfInfo = this.familyList.find(item => item.relation === 1);
            this.selfInfoReadonly = !!selfInfo;
            if (selfInfo) {
              const { idNoMask: idNo, nameMask: name, userInfoSecId } = selfInfo;
              this.formData.holderUserInfo = {
                ...this.formData.holderUserInfo,
                ...{
                  idNo,
                  name,
                  userInfoSecId
                }
              };
            }
          }
        } else {
          let relation = this.formData.insuredUserInfo.relation;
          (this.showAuthXyqb || this.mongoToken) && this.relationChange(relation, false);
        }
      }
    },
    async calFee() {
      let { price } = this.headerInfo;
      const { amountInsured, policyPeriod, payPeriod, payType } = this.formData.productItem;
      const {
        relation,
        userInfoSecId: insureidId,
        idNo: insureidNo,
        socialSecurity
      } = this.formData.insuredUserInfo;
      let idNo = "";
      let userInfoSecId = undefined;
      if (!relation || relation === "1") {
        userInfoSecId = this.formData.holderUserInfo.userInfoSecId;
        idNo = this.formData.holderUserInfo.idNo;
      } else {
        userInfoSecId = insureidId;
        idNo = insureidNo;
      }
      if (!amountInsured || !policyPeriod || !payPeriod || !payType || !idNo) return;
      const _param = {
        productNo: this.formData.productNo,
        productUserInfo: {
          insuredUserInfo: {
            idNo,
            userInfoSecId,
            socialSecurity: socialSecurity === "1" ? true : false
          },
          productItem: {
            amountInsured,
            policyPeriod,
            payPeriod,
            payType
          }
        }
      };
      const res = await trail(_param);
      if (res) {
        price[1] = "元/年";
        price[0] = res.downPayPrice;
        this.goodActionInfo = {
          title: price
        };
        this.goodBuyModalInfo = [{ title: `保费`, value: `${price[0]}${price[1]}` }];
      }
    }
  }
};
</script>
<style lang="less" src="./index.less" scoped></style>
