<template>
  <LoginLayout>
    <div class="outer-page 2xl:py-185px 2xl:px-130px lg:py-136px lg:px-60px ">
      <div class="inner" v-if="step !== 4">
        <!-- 忘记密码form -->
        <div class="text-24px c-#000 fw-700">{{ title }}</div>
        <div class="mt-24px mb-40px w-100% h-1px bg-#D1D5DB"></div>
        <div v-show="step === 1">
          <a-form ref="postFormRef" :model="postForm" :rules="postFormRules" :colon="false">
            <a-form-item ref="account" label="手机号/邮箱" name="account" class="mb-32px custom-form-item">
              <a-input v-model:value="postForm.account" size="large" placeholder="请输入您的手机号/邮箱" />
            </a-form-item>
          </a-form>
          <a-button
            :disabled="!postForm.account.length"
            :loading="captchaLoading"
            class="w-full disabled:bg-#80B3FF bg-#0068FF !b-rd-6px text-#fff !fw-700 !h-56px !text-#fff"
            size="large"
            @click="onSendCaptcha"
            >下一步</a-button
          >
        </div>
        <!-- 验证码form -->
        <a-form v-if="step === 2" ref="captchaFormRef" :model="postForm" :rules="postFormRules" :colon="false">
          <div class="tips flex justify-between mb-24px">
            <div class="text text-#666666">验证码已发送至 {{ maskedPhoneOrEmail(postForm.account) }}</div>
            <div class="c-#0068FF cursor-pointer" @click="onSendCaptcha" v-if="seconds === 0">重新发送</div>
            <div class="c-ccc" v-else>重新发送({{ seconds }}s)</div>
          </div>
          <a-form-item class="!mb-0">
            <CaptchaCodeInput v-model="postForm.captcha"></CaptchaCodeInput>
          </a-form-item>
          <a-form-item class="flex justify-center">
            <a-button
              :disabled="postForm.captcha.length != 6"
              class="w-180px mt-50px bg-#0068FF disabled:bg-#80B3FF !b-rd-6px text-#fff !fw-700 !h-42px !text-#fff"
              size="large"
              @click="onCheckCode"
              >提交验证</a-button
            >
          </a-form-item>
        </a-form>

        <!-- 重设密码form -->
        <a-form v-if="step === 3" ref="pwdFormRef" :model="postForm" :rules="postFormRules" :colon="false">
          <a-form-item label="密码" class="custom-form-item" name="newPassword">
            <a-input-password placeholder="请输入新密码" v-model:value="postForm.newPassword"></a-input-password>
          </a-form-item>
          <a-form-item label="确认新密码" class="custom-form-item" name="confirmPassword">
            <a-input-password placeholder="请再次输入新密码" v-model:value="postForm.confirmPassword"></a-input-password>
          </a-form-item>
          <a-form-item>
            <a-button class="w-full mt-10px bg-#0068FF !b-rd-6px text-#fff !fw-700 !h-56px !text-#fff" size="large" @click="onSubmit"
              >下一步</a-button
            >
          </a-form-item>
        </a-form>
      </div>

      <div class="text-center" v-if="step === 4">
        <img class="w-88px h-88px" src="@/assets/images/check.png" alt="" />
        <div>
          <h3 class="c-333 fw-700 fs-24 mb-20px mt-32px">新密码设置成功</h3>
          <div class="c-333 mb-42px">请妥善保管您的密码， 且不要分享给其他人</div>
          <router-link to="/login">
            <a-button class="w-180px bg-#0068FF !b-rd-6px text-#fff !fw-700 !h-42px !text-#fff" size="large" @click="onSendCaptcha">去登录</a-button>
          </router-link>
          <div class="mt-20px text-12px text-#000/60">{{ countNum }} 秒后将自动跳转至登录页</div>
        </div>
      </div>
    </div>
  </LoginLayout>
</template>

<script setup lang="ts">
// import LoginLayout from 'Components/layout/LoginLayout.vue'
import useUserStore from 'Store/modules/user'
import { useRoute } from 'vue-router'

// import type { ForgetPwdData, CaptchaData } from 'Types/api/user'
// import UploadOneImage from '@/components/upload/UploadOneImage.vue'
// import DragVerify from '@/components/DragVerify.vue'
// import CaptchaCodeInput from '@/components/CaptchaCodeInput.vue'

// import { Dayjs } from 'dayjs';
import type { UnwrapRef } from 'vue'
import type { Rule } from 'ant-design-vue/es/form'
import { apiSendCaptcha, apiCheckCaptcha, apiChangePassword } from 'API/user'

import { validatePhoneOrEmail, maskedPhoneOrEmail, validatePassword, genValidateTrue, genValidateRePassword } from 'Utils/validate'
import type { ForgetPwdData, CaptchaData } from 'Types/api'
// 获取地址栏参数
const route = useRoute()
const phone = route.query.phone as string

