<script setup>
import { ref, computed, reactive, toRefs } from "vue";
import { ElMessage } from "element-plus";
import { useLogin } from "@/hooks/login/use-login";
import { departInterence } from "@/api/api.js";
import { checkPassWord } from "@/utils/commonOptions";
import http from "@/api/http.js";
import CaptchaInput from "./components/CaptchaInput.vue";
import ModelSteps from "./components/ModelSteps.vue";
import VerificationBox from "./components/VerificationBox.vue";

const props = defineProps({
  isMobile: {
    type: Boolean,
    default: false,
  },
  autoAccount: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["changeModel"]);

const { getCodePic, picSrc, picId } = useLogin();
getCodePic();

/* form */
const form = ref({
  //步骤0的表单
  account: props.autoAccount,
  picCode: "",
});
const forgetPassTextMobile = computed(() => {
  switch (currentStep.value) {
    case 0:
      return "忘记密码";
    case 1:
      return "安全验证";
    case 2:
      return "请输入验证码";
    case 3:
      return "设置密码";
    default:
      return "";
  }
});

/* 第一步 */
const currentStep = ref(0);
const userInfo = reactive({
  userMobile: "", //用户的手机号
  TelAreaCode: "", //用户手机号的区号
  userEmail: "", //用户的邮箱
});
//获取用户账号信息
function getUserInfo() {
  //检查form是否填写完整
  const { account, picCode } = form.value;
  if (!account) {
    return ElMessage.warning("请输入账号");
  }
  if (!picCode) {
    return ElMessage.warning("请输入图形验证码");
  }
  //请求接口获取账号数据，赋值userMobile,userEmail
  departInterence
    .accountCheck({
      CaptchaId: picId.value,
      CaptchaCode: picCode,
      UserName: account,
    })
    .then((res) => {
      if (res.Ret !== 200) {
        //刷新图形验证码
        getCodePic();
        form.value.picCode = "";
        return;
      }
      if (res.Data) {
        userInfo.userMobile = res.Data.Mobile || "";
        userInfo.userEmail = res.Data.Email || "";
        userInfo.TelAreaCode = res.Data.TelAreaCode || "";
        goSteps();
      }
    });
}
function goSteps() {
  currentStep.value++;
}

/* 第二步 */
const checkState = reactive({
  checkWay: "", //选择的验证方式
  authCode: "", //手机/邮箱验证码，从CaptchaInput组件中取
  mobileCountDown: 0, //手机获取验证码倒计时
  emailCountDown: 0, //邮箱验证码倒计时
  checkPassStr: "确定", //重置密码按钮
  choosedWay: "mobile",
});
//获取对应验证方式的验证码
function getCode(way) {
  checkState.checkWay = way;

  const { userMobile, TelAreaCode, userEmail } = userInfo;
  departInterence
    .getCodeVerify({
      VerifyType: way === "mobile" ? 1 : 2,
      CaptchaId: picId.value,
      CaptchaCode: form.value.picCode,
      Mobile: way === "mobile" ? userMobile : "",
      TelAreaCode: way === "mobile" ? TelAreaCode : "",
      Email: way === "email" ? userEmail : "",
      Source: 3,
    })
    .then((res) => {
      if (res.Ret !== 200) return;
      goSteps();
    });
}

const captInput = ref(null);
//检查输入的验证码
function checkInput() {
  const code = captInput.value.captchas.map((x) => x.num).join("");
  if (code.length !== 6) {
    return ElMessage.warning("请输入完整的验证码");
  }

  departInterence
    .checkCodeVerify({
      FindType: checkState.checkWay === "mobile" ? 1 : 2,
      VerifyCode: code,
      UserName: form.value.account,
      Mobile: checkState.checkWay === "mobile" ? userInfo.userMobile : "",
      Email: checkState.checkWay === "email" ? userInfo.userEmail : "",
    })
    .then((res) => {
      if (res.Ret !== 200) return;
      goSteps();
    });
}

/* 第三步 */
const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入新密码"));
  }
  if (passForm.value.pass2 !== "") {
    passFormRef.value.validateField("pass2");
  }
  if (!checkPassWord(value)) {
    callback(
      new Error(
        "密码要求8位及以上，包含数字、大写字母、小写字母、特殊字符中的三个类型"
      )
    );
  } else {
    callback();
  }
};
const validateCheck = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入确认密码"));
  } else if (value !== passForm.value.pass1) {
    callback(new Error("两次输入的密码不一致，请检查"));
  } else {
    callback();
  }
};
const passFormRef = ref(null);
//设置新密码的表单
const passForm = ref({
  pass1: "",
  pass2: "",
});
const passRules = {
  pass1: [{ validator: validatePass, trigger: "blur" }],
  pass2: [{ validator: validateCheck, trigger: "blur" }],
};
const countDownNum = ref(5);
const resetPassTimer = ref(null);
async function handleResetPass() {
  if (checkState.checkPassStr.includes("去登陆")) {
    emit("changeModel");
    return;
  }
  await passFormRef.value.validate();
  //重置密码
  departInterence
    .resetPass({
      UserName: form.value.account,
      Password: new http.Base64().encode(passForm.value.pass1),
      RePassword: new http.Base64().encode(passForm.value.pass2),
    })
    .then((res) => {
      if (res.Ret !== 200) return;
      ElMessage.success("重置密码成功，请登陆");

      localStorage.setItem("timeKey", Date.now());
      localStorage.setItem(
        "account",
        new http.Base64().encode(form.value.account)
      );
      localStorage.setItem(
        "checkPass",
        new http.Base64().encode(passForm.value.pass1)
      );

      resetPassCountDown();
      resetPassTimer = setInterval(() => {
        resetPassCountDown();
      }, 1000);
    });
}
function resetPassCountDown() {
  countDownNum.value--;
  checkPassStr.value = `去登陆（${countDownNum.value}s）`;
  if (countDownNum.value <= 0) {
    clearInterval(resetPassTimer.value);
    emit("changeModel");
    return;
  }
}

