<template>
  <div class="relative">
    <WellcomeCard class="relative left-1/2 -translate-x-1/2"
      ><div class="mb-3">
        欢迎认证 · <span style="font-weight: bold">上链查存证平台</span>
      </div></WellcomeCard
    >
    <div
      style="font-size: 12px; font-weight: 500; color: #3370fe"
      class="mt-2.5"
    >
      <span class="cursor-pointer" @click="$emit('select')">认证中心 ></span>
      <span style="color: var(--sy-black)">申请个人认证</span>
    </div>
    <div class="title text-center mt-10">请提交您的实名认证信息</div>
    <div class="mx-auto" style="width: 770px">
      <ElForm ref="formRef" :rules="rules" :model="formModel">
        <CustomizeFormItem prop="name" label="姓名">
          <syDialogInput
            placeholder="请输入您的真实姓名"
            style="width: 100%"
            v-model:value="formModel.name"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem prop="id" label="身份证号">
          <syDialogInput
            placeholder="请输入您的身份证号"
            style="width: 100%"
            v-model:value="formModel.id"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem prop="bankCard" label="银行卡号">
          <syDialogInput
            placeholder="请输入您的银行卡号"
            style="width: 100%"
            v-model:value="formModel.bankCard"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem prop="phone" label="银行预留手机号">
          <syDialogInput
            placeholder="请输入您的预留手机号"
            maxLength="11"
            style="width: 100%"
            v-model:value="formModel.phone"
            :value="formModel.phone"
            @update:value="
              (v: string) => (formModel.phone = v.replaceAll(/[^\d]/gi, ''))
            "
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem prop="code" label="验证码">
          <syDialogInput
            placeholder="请输入验证码"
            style="width: 100%"
            maxLength="6"
            v-model:value="formModel.code"
          >
            <template #suffix>
              <div class="h-full flex items-center">
                <div
                  @click="handleClickSendSms"
                  class="cursor-pointer flex items-center justify-center select-none"
                  style="
                    height: 25px;
                    background: #f4f4f4;
                    width: 104px;
                    font-size: 12px;
                  "
                >
                  <span
                    v-if="timer && timer.count === 60"
                    class="text-mBlue"
                    :class="{
                      ' text-mGray6': timer && timer.lock,
                    }"
                    >发送验证码</span
                  >
                  <span v-else class="text-mGray6">
                    {{ timer && timer.count }}秒后重新发送
                  </span>
                </div>
              </div>
            </template>
          </syDialogInput>
        </CustomizeFormItem>
      </ElForm>
      <syButton
        @click="handleConfirm"
        :loading="loading"
        mode="elementBtn"
        type="primary"
        style="width: 100%; height: 40px; margin-top: 52px"
        >提交审核</syButton
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { syDialogInput, syButton } from "cqk-sy-ui";
import { ElForm, ElLoading, ElMessage } from "element-plus";

import WellcomeCard from "./WellcomeCard.vue";
import CustomizeFormItem from "@/components/Form/CustomizeFormItem.vue";
import {
  checkCard,
  checkIdNumber,
  checkPhone,
  checkVerificationCode,
} from "@/utils/match";
import { get, personVerify, smsPerson } from "@/service/Api.service";
import { router } from "@/router";
import { sleep } from "@/utils/promise";

const formRef = ref<InstanceType<typeof ElForm>>();
const timer = reactive({
  count: 60,
  lock: false,
  record: NaN,
});

const emit = defineEmits(["update", "select"]);

const loading = ref(false);

const rules = reactive({
  name: [
    {
      required: true,
      message: "姓名不能为空",
    },
  ],
  id: [
    {
      required: true,
      message: "请输入身份证号",
    },
    {
      validator: checkIdNumber,
    },
  ],
  bankCard: [
    {
      required: true,
      message: "请输入银行卡号",
    },
    {
      validator: checkCard,
    },
  ],
  phone: [
    {
      required: true,
      message: "请输入银行预留手机号",
    },
    {
      validator: checkPhone,
    },
  ],
  code: [
    {
      required: true,
      message: "请输入验证码",
    },
    {
      validator: checkVerificationCode,
    },
  ],
});

const formModel = reactive({
  name: "",
  id: "",
  bankCard: "",
  phone: "",
  code: "",
});

async function handleClickSendSms() {
  if (!timer.lock) {
    timer.lock = true;
    formRef.value?.validateField("phone", async (isValid) => {
      if (isValid) {
        const res = await smsPerson(formModel.phone);
        if (res && res.code === 200) {
          ElMessage({
            message: "验证码发送成功！",
            type: "success",
          });
          timer.record = window.setInterval(() => {
            if (timer.count === 0) {
              window.clearInterval(timer.record);
              timer.count = 60;
              timer.lock = false;
            }
            timer.count--;
          }, 1000);
        } else {
          timer.lock = false;
        }
      } else {
        timer.lock = false;
      }
    });
  }
}

async function checkIfVerified(count = 3) {
  const res = await get(JSON.parse(String(sessionStorage.getItem("user"))).id);
  if (res) {
    if (res.data.status !== 1 && res.data.status !== 2) {
      ElMessage(res.data.message);
    } else if (res.data.status === 2) {
      emit("update");
      ElMessage.success("认证成功");
      router.replace({
        name: "userCenter",
        query: {
          type: "authenticate",
        },
      });
    } else if (res.data.status === 1) {
      if (count === 0) {
        ElMessage("认证失败，请重新认证");
        router.replace({
          name: "userCenter",
          query: {
            type: "authenticate",
          },
        });
      } else {
        await sleep(3000);
        count--;
        await checkIfVerified(count);
      }
    }
  }
}

async function handleConfirm() {
  loading.value = true;
  const res = await personVerify({
    name: formModel.name,
    id_card: formModel.id,
    bank_card: formModel.bankCard,
    bank_phone: formModel.phone,
    code: formModel.code,
  });

  if (res && res.code === 200) {
    const l = ElLoading.service({
      lock: true,
      text: "认证中",
      background: "rgba(0, 0, 0, 0.7)",
    });
    await checkIfVerified(3);
    l.close();
  } else {
    ElMessage.error(res?.msg || "认证失败");
  }
  loading.value = false;
}
</script>

<style scoped lang="scss">
.title {
  font-size: 24px;
  font-weight: 600;
  color: #353535;
}
</style>
