<template>
  <div class="full-width window-height row" style="background-color: #F1F2F4;">
    <div class="col">
        <div class=" full-height column"  style="padding: 50px 0; width:435px;margin:0 auto">
        <div>
            <img src="https://imgfile.oytour.com/static/pptdefault1.png" style="height: 25px;width: auto;">
        </div>
        <div class="col column items-center flex-center full-width">
            <div class="text-center  full-width" v-if="!resetToken && !validateFaild">
                <div class="text-weight-bold text-dark" style="font-size: 23px;">忘记密码？</div>
                <div class="text-info q-mt-md q-mb-xl" style="font-size: 14px; font-weight: 500;">输入你的注册邮箱，重置你的密码。</div>
                <el-input v-model="email" placeholder="邮箱" size="large" clearable class="pingfangr full-width" :readonly="isSend" style="height:50px !important;">
                    <template #suffix>
                        <el-button link :loading="sending" v-if="!isCountdown && isSend" @click="sendVerifyCode">重新发送</el-button>
                        <template  v-if="isCountdown">
                            <el-countdown title="" format="ss" :value="countValue" value-style="font-size:14px;color:#f89c53;" class="inline q-mx-sm" @finish="()=>isCountdown=false" />s
                        </template>
                    </template>
                </el-input>
                <div class="q-mt-lg" v-if="isSend">
                    <div class="text-small text-info text-left q-mb-md">请输入邮件验证码：</div>
                    <VerifyCode v-model="code" :digit="6"></VerifyCode>
                </div>
                
                <el-button type="primary" size="large" class="q-mt-lg ppt-button" :disabled="!mailRegex.test(email)"  @click="sendVerifyCode" :loading="sending" v-if="!isSend">发送验证码</el-button>
                <el-button type="primary" size="large" class="q-mt-lg ppt-button" :disabled="code.length!=6" :loading="sending" v-if="isSend && !sending" @click="verifyHandler">提交验证码</el-button>
            </div>
            <div class="full-width" v-if="resetToken && !validateFaild">
                <div class="text-weight-bold text-dark" style="font-size: 16px;">重新设置你的密码</div>
                <div class="text-weight-bold text-dark q-mt-md" style="font-size: 24px;">{{ resetToken.mail }}</div>
                <div class="text-info q-mt-md q-mb-xl" style="font-size: 14px; font-weight: 500;">我们建议你的密码包含大写+小写+数字+特殊字符进行组合</div>
                <el-input v-model="resetModel.newPassword" type="password" placeholder="新密码" size="large" show-password class="pingfangr full-width" style="height:50px !important;" />
                <el-input v-model="resetModel.confirmPassword"  type="password" placeholder="确认密码" size="large" show-password class="pingfangr full-width q-mt-lg" style="height:50px !important;" />
                <div>
                    <el-button type="primary" size="large" class="q-mt-lg ppt-button"  @click="resetPassword" :loading="loading">确认密码</el-button>
                </div>
            </div>
            <div class="full-width" v-if="validateFaild">
                <div class="text-weight-bold text-dark" style="font-size: 16px;">你的请求未通过验证</div>
                <div class="text-info q-mt-md q-mb-xl" style="font-size: 14px; font-weight: 500;">我们无法通过你的请求，可能是由于你的链接已经失效，点击下方按钮重新发起申请。</div>
                <div>
                    <el-button type="primary" size="large" class="q-mt-lg ppt-button"  @click="refereHandler">重新申请修改密码</el-button>
                </div>
            </div>
        </div>
        <div>
            <el-button link icon="Back" size="large" class="ppt-button text-weight-bolder" @click="forwardHandler('/login')"> 返回登录</el-button>
        </div>
        </div>
    </div>
    <div class="col forgot-right-panel column flex-center items-center">
        <img src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Upload/Goods/638521566644129630.png" style="width:400px;user-select: none">
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ApiResult } from "@/configs/axios";
import UserServices from "@/services/UserService";
import { ElLoading, ElMessage } from "element-plus";
import { reactive, ref } from "vue";
import VerifyCode from "@/views/components/element/Verify/VerifyCode.vue";
import { useRouter } from "vue-router";
const email = ref('')
const mailRegex = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/
const loading = ref(false)
const sending = ref(false)
const code = ref('')
const isSend = ref(false)
const isCountdown = ref(false)
const countValue = ref<number>(0)
const resetToken = ref<any>()
const validateFaild = ref(false)
const resetModel = reactive({
    newPassword:'',
    confirmPassword:''
})
const router = useRouter()
const sendVerifyCode = async()=>{
    if(!mailRegex.test(email.value) || sending.value) return
    sending.value= true
    
    const response = await UserServices.SendResetPassCodeAsync(email.value)
    if(response.data.resultCode == ApiResult.SUCCESS){
        ElMessage.success({message:'验证码已发送，请前往邮箱查看'})
        isCountdown.value = true
        countValue.value = Date.now() + 1000 * 60
        isSend.value = true
    } else {
        ElMessage.error({message:response.data.message})
    }
    sending.value= false
}
const verifyHandler = async ()=>{
  if(code.value.length!=6 || !mailRegex.test(email.value) || sending.value || loading.value) return
  loading.value=true
  const response = await UserServices.VerifyResetPassCodeAsync(email.value,code.value,'')
  if(response.data.resultCode == ApiResult.SUCCESS){
    resetToken.value = response.data.data
    ElMessage.success({message:'验证成功，请重新设置你的密码'})
  }else{
    ElMessage.error({message:response.data.message})
  }
  loading.value=false
}


const resetPassword = async()=>{
    if(resetModel.newPassword.length<6||resetModel.newPassword.length>20){
        ElMessage.error({message:'新密码长度应为6-20位'})
        return
    }
    if(resetModel.newPassword!=resetModel.confirmPassword){
        ElMessage.error({message:'两次输入的密码不一致, 请重新输入'})
        return
    }
    if(loading.value) return
    loading.value=true

    const response = await UserServices.ResetPasswordAsync(resetModel.newPassword,resetToken.value.r_token)
    if(response.data.resultCode == ApiResult.SUCCESS){
        ElMessage.success({message:'密码更新成功，正在前往登录页面'})
        setTimeout(() => {
            forwardHandler('/login')
        }, 1000);
        return
    }
    ElMessage.error({message:response.data.message})
    loading.value=false
}
const forwardHandler=(path:string)=>{
    router.push({path})
}
const checkQuickValidate = async ()=>{
    const params = router.currentRoute.value.params
    if(router.currentRoute.value.fullPath.includes('/newpass/') && params.code && params.token) {
        const validLoading = ElLoading.service({text:'正在加载中...',lock:true})
        const response = await UserServices.VerifyResetPassCodeAsync('',params.code.toString(),params.token.toString())
        if(response.data.resultCode == ApiResult.SUCCESS){
            resetToken.value = response.data.data
            ElMessage.success({message:'验证成功，请重新设置你的密码'})
        } else validateFaild.value=true
        validLoading.close()
    }
}
const refereHandler = ()=>{
    location.href='/forgot'
}
checkQuickValidate()
</script>

<style>
.forgot-right-panel{
    background-image: url('https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Upload/Goods/638521440349462315.png');
    background-position: center;
    background-size: cover;
}
</style>