<template>
  <div>
    <card title="请填写投保信息" class="insure-card">
      <h6 class="insure-form-title">本人信息</h6>
      <cr-cell-group class="insure-form">
        <cr-field
          name="selfName"
          v-model="formData.selfName"
          placeholder="请输入投保人姓名"
          label="姓名"
          :readonly="selfInfoReadonly"
          :rules="[{ required: true, message: '请输入姓名' }]"
          @click.native="inputClick"
        />
        <cr-field
          name="selfIdNo"
          v-model="formData.selfIdNo"
          placeholder="信息保密，仅用于投保"
          label="身份证号"
          :readonly="selfInfoReadonly"
          :rules="[{ required: true, message: '请输入身份证号' }]"
          @click.native="inputClick"
        />
        <cr-field
          name="selfPhone"
          v-model="formData.selfPhone"
          placeholder="请输入您的手机号码"
          label="手机号码"
          :readonly="selfInfoReadonly"
          :rules="[{ required: true, message: '请输入手机号码' }]"
          @click.native="inputClick"
        />
        <cr-field
          name="selfCode"
          v-model="formData.selfCode"
          v-if="(!!xyqbAuthState && xyqbAuthState !== 4) || !mongoToken"
          placeholder="请输入短信验证码"
          label="验证码"
          :rules="[{ required: true, message: '请输入验证码' }]"
        >
          <template v-slot:button>
            <a href="javascript:;" @click="getCode" v-if="!showCount">获取验证码</a>
            <span class="login-form-remain" v-else>{{ count }}s</span>
          </template>
        </cr-field>
      </cr-cell-group>
      <h6 class="insure-form-title">为谁投保</h6>
      <cr-radio-btn
        v-model="formData.relation"
        @input="relationChange"
        :radio-data="radioOptions.insuredOptions"
        class="insured"
      />
      <cr-cell-group class="insure-form">
        <cr-field
          name="relativeName"
          v-if="formData.relation !== '1'"
          v-model="formData.name"
          placeholder="请输入被保人姓名"
          :readonly="infoReadonly"
          label="姓名"
          :rules="[{ required: true, message: '请输入姓名' }]"
        />
        <cr-field
          name="relativeIdNo"
          v-if="formData.relation !== '1'"
          v-model="formData.idNo"
          placeholder="信息保密，仅用于投保"
          :readonly="infoReadonly"
          label="身份证号"
          :rules="[{ required: true, message: '请输入身份证号' }]"
        />
        <cr-field
          class="insure-form-item_nobg"
          v-if="radioOptions.medicalOptions"
          v-model="formData.socialSecurity"
          name="socialSecurity"
          label="有无医保"
          :rules="[{ required: true, message: '请选择医保状态' }]"
        >
          <template #input>
            <svg-icon
              icon-class="doubt"
              @click.native="question = true"
              class-name="Ffr-title-svg"
            />
            <cr-radio-btn
              name="socialSecurity"
              v-model="formData.socialSecurity"
              :radio-data="radioOptions.medicalOptions"
            />
          </template>
        </cr-field>
        <cr-field
          class="insure-form-item_nobg"
          v-if="radioOptions.paywayOptions"
          v-model="formData.payType"
          name="payType"
          label="缴费方式"
          :rules="[{ required: true, message: '请选择缴费方式' }]"
        >
          <template #input>
            <cr-radio-btn
              name="payType"
              v-model="formData.payType"
              :radio-data="radioOptions.paywayOptions"
            />
          </template>
        </cr-field>
      </cr-cell-group>
    </card>
    <Modal
      class="insured-modal"
      v-model="question"
      :closeable="false"
      @confirm="question = false"
      cancel-btn=""
      content="常见的社保包括农村合作医疗(新农合)、城镇居民社保、城镇职工医保、少儿医保等政府主导的基本医疗保障项目，满足最基本的医疗保障要求。"
      title="我们常说的社保都包括哪些？"
      confirm-btn="我知道了"
    />
  </div>
</template>

<script>
import Card from "@/components/Card";
import Modal from "@/components/Modal";
import { mapState, mapActions } from "vuex";
import { getFamilyList, getCaptchaSms } from "@/api/user";
import { isPhone } from "@/service/validation";
import localStorage from "@/service/localStorage";
import CrRadioBtn from "@/components/CrRadioBtn";
import autoSaveForm from "@/mixins/autoSaveForm.mixin";

