<template>
  <Modal
    v-model:visible="dialogShow"
    v-if="dialogShow"
    @cancel="toCancel"
    centered
    :maskClosable="false"
  >
    <template #title v-if="step === 1 || step === 2">
      {{ dialogTitle }}
    </template>

    <a-form
      :model="forgetForm"
      ref="forgetFormRef"
      :rules="forgetRules"
      name="basic"
      layout="vertical"
    >
      <!-- 第一步 -->
      <a-form-item name="userName" v-if="step === 1">
        <c-input
          v-model:value.trim="forgetForm.userName"
          placeholder="请输入账户名称"
          autocomplete="off"
          size="large"
        >
        </c-input>
      </a-form-item>

      <!-- 第二步 -->
      <a-form-item name="mobile" v-if="step === 2">
        <c-input
          v-model:value.trim="forgetForm.mobile"
          :placeholder="`请输入${
            forgetForm.verifyType === 'SMS'
              ? '手机号'
              : forgetForm.verifyType === 'EMAIL'
              ? '邮箱'
              : ''
          }`"
          disabled
          size="large"
        >
          <template #addonAfter>
            <a-select
              v-model:value="forgetForm.verifyType"
              size="large"
              style="width: 150px"
            >
              <a-select-option
                :value="item.value"
                :key="item.value"
                v-for="item in verifyTypeOptios"
                >{{ item.label }}</a-select-option
              >
            </a-select>
          </template>
        </c-input>
      </a-form-item>

      <a-form-item name="verifyCode" v-if="step === 2">
        <div class="verification">
          <c-input
            v-model:value.trim="forgetForm.verifyCode"
            placeholder="请输入六位数验证码"
            size="large"
            class="code-ipt"
          ></c-input>
          <a-button
            @click="handerCode"
            :loading="btnLoading"
            size="large"
            class="code-btn"
          >
            {{ codeInfo.disabled ? `已发送(${codeInfo.count})` : "获取验证码" }}
          </a-button>
        </div>
      </a-form-item>

      <!-- 第三步 -->
      <!-- 新密码 -->
      <a-form-item name="password" label="新密码" v-if="step === 3">
        <c-input-password
          v-model:value.trim="forgetForm.password"
          placeholder="请输入密码"
          size="large"
        ></c-input-password>
      </a-form-item>

      <!-- 确认密码 -->
      <a-form-item
        name="confirmPassword"
        label="再次确认新密码"
        v-if="step === 3"
      >
        <c-input-password
          v-model:value.trim="forgetForm.confirmPassword"
          placeholder="请确认密码"
          size="large"
        ></c-input-password>
      </a-form-item>
    </a-form>

    <template #footer>
      <!-- 第1步 -->
      <a-button
        v-if="step === 1"
        key="back"
        type="primary"
        :loading="nextBtnloading"
        @click="toNextStep"
        >下一步</a-button
      >

      <!-- 第2步 -->
      <div class="code-bnt" v-if="step === 2">
        <a-button
          key="back"
          type="primary"
          @click="toSubmitPassword"
          :loading="codeBtnloading"
          block
          >确定</a-button
        >
      </div>

      <!-- 第3步 -->
      <template v-if="step === 3">
        <a-button
          key="back"
          type="primary"
          html-type="submit"
          :loading="saveBtnloading"
          @click="toEditSavePassword"
          >保存</a-button
        >
        <a-button key="back" @click="toCancel">取消</a-button>
      </template>
    </template>
  </Modal>
</template>

<script lang="ts" setup>
import { useVModel } from "@vueuse/core";
import { Modal, message as CMS } from "ant-design-vue";
import { ref, reactive, watch, computed } from "vue";
import { formRulesFn } from "../config/rules";
import { verifyTypeOptios, countDownTime } from "../config";

const nextBtnloading = ref<boolean>(false);
const codeBtnloading = ref<boolean>(false);
const saveBtnloading = ref<boolean>(false);
const props = defineProps({
  modelValue: {
    type: Boolean,
    require: true,
  },
  userInfo: {
    type: Object,
    default: () => {},
  },
});
const emit = defineEmits([
  "update:modelValue",
  "verifyUserName",
  "toSubmitPassword",
  "toEditSavePassword",
  "handerCode",
]);

let dialogShow = useVModel(props, "modelValue");

const forgetForm: any = reactive({
  userName: "",
  password: "",
  confirmPassword: "",
  verifyType: "SMS",
  mobile: "",
  verifyCode: "",
});
let dialogTitle = ref("请填写需要找回的账号");
let step = ref(1);
let btnLoading = ref(false);
const forgetFormRef = ref();
let forgetRules = formRulesFn(forgetForm);

// 验证码参数
const codeInfo = reactive({
  count: countDownTime, //倒计时数
  disabled: false, //是否被禁用
});

// 关闭弹框
const toCancel = (e) => {
  dialogShow.value = false;
};

watch(
  () => forgetForm.verifyType,
  (newVal) => {
    console.log("verifyType", newVal);
    if (newVal === "SMS") {
      forgetForm.mobile = computed(() => {
        return props.userInfo.mobile;
      });
    } else if (newVal === "EMAIL") {
      forgetForm.mobile = computed(() => {
        return props.userInfo.email;
      });
    }
  },
  { deep: true, immediate: true }
);

//第1步
const toNextStep = async () => {
  await forgetFormRef.value.validateFields("userName");
  nextBtnloading.value = true;
  emit(
    "verifyUserName",
    forgetForm.userName,
    () => {
      step.value = 2;
      dialogTitle.value = "请选择验证方式，并提供您收到的验证码";
      nextBtnloading.value = false;
    },
    () => {
      nextBtnloading.value = false;
    }
  );
};

//第2步
//获取验证码
const handerCode = async () => {
  await forgetFormRef.value.validateFields("mobile");
  if (!codeInfo.disabled) {
    btnLoading.value = true;
    emit(
      "handerCode",
      { type: forgetForm.verifyType, content: forgetForm.mobile },
      () => {
        CMS.info("短信验证码已发送，请注意查收!");
        codeInfo.disabled = true;
        btnLoading.value = false;
        countdownHandler();
      },
      () => {
        // CMS.error("短信验证码发送失败，请重试!");
        btnLoading.value = false;
      }
    );
  }
};

//第2步
//提交验证
const toSubmitPassword = async () => {
  await forgetFormRef.value.validateFields("mobile");
  await forgetFormRef.value.validateFields("verifyCode");
  codeBtnloading.value = true;
  emit(
    "toSubmitPassword",
    forgetForm,
    () => {
      step.value = 3;
      codeBtnloading.value = false;
    },
    () => {
      codeBtnloading.value = false;
    }
  );
};

//第3步
const toEditSavePassword = async () => {
  await forgetFormRef.value.validateFields("password");
  await forgetFormRef.value.validateFields("confirmPassword");
  saveBtnloading.value = true;

  emit(
    "toEditSavePassword",
    forgetForm,
    () => {
      dialogShow.value = false;
      saveBtnloading.value = false;
    },
    () => {
      saveBtnloading.value = false;
    }
  );
};

// 发送验证码的倒计时
const countdownHandler = () => {
  var countdown = function () {
    if (codeInfo.count == 0) {
      codeInfo.disabled = false;
      codeInfo.count = countDownTime;
      return;
    } else {
      codeInfo.disabled = true;
      codeInfo.count--;
    }
    setTimeout(countdown, 1000);
  };
  setTimeout(countdown, 1000);
};
</script>

<script lang="ts">
import { defineComponent } from "vue";
import { log } from "console";
export default defineComponent({
  name: "c-forget-password",
});
</script>

<style lang="less" scoped>
.code-bnt {
  width: 100% !important;
  display: block;
}
.verification {
  display: flex;
  background-color: #fff;
  .code-ipt {
    flex: 1;
  }
  .code-btn {
    width: 150px;
    background-color: #fff;
    display: block;
    overflow-wrap: break-word;
    white-space: nowrap;
    margin-left: 8px;
  }
  // }
}
</style>