function changeModel() {
  if (currentStep.value > 0) {
    currentStep.value--;
    if (currentStep.value === 0) {
      getCodePic();
      form.value.picCode = "";
    }
  } else {
    emit("changeModel");
  }
}

const { userMobile, userEmail } = toRefs(userInfo);
const { checkPassStr, choosedWay } = toRefs(checkState);
</script>
<template>
  <div class="forget-pass-model">
    <div class="header-nav" @click="changeModel">
      <span><i class="el-icon-back"></i></span>
      <span v-if="!isMobile">忘记密码</span>
      <span v-else>{{ forgetPassTextMobile }}</span>
    </div>
    <div class="step-container model-wrap" v-show="currentStep === 0">
      <el-form
        ref="modelForm"
        label-position="right"
        label-width="0px"
        :model="form"
      >
        <el-form-item prop="account">
          <el-input
            type="text"
            v-model="form.account"
            auto-complete="off"
            placeholder="请输入账号"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="picCode">
          <el-input
            class="input-with-slot"
            type="text"
            v-model="form.picCode"
            auto-complete="off"
            placeholder="请输入图形验证码"
          >
            <template #append>
              <div class="pic-box" @click="getCodePic">
                <img :src="picSrc" alt="图形验证码" />
              </div>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <el-button class="submit_btn" @click="getUserInfo">下一步</el-button>
    </div>
    <div class="step-container" v-show="currentStep > 0">
      <div class="container-header">
        <p>您正在找回账号{{ form.account }}的密码</p>
        <ModelSteps :active-step="currentStep" />
      </div>
      <div
        class="container-inner model-wrap"
        v-show="currentStep === 1 && !isMobile"
      >
        <VerificationBox
          verifies-type="mobile"
          :info-text="userMobile || '暂未绑定'"
          :hideBtn="!userMobile"
          @goNext="getCode"
        />
        <VerificationBox
          verifies-type="email"
          :info-text="userEmail || '暂未绑定'"
          :hideBtn="!userEmail"
          @goNext="getCode"
        />
      </div>
      <div v-show="currentStep === 1 && isMobile">
        <div
          class="verification-item"
          :class="{
            active: choosedWay === 'mobile',
            disabled: !userMobile.length ? true : false,
          }"
          @click="choosedWay = 'mobile'"
        >
          <!-- <div class="icon"> -->
          <img src="~@/assets/img/icons/phone-login-type.png" />
          <!-- </div> -->
          <div class="text">{{ userMobile || "暂未绑定" }}</div>
        </div>
        <div
          class="verification-item"
          :class="{
            active: choosedWay === 'email',
            disabled: !userEmail.length ? true : false,
          }"
          @click="choosedWay = 'email'"
        >
          <!-- <div class="icon"> -->
          <img src="~@/assets/img/icons/email-login-type.png" />
          <!-- </div> -->
          <div class="text">{{ userEmail || "暂未绑定" }}</div>
        </div>
        <el-button
          class="verification-button"
          type="primary"
          round
          @click="getCode(choosedWay)"
          v-show="userMobile.length || userEmail.length"
          >获取验证码</el-button
        >
      </div>
      <div class="container-inner" v-show="currentStep === 2">
        <CaptchaInput ref="captInput" />
        <div class="btn-wrap">
          <el-button type="primary" plain @click="changeModel"
            >上一步</el-button
          >
          <el-button type="primary" @click="checkInput">下一步</el-button>
        </div>
      </div>
      <div class="container-inner model-wrap" v-show="currentStep === 3">
        <el-form
          ref="passFormRef"
          label-position="right"
          label-width="0px"
          :model="passForm"
          :rules="passRules"
        >
          <el-form-item prop="pass1">
            <el-input
              type="password"
              show-password
              v-model.trim="passForm.pass1"
              auto-complete="off"
              @copy.capture.prevent="
                () => {
                  return false;
                }
              "
              @cut.capture.prevent="
                () => {
                  return false;
                }
              "
              @paste.capture.prevent="
                () => {
                  return false;
                }
              "
              placeholder="请输入新密码"
            >
            </el-input>
          </el-form-item>
          <el-form-item prop="pass2">
            <el-input
              type="password"
              show-password
              v-model.trim="passForm.pass2"
              auto-complete="off"
              @copy.capture.prevent="
                () => {
                  return false;
                }
              "
              @cut.capture.prevent="
                () => {
                  return false;
                }
              "
              @paste.capture.prevent="
                () => {
                  return false;
                }
              "
              placeholder="请确认新密码"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <el-button class="submit_btn" @click="handleResetPass">{{
          checkPassStr
        }}</el-button>
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss">
@import "./css/formStyle.scss";
</style>
<style scoped lang="scss">
.forget-pass-model {
  .header-nav {
    font-size: 38px;
    margin-bottom: 60px;
    cursor: pointer;
  }
  .step-container {
    .container-header {
      margin-bottom: 60px;
      p {
        font-size: 18px;
        padding-bottom: 20px;
        border-bottom: 1px solid #dcdfe6;
        margin-bottom: 60px;
      }
      .el-steps {
        margin-top: 60px;
      }
    }
    .container-inner {
      .btn-wrap {
        margin-top: 100px;
        text-align: center;
        .el-button {
          width: 200px;
        }
      }
    }
  }
  .verification-item {
    display: flex;
    align-items: center;
    width: 100%;
    box-sizing: border-box;
    padding: 10px 15px;
    margin-bottom: 30px;
    border: 1px solid #dcdfe6;
    border-radius: 8px;
    background-color: #fff;
    &.active {
      border: 1px solid #0052d9;
      background-color: #f2f3ff;
    }
    &.disabled {
      user-select: none;
      pointer-events: none;
    }
    img {
      width: 40px;
      margin-right: 10px;
    }
  }
  .verification-button {
    width: 100%;
    margin-top: 20px;
  }
  @media screen and (max-width: 650px) {
    .header-nav {
      font-size: 24px;
    }
    .submit_btn {
      border-radius: 50px;
    }
    .step-container {
      .container-header {
        display: none;
      }
      .container-inner {
        .btn-wrap {
          .el-button {
            width: 100%;
            margin-left: 0;
            border-radius: 42px;
            &:first-child {
              margin-bottom: 30px;
            }
          }
        }
      }
    }
  }
}
</style>
