<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: '请输入姓名' },
            {
              validator: isChineseNameMask,
              message: '请填写正确的投保人姓名，最少2个中文字符'
            }
          ]"
          @click.native="inputClick"
        />
        <cr-field
          name="selfIdNo"
          v-model="formData.selfIdNo"
          placeholder="信息保密，仅用于投保"
          label="身份证号"
          :readonly="selfInfoReadonly"
          :rules="[
            { required: true, message: '请输入身份证号' },
            {
              validator: isIdNoMask,
              message: '请填写正确的投保人身份证号'
            }
          ]"
          @click.native="inputClick"
        />
        <cr-field
          name="selfPhone"
          v-model="selfPhone"
          type="tel"
          placeholder="请输入您的手机号码"
          label="手机号码"
          :readonly="selfInfoReadonly"
          :rules="[
            { required: true, message: '请输入手机号码' },
            {
              validator: isPhoneMask,
              message: '请填写正确的投保人手机号'
            }
          ]"
          @click.native="inputClick"
        />
        <cr-field
          name="selfCode"
          v-model="formData.selfCode"
          type="digit"
          v-if="!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-icon
            type="arrow"
            slot="button"
            v-if="relationList.length > 1"
            class="relation-select"
            @click="showRelations = true"
          />
        </cr-field>
        <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="我知道了"
    />
    <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>
  </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 localStorage from "@/service/localStorage";
