<template>
  <div class="container">
    <div class="policy-tip-wrap">
      <div class="policy-tip">您所填写的数据，仅用于投保，平台将严格保密</div>
    </div>
    <cr-form
      ref="policyForm"
      class="policy-form"
      scroll-to-error
      @submit="onFormSubmit"
      @failed="onFormFailed"
    >
      <cr-cell-group title="投保人信息">
        <cr-field
          v-model="formData.holderUserInfo.name"
          name="holderUserInfo.name"
          label="姓名"
          placeholder="请输入投保人姓名"
          :rules="[{ require: true, message: '请输入投保人姓名' }]"
          @click.native="inputClick"
        />
        <cr-field
          v-model="formData.holderUserInfo.idNo"
          name="holderUserInfo.idNo"
          label="身份证号"
          placeholder="请填写投保人身份证号"
          :rules="[{ require: true, message: '请填写投保人身份证号' }]"
          @click.native="inputClick"
        />
        <cr-field
          v-model="formData.holderUserInfo.phoneNo"
          name="formData.holderUserInfo.phoneNo"
          type="tel"
          label="手机号"
          placeholder="请填写投保人手机号"
          :rules="[{ require: true, message: '请填写投保人手机号' }]"
          @click.native="inputClick"
        />
        <cr-field
          v-model="formData.holderUserInfo.email"
          name="holderUserInfo.email"
          type="email"
          label="电子邮箱"
          placeholder="用户接收电子保单"
          :rules="[{ require: true, message: '请填写电子邮箱' }]"
        />
        <cr-field
          v-model="formData.holderUserInfo.annualIncome"
          name="holderUserInfo.annualIncome"
          label="年收入"
          type="digit"
          placeholder="请输入投保人年收入"
          :rules="[{ require: true, message: '请输入投保人年收入' }]"
        />
        <cr-field
          v-model="formData.holderUserInfo.addressCode"
          name="holderUserInfo.addressCode"
          label="居住省市"
          :rules="[{ require: 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="[{ require: true, message: '请输入居住详细地址' }]"
        />
        <cr-field
          v-model="formData.holderUserInfo.occupation"
          name="holderUserInfo.occupation"
          label="职业"
          :rules="[{ require: true, message: '请选择投保人职业' }]"
        >
          <template #input>
            <popup-picker
              :picker-data="['老师', '工人']"
              v-model="formData.holderUserInfo.occupation"
              placeholder="请选择投保人职业"
            />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.holderUserInfo.longTerm"
          name="holderUserInfo.longTerm"
          label="身份证有效期"
          :rules="[{ require: true, message: '请选择身份证有效期' }]"
        >
          <template #input>
            <cr-radio-btn
              v-model="formData.holderUserInfo.longTerm"
              :radio-data="idCardInvaildOptions"
            />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.holderUserInfo.validEnd"
          name="holderUserInfo.validEnd"
          label="有效期至"
          :rules="[{ require: true, message: '请选择您的证件有效止期' }]"
        >
          <template #input>
            <popup-date-picker
              v-model="formData.holderUserInfo.validEnd"
              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="relationChange"
              :radio-data="insuredOptions"
            />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.insuredUserInfo.socialSecurity"
          name="insuredUserInfo.socialSecurity"
          label="有无社保"
          :rules="[{ require: 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="digit"
          placeholder="请填写被保人身高"
          :rules="[{ require: true, message: '请填写被保人身高' }]"
        >
          <div class="form-unit" slot="button">厘米</div>
        </cr-field>
        <cr-field
          v-model="formData.insuredUserInfo.weight"
          name="insuredUserInfo.weight"
          label="体重"
          type="digit"
          placeholder="请填写被保人体重"
          :rules="[{ require: true, message: '请填写被保人体重' }]"
        >
          <div class="form-unit" slot="button">公斤</div>
        </cr-field>
        <template v-if="formData.insuredUserInfo.relation !== '0'">
          <cr-field
            v-model="formData.insuredUserInfo.name"
            name="insuredUserInfo.name"
            label="姓名"
            placeholder="请输入投保人姓名"
            :rules="[{ require: true, message: '请输入投保人姓名' }]"
          />
          <cr-field
            v-model="formData.insuredUserInfo.idNo"
            name="insuredUserInfo.idNo"
            label="身份证号"
            placeholder="请填写投保人身份证号"
            :rules="[{ require: true, message: '请填写投保人身份证号' }]"
          />
          <cr-field
            v-model="formData.insuredUserInfo.phoneNo"
            name="insuredUserInfo.phoneNo"
            label="手机号"
            type="tel"
            placeholder="请填写投保人手机号"
            :rules="[{ require: true, message: '请填写投保人手机号' }]"
          />
          <cr-field
            v-model="formData.insuredUserInfo.annualIncome"
            name="insuredUserInfo.annualIncome"
            label="年收入"
            type="digit"
            placeholder="请输入投保人年收入"
            :rules="[{ require: true, message: '请输入投保人年收入' }]"
          />
          <cr-field
            v-model="formData.insuredUserInfo.addressCode"
            name="insuredUserInfo.addressCode"
            label="居住省市"
            :rules="[{ require: 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="[{ require: true, message: '请输入居住详细地址' }]"
          />
          <cr-field
            v-model="formData.insuredUserInfo.occupation"
            name="insuredUserInfo.occupation"
            label="职业"
            :rules="[{ require: true, message: '请选择投保人职业' }]"
          >
            <template #input>
              <popup-picker
                :picker-data="['老师', '工人']"
                v-model="formData.insuredUserInfo.occupation"
                placeholder="请选择投保人职业"
              />
            </template>
          </cr-field>
          <cr-field
            v-model="formData.insuredUserInfo.longTerm"
            name="insuredUserInfo.longTerm"
            label="身份证有效期"
            :rules="[{ require: true, message: '请选择身份证有效期' }]"
          >
            <template #input>
              <cr-radio-btn
                v-model="formData.insuredUserInfo.longTerm"
                :radio-data="idCardInvaildOptions"
              />
            </template>
          </cr-field>
          <cr-field
            v-model="formData.insuredUserInfo.validEnd"
            name="insuredUserInfo.validEnd"
            label="有效期至"
            :rules="[{ require: true, message: '请选择您的证件有效止期' }]"
          >
            <template #input>
              <popup-date-picker
                v-model="formData.insuredUserInfo.validEnd"
                placeholder="请选择您的证件有效止期"
              />
            </template>
          </cr-field>
        </template>
      </cr-cell-group>
      <cr-cell-group title="保障方案">
        <cr-field
          v-model="formData.productItem.insuredAmount"
          name="productItem.insuredAmount"
          label="投保限额"
          :rules="[{ require: true, message: '请选择投保限额' }]"
        >
          <template #input>
            <stepper v-model="formData.productItem.insuredAmount" :option="insuredAmountOptions" />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.productItem.policyPeriod"
          name="productItem.policyPeriod"
          label="保险期限"
          :rules="[{ require: true, message: '请选择保险期限' }]"
        >
          <template #input>
            <cr-radio-btn v-model="formData.productItem.policyPeriod" :radio-data="termOptions" />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.payPeriod"
          name="payPeriod"
          label="交费方式"
          :rules="[{ require: true, message: '请选择交费方式' }]"
        >
          <template #input>
            <cr-radio-btn v-model="formData.productItem.payType" :radio-data="paywayOptions" />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.productItem.paymentPeriod"
          name="productItem.paymentPeriod"
          label="交费期间"
          :rules="[{ require: true, message: '请选择交费期间' }]"
        >
          <template #input>
            <cr-radio-btn
              v-model="formData.productItem.paymentPeriod"
              :radio-data="benefitOptions"
            />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.effectiveDate"
          name="effectiveDate"
          label="生效日期"
          :rules="[{ require: true, message: '生效日期' }]"
        >
          <template #input>
            <popup-date-picker v-model="formData.effectiveDate" placeholder="请选择生效日期" />
          </template>
        </cr-field>
        <cr-field
          v-model="formData.beneficiaryUser"
          name="beneficiaryUser"
          placeholder="请填写受益人"
          label="受益人"
          :rules="[{ require: true, message: '请填写受益人' }]"
        />
      </cr-cell-group>
      <good-action @leftClick="goInsureState = true" :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(1)">转账授权书</a>
        </div>
        <div class="pay-protocol-link pay-protocol-link_wrap">
          <a href="javascript:;" @click="openIframePupop(8)">人身保险投保提示书</a>
          <a href="javascript:;" @click="openIframePupop(3)">税收居民身份证明</a>
          <a href="javascript:;" @click="openIframePupop(3)">风控查询授权书</a>
        </div>
      </div>
    </go-insure-dialog>
    <popup-with-iframe
      v-model="popupShow"
      :title="pupopData.title"
      :content="pupopData.content"
      :url="pupopData.url"
    >
    </popup-with-iframe>
  </div>
