<script setup lang="ts">
import { ref, watch } from "vue";
import { useRequest } from "vue-request";
import { myRequest } from "@/requests/request.ts";
import { loginData, userinfo } from "@/store/store.ts";
import { ElMessage } from "element-plus";
import { formatError, rsaEncrypt } from "@/utils/utils.ts";
import { Lock } from "@element-plus/icons-vue";

const active = ref(0);
const visible = ref(false);
const email = ref("");
const leftTime = ref(0);
const inputData = ref({ confirmCode: "", password: "", rePass: "" });

const { runAsync: getConfirmCode } = useRequest(
  () => myRequest(`/api/user/reset?username=${loginData.username}`),
  { manual: true },
);
const { runAsync: getPubKey } = useRequest(
  () => myRequest(`/api/user/login?username=${loginData.username}`),
  { manual: true },
);
const { runAsync: runLogin } = useRequest(
  (enPass: string) =>
    myRequest(
      `/api/user/login?username=${loginData.username}&password=${encodeURIComponent(enPass)}&confirmCode=${inputData.value.confirmCode}`,
      "",
      {},
      "post",
    ),
  { manual: true },
);

const forgetPwd = () => {
  if (!loginData.username) {
    ElMessage.error("请输入用户名");
    return;
  }
  getConfirmCode()
    .then((res) => {
      visible.value = true;
      leftTime.value = 30;
      email.value = res.data;
    })
    .catch((err) => {
      ElMessage.error(formatError(err));
    });
};

const resetPwd = () => {
  getPubKey()
    .then((res) => {
      const enPass = rsaEncrypt(
        res.data as string,
        inputData.value.password as string,
      );
      runLogin(enPass as string)
        .then((r) => {
          visible.value = false;
          ElMessage.success("密码重置完成");
          userinfo.login = true;
          userinfo.token = r.data;
        })
        .catch((err) => {
          ElMessage.error(formatError(err));
        });
    })
    .catch((err) => {
      ElMessage.error(formatError(err));
    });
};

watch(visible, () => {
  active.value = 0;
});
let timer: any;
watch(leftTime, () => {
  if (leftTime.value === 30) {
    timer = setInterval(() => {
      leftTime.value--;
    }, 1000);
  }
  if (leftTime.value === 0) {
    clearInterval(timer);
  }
});
</script>

<template>
  <el-button link @click="forgetPwd">忘记密码 ？</el-button>
  <el-dialog
    v-model="visible"
    title="密码重置"
    append-to-body
    style="min-width: 30rem"
  >
    <el-steps :active="active" align-center>
      <el-step title="邮箱验证" />
      <el-step title="重置密码" />
    </el-steps>
    <div class="content" v-if="active === 0">
      <div class="email-div flex around">
        验证码已发送邮箱：{{ email }}， 5分钟内有效
      </div>
      <div class="confirm-div flex around">
        <div class="flex" style="width: 15rem">
          <label style="width: 5rem">验证码：</label>
          <el-input
            v-model="inputData.confirmCode"
            clearable
            placeholder="请填写验证码"
          />
        </div>
        <div>
          {{ leftTime > 0 ? `${leftTime}s 后` : ""
          }}<el-button link :disabled="leftTime > 0" @click="forgetPwd"
            >重新发送</el-button
          >
        </div>
      </div>
    </div>
    <div class="content" v-if="active === 1">
      <div class="input-div">
        <el-input
          v-model="inputData.password"
          placeholder="输入密码"
          size="large"
          type="password"
          clearable
          show-password
          class="input"
          ><template #prefix>
            <el-icon><Lock /></el-icon> </template
        ></el-input>
        <el-input
          v-model="inputData.rePass"
          placeholder="重复输入密码"
          size="large"
          type="password"
          clearable
          show-password
          class="input"
          ><template #prefix>
            <el-icon><Lock /></el-icon> </template
        ></el-input>
      </div>
    </div>

    <template #footer>
      <el-button link @click="active--" v-if="active > 0">上一步</el-button>
      <el-button
        @click="active++"
        v-if="active === 0"
        :disabled="!inputData.confirmCode"
        >下一步</el-button
      >
      <el-button
        type="primary"
        v-if="active > 0"
        :disabled="
          !inputData.password || inputData.rePass !== inputData.password
        "
        @click="resetPwd"
        >完成</el-button
      >
    </template>
  </el-dialog>
</template>

<style scoped>
.email-div {
  height: 5rem;
}
.confirm-div {
  height: 5rem;
  min-width: 25rem;
  max-width: 30rem;
  margin: 0 auto;
}
.input-div {
  position: relative;
  text-align: center;
}
.input {
  margin: 2rem;
  height: 3rem;
  width: calc(100% - 8rem);
}
</style>