import CrRadioBtn from "@/components/CrRadioBtn";
import autoSaveForm from "@/mixins/autoSaveForm.mixin";
import { isIdNo, isChineseName, isPhone } from "@/service/validation";
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,
      showRelations: false,
      refreshed: false,
      relationList: [],
      selfPhone: ""
    };
  },
  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;
      }
    },
    detailType: {
      immediate: true,
      handler(val) {
        this.autoSaveKey = val + AUTO_SAVE_KEY;
      }
    },
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        // this.selfPhone = val.selfPhone;
        this.formData = val;
      }
    },
    userInfo: {
      immediate: true,
      deep: true,
      handler(val) {
        this.selfPhone = val.phoneNoMask && val.phoneNoMask !== "点击登录" ? val.phoneNoMask : "";
        this.$forceUpdate();
      }
    },
    selfPhone(val) {
      this.formData.selfPhone = val;
    },
    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) {
        this.mongoToken = localStorage.get("mongoToken");
        if (val === 4 && this.userInfo.phoneNoMask === "点击登录") {
          const xyqbUserInfo = localStorage.get("xyqbUserInfo");
          const { nameMask, idNoMask, phoneNoMask } = xyqbUserInfo;
          if (nameMask) {
            this.formData.selfName = nameMask;
          }
          if (idNoMask) {
            this.formData.selfIdNo = idNoMask;
          }
          if (phoneNoMask) {
            setTimeout(() => {
              this.selfPhone = phoneNoMask;
            }, 500);
          }
          this.xyqbAuthState = localStorage.get("xyqbAuthState");
          this.selfInfoReadonly = nameMask && idNoMask && phoneNoMask;
          this.getFamilyList();
          this.$forceUpdate();
        }
      }
    }
  },
  computed: {
    ...mapState(["showAuthXyqb"]),
    ...mapState("user", ["userInfo"]),
    socialSecurityReadonly() {
      const { relation } = this.formData;
      const { selfInfoReadonly, infoReadonly } = this;
      return (relation === "1" && selfInfoReadonly) || (relation !== "1" && infoReadonly);
    }
  },
  mounted() {
    this.mongoToken = localStorage.get("mongoToken");
    this.getFamilyList();
  },
  methods: {
    ...mapActions(["setAuthXyqb"]),
    ...mapActions("user", ["setUserInfo"]),
    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);
      }
    },
    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 = {
        ...this.formData,
        ...{
          idNo: idNoMask,
          name: nameMask,
          userInfoSecId,
          socialSecurity:
            socialSecurity === "" || typeof socialSecurity === "undefined"
              ? ""
              : socialSecurity
              ? "1"
              : "0"
        }
      };
      this.onRelationCancel();
    },
    relationChange(relation = this.formData.relation, validSelf = false) {
      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;
        }
      });
      if (validSelf) return;
      let userArray = this.familyList.filter(item => item.relation === +relation);
      let [name, idNo, userInfoSecId, socialSecurity] = ["", "", "", ""];
      if (
        relation ===
        (localStorage.get(this.autoSaveKey) && localStorage.get(this.autoSaveKey).relation)
      ) {
        const {
          name: cachename,
          idNo: cacheidNo,
          userInfoSecId: cacheuserInfoSecId,
          socialSecurity: cachesocialSecurity
        } = localStorage.get(this.autoSaveKey);

        [name, idNo, userInfoSecId, socialSecurity] = [
          cachename,
          cacheidNo,
          cacheuserInfoSecId,
          cachesocialSecurity
        ];
      }
      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.relationList = userArray.length > 1 ? userArray : [];
      setTimeout(() => {
        this.formData = {
          ...this.formData,
          ...{
            name,
            idNo,
            userInfoSecId,
            socialSecurity:
              socialSecurity === "" || typeof socialSecurity === "undefined"
                ? ""
                : socialSecurity
                ? "1"
                : "0"
          }
        };
      });

      if (!this.formData.socialSecurity && this.radioOptions.medicalOptions) {
        try {
          this.formData.socialSecurity = localStorage.get(this.autoSaveKey).socialSecurity;
        } catch (e) {
          //
        }
      }
    },
    getFamilyList(reset = false) {
      return new Promise(resolve => {
        this.mongoToken = localStorage.get("mongoToken");
        console.log(this.mongoToken);
        if (!this.mongoToken) return;
        this.setUserInfo();
        getFamilyList().then(res => {
          if (res) {
            this.familyList = res;
            if (this.hasAutoSaveData(this.autoSaveKey) && !reset) {
              this.getSaveInfoHandler(this.autoSaveKey, AUTO_SAVE_TARGET);
              const { idNo, userInfoSecId, relation } = this.formData;
              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 = {
                        ...this.formData,
                        ...{
                          idNo: idNoMask,
                          name: nameMask,
                          userInfoSecId,
                          socialSecurity:
                            typeof socialSecurity === undefined || socialSecurity === ""
                              ? ""
                              : socialSecurity
                              ? "1"
                              : "0"
                        }
                      };
                    }
                  });
                }
              } else {
                this.formData.relation = "1";
              }
              if (this.mongoToken && !this.selfPhone) {
                this.selfPhone = this.userInfo.phoneNoMask;
              }
              if (!this.formData.selfName) {
                const selfInfo = this.familyList.find(item => item.relation === 1);
                this.selfInfoReadonly = !!selfInfo;
                if (selfInfo) {
                  const {
                    idNoMask: selfIdNo,
                    nameMask: selfName,
                    socialSecurity,
                    userInfoSecId: selfSecId
                  } = selfInfo;
                  this.formData = {
                    ...this.formData,
                    ...{
                      selfName,
                      selfIdNo,
                      selfSecId,
                      selfSocialSecurity: socialSecurity ? "1" : "0"
                    }
                  };
                }
              } else {
                this.selfInfoReadonly = true;
              }
            } else {
              let relation = this.formData.relation || "1";
              (this.showAuthXyqb || this.mongoToken) && this.relationChange(relation, reset);
            }
          }
          resolve();
        });
      });
    },
    // TODO 倒计时未回显
    async getCode() {
      const TIME_COUNT = 60;
      const { selfPhone } = this;
      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 !important;
    overflow: initial;
    align-items: baseline !important;
    margin-bottom: 0 !important;
    flex-wrap: wrap;
    .radio-btn {
      margin-bottom: 0;
    }
    @{deep} .cr-cell {
      &__title {
        width: 100%;
        flex: none;
        margin-bottom: 16px;
        font-size: @font-size-16;
        span {
          font-weight: @font-weight-bold;
        }
      }
      &__value {
        width: 100%;
        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;
}
.relation-select {
  width: 13px;
  height: 22px;
  text-align: center;
  line-height: 22px;
}
</style>