</template>

<script>
import GoodAction from "@/components/GoodAction";
import CrRadioBtn from "@/components/CrRadioBtn";
import PopupPicker from "@/components/PopupPicker";
import PopupAreaPicker from "@/components/PopupAreaPicker";
import PopupDatePicker from "@/components/PopupDatePicker";
import PopupWithIframe from "@/components/PopupWithIframe";
import Stepper from "@/components/Stepper";
import GoInsureDialog from "@/views/Goods/Detail/modules/GoInsureDialog";
import detailPayMixin from "@/views/Goods/Detail/modules/detailPay.mixin";

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";
const {
  headerInfo,
  popupArray,
  paywayOptions,
  insuredAmountOptions,
  termOptions,
  benefitOptions,
  insuredOptions,
  idCardInvaildOptions,
  socialSecOptions
} = Detail;
export default {
  name: "AddPolicy",
  mixins: [detailPayMixin],
  components: {
    GoodAction,
    CrRadioBtn,
    GoInsureDialog,
    PopupPicker,
    PopupAreaPicker,
    PopupDatePicker,
    PopupWithIframe,
    Stepper
  },
  data() {
    return {
      popupArray,
      headerInfo,
      calTimer: null,
      goInsureState: false,
      popupShow: false,
      currentPupopIndex: null,
      goodActionInfo: {},
      goodBuyModalInfo: [],
      policyFormData: JSON.parse(sessionStorage.getItem("policyFormData") || "{}"),
      formData: {
        insuredUserInfo: {
          relation: "0"
        },
        holderUserInfo: {},
        productItem: {
          insuredAmount: "500000"
        }
      },
      subFromData: {},
      familyList: [],
      formMaskData: {},
      idCardInvaildOptions,
      socialSecOptions,
      insuredOptions,
      termOptions,
      paywayOptions,
      benefitOptions,
      insuredAmountOptions
    };
  },
  watch: {
    popupShow(val) {
      if (!val && this.currentPupopIndex === 6) this.currentPupopIndex = null;
    },
    headerInfo: {
      deep: true,
      handler(val) {
        const { price, subPrice } = val;
        this.goodActionInfo = {
          title: price
        };
        this.goodBuyModalInfo = [
          { title: `${price[2]}保费`, value: `${price[0]}${price[1]}` },
          { title: `${subPrice[2]}保费`, value: `${subPrice[0]}${subPrice[1]}${subPrice[3]}` }
        ];
      }
    },
    formDataCpu: {
      deep: true,
      handler() {
        if (this.calTimer) {
          clearTimeout(this.calTimer);
        }
        this.calTimer = setTimeout(() => {
          this.calFee();
        }, 600);
      }
    },
    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.$forceUpdate();
        }
      }
    }
  },
  computed: {
    ...mapState(["showAuthXyqb"]),
    pupopData() {
      const { popupArray, currentPupopIndex } = this;
      return popupArray[currentPupopIndex] || {};
    },
    formDataCpu() {
      return JSON.parse(JSON.stringify(this.formData));
    }
  },
  mounted() {
    this.getParamFromSession();
    this.getDetail();
    this.getFamilyList();
  },
  methods: {
    ...mapActions(["setAuthXyqb"]),
    inputClick() {
      if (this.showAuthXyqb === 1) {
        this.setAuthXyqb(2);
      }
    },
    onFormSubmit() {
      this.goInsureState = true;
    },
    onFormFailed(errorInfo) {
      const { errors } = errorInfo;
      this.$notify({ type: "warning", message: errors[0].message });
    },
    nextStep() {
      this.subFromData = JSON.parse(JSON.stringify(this.formData));
      this.subFromData.insuredUserInfo.socialSecurity =
        this.subFromData.insuredUserInfo.socialSecurity === "1" ? true : false;
      this.generateOrder();
    },
    relationChange(relation = this.formData.insuredUserInfo.relation) {
      this.familyList.forEach(item => {
        const { relation, nameMask: name, idNoMask: idNo, userInfoSecId, socialSecurity } = item;
        if (+relation === 0) {
          this.formData.holderUserInfo = {
            ...this.formData.holderUserInfo,
            ...{ name, idNo, userInfoSecId, socialSecurity: socialSecurity ? "1" : "0" }
          };
        }
      });
      const userArray = this.familyList.filter(item => item.relation === +relation);
      let [name, idNo, userInfoSecId, socialSecurity] = ["", "", "", "0"];
      if (userArray.length) {
        let { nameMask, idNoMask, userInfoSecId: id, socialSecurity: ss } = userArray[0];
        [name, idNo, userInfoSecId, socialSecurity] = [nameMask, idNoMask, id, ss];
      }
      this.formData.insuredUserInfo = {
        ...this.formData.insuredUserInfo,
        ...{ name, idNo, userInfoSecId, socialSecurity: socialSecurity ? "1" : "0" }
      };
    },
    openIframePupop(index) {
      this.currentPupopIndex = index;
      this.popupShow = true;
    },
    getParamFromSession() {
      const {
        amountInsured: insuredAmount,
        policyPeriod,
        payPeriod: paymentPeriod,
        payType,
        productNo
      } = this.policyFormData;
      this.formData.productNo = productNo;
      this.formData.productItem = {
        ...this.formData.productItem,
        ...{ insuredAmount, policyPeriod, paymentPeriod, payType }
      };
      this.$forceUpdate();
    },
    async getDetail() {
      const res = await list();
      if (res) {
        res.forEach(item => {
          if (item.productNo === this.formData.productNo) {
            this.headerInfo.price[0] = item.downPayPrice;
          }
        });
      }
    },
    async getFamilyList() {
      const res = await getFamilyList();
      if (res) {
        this.familyList = res;
        this.showAuthXyqb === -1 && this.relationChange();
      }
    },
    async calFee() {
      let { price } = this.headerInfo;
      const {
        insuredAmount: amountInsured,
        policyPeriod,
        paymentPeriod: payPeriod,
        payType
      } = this.formData.productItem;
      let idNo = "";
      const { socialSecurity } = this.formData.insuredUserInfo;
      if (this.formData.insuredUserInfo.relation !== "0") {
        idNo = this.formData.insuredUserInfo.idNo;
      } else {
        idNo = this.formData.holderUserInfo.idNo;
      }
      if (!amountInsured || !policyPeriod || !payPeriod || !payType || !idNo || !socialSecurity)
        return;
      const _param = {
        productNo: this.goodId,
        productUserInfo: {
          userInfo: {
            idNo,
            socialSecurity: socialSecurity === "1" ? true : false
          },
          productItem: {
            amountInsured,
            policyPeriod,
            payPeriod,
            payType
          }
        }
      };
      const res = await trail(_param);
      if (res) {
        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>