const postFormRef = ref()
const captchaLoading = ref(false)
const captchaFormRef = ref()
const pwdFormRef = ref()
const countNum = ref(10)
// 当前注册阶段
let step = ref(1)
let seconds = ref(0)
interface ICaptcha {
  account: string
  type: string
}
const router = useRouter()
const title = computed(() => {
  return step.value === 1 ? '忘记密码' : step.value === 2 ? '请输入6位短信验证码' : '重设密码'
})

const postForm: UnwrapRef<ForgetPwdData> = reactive({
  account: phone || '',
  captcha: '',
  newPassword: '',
  confirmPassword: '',
  token: '',
})
const postFormRules: Record<string, Rule[]> = {
  account: [{ required: true, validator: validatePhoneOrEmail, trigger: 'change' }],
  captcha: [{ required: true, message: '验证码未输入', trigger: 'change' }],
  newPassword: [{ required: true, validator: validatePassword, trigger: 'change' }],
  confirmPassword: [{ required: true, validator: genValidateRePassword(toRefs(postForm).newPassword) }],
}

const onSendCaptcha = async () => {
  try {
    captchaLoading.value = true
    await postFormRef.value.validate()
    const captcha: CaptchaData = {
      account: postForm.account,
      type: 's_forgot_password',
    }
    await apiSendCaptcha(captcha)
    captchaLoading.value = false
    countSeconds()
    step.value = 2
  } catch (error) {
    captchaLoading.value = false
  }
}

const countSeconds = () => {
  seconds.value = 60
  const timer = setInterval(() => {
    seconds.value--
    if (seconds.value === 0) {
      clearInterval(timer)
    }
  }, 1000)
}
/**
 * 检查验证码是否正确
 */
const onCheckCode = () => {
  captchaFormRef.value
    .validate()
    .then(() => {
      console.log('values', postForm, toRaw(postForm))
      apiCheckCaptcha({
        captcha: postForm.captcha,
        account: postForm.account,
        type: 's_forgot_password',
      }).then((res) => {
        if (res.data.success) {
          postForm.token = res.data.result.token
          step.value = 3
        }
      })
      // const userStore = useUserStore()
      // userStore.register(toRaw(postForm)).catch(() => {
      //   postForm.isUnlock = false
      // })
    })
    .catch((error: Error) => {
      console.log('error', error)
    })
}
const onSubmit = () => {
  pwdFormRef.value
    .validate()
    .then(() => {
      console.log('values', postForm, toRaw(postForm))
      apiChangePassword(toRaw(postForm)).then((res) => {
        if (res.data?.success) {
          step.value = 4
          setCountNum()
        }
      })
    })
    .catch((error: Error) => {
      console.log('error', error)
    })
}
const setCountNum = () => {
  countNum.value = 10
  const timer = setInterval(() => {
    countNum.value--
    if (countNum.value === 0) {
      clearInterval(timer)
      router.push('/login')
    }
  }, 1000)
}
</script>

<style scoped lang="less">
@import '@/assets/styles/variables.less';
.page {
  .tabs {
    display: flex;
    justify-content: center;
    margin-bottom: 70px;
    .tab {
      padding-bottom: 10px;
      border-bottom: 4px solid transparent;
      transition: 0.3s;
      &.active {
        border-bottom: 4px solid @color-new-primary;
        color: @color-new-primary;
        font-weight: 700;
      }
    }
  }

  .outer-page {
    background-color: #fff;
    border-radius: 18px;
    display: flex;
    justify-content: center;
    align-items: center;
    .inner {
      width: 376px;
    }
  }
  ::v-deep(.ant-form) {
    .ant-form-item {
      &.custom-form-item {
        .ant-form-item-row {
          display: block !important;
          width: 100% !important;

          .ant-form-item-label {
            color: #000000;
            margin-bottom: 10px;
          }

          .ant-form-item-control {
            .ant-input-affix-wrapper {
              border-radius: 6px;
              width: 100%;
              border-color: #8692a6;
              input {
                height: 40px;
              }
            }
            input {
              width: 100%;
              border-radius: 6px;
              border-color: #8692a6;
              height: 50px;
              &.ant-input-status-error {
                border-color: #ff4d4f;
              }
            }
            .ant-form-item-explain-error {
              text-align: right;
            }
          }
        }
        &.error-form-item {
          .ant-form-item-explain-error {
            padding-right: 140px;
          }
        }
      }
      .custom-radio {
        .ant-checkbox {
          margin-right: 10px;
          &.ant-checkbox-checked {
            .ant-checkbox-inner {
              background-color: #0068ff;
              border-color: #0068ff;
            }
            &:after {
              border: 1px solid #0068ff;
            }
          }
          .ant-checkbox-inner {
            &:hover {
              border-color: #0068ff !important;
            }
          }
        }
      }
    }
  }
}
</style>
