<template>
  <div class="register-box" v-if="isVisible">
    <div class="register-container">
      <div class="register-close" @click="closeRegisterForm">
        <el-icon color="#333" size="24" class="btn_close"><Close /></el-icon>
      </div>
      <h4>欢迎入驻开店</h4>
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="88px"
        :hide-required-asterisk="true"
      >
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input
            v-model="formData.phoneNumber"
            placeholder="请输入手机号"
            maxlength="11"
            size="large"
          />
        </el-form-item>
        <el-form-item label="验证码" prop="verificationCode">
          <el-input
            v-model="formData.verificationCode"
            placeholder="验证码"
            size="large"
          >
            <template #append>
              <el-button
                type="primary"
                class="btn_code"
                size="large"
                v-if="!sendCode"
                :disabled="formData.phoneNumber.length !== 11"
                @click="getVerify_code"
                round
                >发送验证码</el-button
              >
              <el-button
                type="primary"
                class="btn_code"
                size="large"
                v-if="sendCode"
                disabled
                round
                >{{ countdown }}S</el-button
              >
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div class="foot">
        <el-button
          class="btn_sumit"
          color="#ea4322"
          size="large"
          :disabled="!formData.phoneNumber || !formData.verificationCode"
          round
          @click="handleRegister"
          >确定</el-button
        >
      </div>
      <!-- <div class="tool">
        已有账号？
        <el-button class="btn_sumit" type="danger" text @click="openLoginForm"
          >立即登录</el-button
        >
      </div> -->
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits, onMounted, onUnmounted } from "vue";
import { useUserStore } from "@/stores/userStore";
import { useRouter } from "vue-router";
import { GetSmsCode, GetLogin } from "@/api/login";
import { getApproval_status } from "@/api/login";
import { ElMessage } from "element-plus";
import { Close } from "@element-plus/icons-vue";

const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(["open-login-form", "close-register-form"]);
const formData = ref({
  phoneNumber: "",
  verificationCode: "",
});

const router = useRouter();
const userStore = useUserStore();
const sendCode = ref(false);
const countdown = ref(0);
let timer: ReturnType<typeof setInterval>;
const formRef = ref<InstanceType<typeof import("element-plus/es")["ElForm"]>>();
// 移除 verificationError 相关的 ref
// const verificationError = ref('');

const closeRegisterForm = () => {
  emits("close-register-form");
};

const openLoginForm = () => {
  closeRegisterForm();
  emits("open-login-form");
};

const getVerify_code = async () => {
  const params = {
    number: formData.value.phoneNumber,
  };
  const res = await GetSmsCode(params);

  if (res && res.status === 200) {
    const clicktime = new Date().getTime() + 60000;
    localStorage.setItem("Countdown", JSON.stringify(clicktime));
    sendCode.value = true;
    countdown.value = 60;
    startCountdown();
  } else {
    console.log("获取失败");
  }
};

const startCountdown = () => {
  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
      sendCode.value = false;
      localStorage.removeItem("Countdown");
    }
  }, 1000);
};

const register = async () => {
  const params = {
    user_mobile: formData.value.phoneNumber,
    rand_key: formData.value.phoneNumber,
    verify_code: formData.value.verificationCode,
  };
  const res = await GetLogin(params);
  if (res && res.status === 200 && res.data && res.data) {
    userStore.setToken(res.data.token);
    userStore.setMobilePhone(formData.value.phoneNumber);
    formData.value.phoneNumber = "";
    formData.value.verificationCode = "";
    closeRegisterForm();

    try {
      const approvalRes = await getApproval_status();
      if (approvalRes.data.code === 0 && approvalRes.data.status === 200) {
        const approvalStatus = approvalRes.data.approval_status;
        localStorage.setItem("approval_status", approvalStatus);
        if (approvalStatus == "4" || approvalRes.data==null) {
          router.push({ name: "start" });
        } else {
          router.push({ name: "check" });
        }
      }
    } catch (error) {
      console.error("获取审批状态失败:", error);
    }
  } else {
    if (res.status === 250) {
      // 使用 ElMessage 提示验证码错误
      ElMessage.error("验证码错误");
    } else {
      console.log("操作返回的信息", res.data.msg);
      console.log("hhhhh", res);
    }
  }
};

const rules = ref({
  phoneNumber: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern:
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      message: "请输入正确的11位手机号",
      trigger: "blur",
    },
  ],
  verificationCode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
  ],
});

const handleRegister = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      register();
    } else {
      ElMessage.error("请正确填写注册信息！");
    }
  });
};

onMounted(() => {
  const savedCountdown = localStorage.getItem("Countdown");
  if (savedCountdown) {
    const clicktime = JSON.parse(savedCountdown) as number;
    const currentTime = new Date().getTime();
    const remainingTime = (clicktime - currentTime) / 1000;
    if (remainingTime > 0) {
      sendCode.value = true;
      countdown.value = Math.ceil(remainingTime);
      startCountdown();
    } else {
      localStorage.removeItem("Countdown");
      sendCode.value = false;
    }
  }
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<style lang="scss">
.register-box {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.75);
  z-index: 1000101;

  .el-message {
    z-index: 1000102 !important; // 确保这个值高于遮罩层的 z-index
  }

  .foot {
    padding-top: 20px;
    .btn_sumit {
      display: block;
      width: 100%;
    }

    .btn_code {
      display: block;
      width: 60px;
    }
  }

  .register-container {
    padding: 25px;
    border-radius: 10px;
    background-color: #fff;
    width: 500px;
    position: relative;

    h4 {
      color: #666;
      text-align: center;
      margin-bottom: 30px;
      font-size: 24px;
    }

    .el-input {
      width: 100%;
    }

    .verifyAndButton {
      display: flex;
      width: 100%;
    }

    .register-close {
      position: absolute;
      top: 10px;
      right: 10px;
      .btn_close {
        cursor: pointer;
        &:hover {
          color: #409efc;
        }
      }
    }

    .tool {
      padding-top: 25px;
      display: flex;
      justify-content: center;
      align-items: center;
      text-align: center;
      font-size: 14px;
      color: #666;
    }
  }
}
</style>