const AUTO_SAVE_KEY = "DetailFormData";
const AUTO_SAVE_TARGET = "formData";
const DATA_CHANGE_EVENT = "input";
export default {
  name: "InsurePersonForm",
  components: {
    CrRadioBtn,
    Card,
    Modal
  },
  mixins: [autoSaveForm],
  props: {
    value: {
      type: Object,
      default() {
        return {};
      }
    },
    radioOptions: {
      type: Object,
      default() {
        return {};
      }
    },
    detailType: String
  },
  data() {
    return {
      formData: {},
      familyList: [],
      showCount: false,
      count: "",
      timer: null,
      autoSaveKey: AUTO_SAVE_KEY,
      mongoToken: localStorage.get("mongoToken"),
      xyqbAuthState: localStorage.get("xyqbAuthState"),
      selfInfoReadonly: false,
      infoReadonly: false,
      question: false
    };
  },
  watch: {
    detailType: {
      immediate: true,
      handler(val) {
        this.autoSaveKey = val + AUTO_SAVE_KEY;
      }
    },
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        this.formData = val;
      }
    },
    userInfo: {
      immediate: true,
      deep: true,
      handler(val) {
        this.formData.selfPhone =
          val.phoneNoMask && val.phoneNoMask !== "点击登录" ? val.phoneNoMask : "";
        this.$forceUpdate();
      }
    },
    formData: {
      immediate: true,
      deep: true,
      handler(val) {
        this.autoSaveHandler(AUTO_SAVE_TARGET, this.autoSaveKey);
        this.$emit(DATA_CHANGE_EVENT, val);
        this.$forceUpdate();
      }
    },
    showAuthXyqb: {
      immediate: true,
      handler(val) {
        if (val === 4 && this.userInfo.phoneNoMask === "点击登录") {
          const xyqbUserInfo = localStorage.get("xyqbUserInfo");
          this.formData.selfName = xyqbUserInfo.nameMask;
          this.formData.selfIdNo = xyqbUserInfo.idNoMask;
          this.formData.selfPhone = xyqbUserInfo.phoneNoMask;
          this.xyqbAuthState = localStorage.get("xyqbAuthState");
          this.selfInfoReadonly = true;
          this.$forceUpdate();
        }
      }
    },
    familyList() {
      this.relationChange();
    }
  },
  computed: {
    ...mapState(["showAuthXyqb"]),
    ...mapState("user", ["userInfo"]),
    socialSecurityReadonly() {
      const { relation } = this.formData;
      const { selfInfoReadonly, infoReadonly } = this;
      return (relation === "1" && selfInfoReadonly) || (relation !== "1" && infoReadonly);
    }
  },
  mounted() {
    this.getFamilyList();
  },
  methods: {
    ...mapActions(["setAuthXyqb"]),
    ...mapActions("user", ["setUserInfo"]),
    inputClick() {
      if (this.showAuthXyqb === 1) {
        this.setAuthXyqb(2);
      }
    },
    relationChange(relation = this.formData.relation) {
      this.familyList.forEach(item => {
        const {
          relation,
          nameMask: selfName,
          idNoMask: selfIdNo,
          userInfoSecId: selfSecId,
          socialSecurity
        } = item;
        if (+relation === 1) {
          this.formData = {
            ...this.formData,
            ...{
              selfName,
              selfIdNo,
              selfSecId,
              selfSocialSecurity: socialSecurity ? "1" : "0"
            }
          };
          this.selfInfoReadonly = true;
        }
      });
      const userArray = this.familyList.filter(item => item.relation === +relation);
      let [name, idNo, userInfoSecId, socialSecurity] = ["", "", "", ""];
      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") {
          const { selfName: sName, selfIdNo: sNo } = this.formData;
          [name, idNo] = [sName, sNo];
        }
        this.infoReadonly = false;
      }
      this.formData = {
        ...this.formData,
        ...{
          name,
          idNo,
          userInfoSecId,
          socialSecurity:
            socialSecurity === "" || typeof socialSecurity === "undefined"
              ? this[this.autoSaveKey + "Cache"].socialSecurity || ""
              : socialSecurity
              ? "1"
              : "0"
        }
      };
    },
    async getFamilyList() {
      this.mongoToken = localStorage.get("mongoToken");
      if (!this.mongoToken) return;
      this.setUserInfo();
      const res = await getFamilyList();
      if (res) {
        this.familyList = res;
        if (this.hasAutoSaveData(this.autoSaveKey)) {
          this.getSaveInfoHandler(this.autoSaveKey, AUTO_SAVE_TARGET);
        } else {
          const queryId = this.$route.query.userInfoSecId;
          let relation = this.formData.relation;
          if (queryId) {
            relation = this.familyList.filter(item => item.userInfoSecId === queryId)[0].relation;
          }
          (this.showAuthXyqb || this.mongoToken) && this.relationChange(relation);
        }
      }
    },
    // TODO 倒计时未回显
    async getCode() {
      const TIME_COUNT = 60;
      const { selfPhone } = this.formData;
      if (this.timer) return;
      if (!isPhone(selfPhone)) {
        this.$notify({ type: "warning", message: "请填写正确的手机号码" });
        return;
      }
      const res = await getCaptchaSms({ phoneNo: selfPhone });
      if (res && !this.timer) {
        this.count = TIME_COUNT;
        this.showCount = true;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.showCount = false;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      } else {
        this.$notify({ type: "warning", message: "获取短信验证码失败，请稍后重试" });
      }
    }
  }
};
</script>
<style lang="less" scoped>
@import "../../../../style/var.less";
.insure-card {
  @{deep} .card-body {
    padding-bottom: 10px;
  }
}
.insure-form {
  &-title {
    font-size: @font-size-16;
    font-weight: @font-weight-bold;
    margin: @padding-md 0;
  }
  @{deep} .cr-cell {
    &-group {
      &::after {
        display: none;
      }
    }
    background-color: @gray-1;
    border-radius: @border-radius-md;
    margin-bottom: 12px;
    align-items: center;
    padding: 9px 16px;
    &::after {
      display: none;
    }
    &__title {
      color: #333333;
      display: flex;
      align-items: center;
    }
  }
  &-item_nobg {
    background-color: transparent !important;
    padding: 10px 0;
    overflow: initial;
    align-items: baseline !important;
    margin-bottom: 0 !important;
    .radio-btn {
      margin-bottom: 0;
    }
    @{deep} .cr-cell {
      &__title {
        width: 31%;
        flex: none;
      }
      &__value {
        width: 69%;
        flex: none;
        overflow: initial;
      }
    }
    @{deep} .cr-field--control {
      display: block;
      position: relative;
    }
  }
}
.insured {
  margin-bottom: 20px;
}
.insured-modal {
  @{deep} .panel-body {
    font-size: 16px;
    font-weight: 400;
    color: #666666;
    line-height: 28px;
  }
}
.Ffr-title-svg {
  position: absolute;
  top: 10px;
  left: -35px;
}
</style>
