<template>
    <div class="container" style="justify-content: space-between;">
      <div class="login-header">
        <svg-icon icon-class="logo" class="logo-img" />
          <i18n class="lang-menu" @change="changeLang"/>
      </div>
      <div class="login">
        <div class="title">
          <svg-icon icon-class="goBack" class="go-back-icon" @click="goLogin" />
          <div>{{ t('common.forgotPassword') }}</div>
        </div>
        <div class="step-wrap">
          <div class="step-item">
            <div class="step-num" :class="{'step-num-active': curStep == 1}">1</div>
            <div class="step-text" :class="{'step-text-active': curStep == 1}">{{ t('forgotPassword.step1') }}</div>
          </div>
          <div class="step-item-gap"></div>
          <div class="step-item">
            <div class="step-num" :class="{'step-num-active': curStep == 2}">2</div>
            <div class="step-text" :class="{'step-text-active': curStep == 2}">{{ t('forgotPassword.step2') }}</div>
          </div>
          <div class="step-item-gap"></div>
          <div class="step-item">
            <div class="step-num" :class="{'step-num-active': curStep == 3}">3</div>
            <div class="step-text" :class="{'step-text-active': curStep == 3}">{{ t('forgotPassword.step3') }}</div>
          </div>
        </div>
        <el-form v-if="curStep == 1" ref="step1Ref" :model="step1Form" :rules="step1Rules" class="login-form" hide-required-asterisk>
          <el-form-item prop="email">
            <el-input v-model="step1Form.email" type="text" size="large" auto-complete="off" :placeholder="t('forgotPassword.emailPlaceholder')" >
              <template #prefix>
                <svg-icon icon-class="inputMail"  style="width: 30px;height: 30px;"/>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input v-model="step1Form.code" type="text" size="large" auto-complete="off" style="width: 360px;margin-right: 14px;" :placeholder="t('forgotPassword.codePlaceholder')" >
              <template #prefix>
                <svg-icon icon-class="inputSend"  style="width: 30px;height: 30px;"/>
              </template>
            </el-input>
            <el-button plain class="send-btn" :disabled="disSend" @click="sendCode" >{{ sendBtnText }}</el-button>
          </el-form-item>
          <el-form-item>
            <el-button class="login-btn" :loading="loading" size="large" type="primary" @click.prevent="handleStep1" :disabled="!step1Form.email || !step1Form.code" >
              <span>{{ t('form.next') }}</span>
              <template #loading>
                <l-ring-2 size="20" stroke="2" stroke-length="0.25" bg-opacity="0.1" speed="0.8" color="white" style="margin-right: 17px;" ></l-ring-2>
              </template>
            </el-button>
          </el-form-item>
        </el-form>
        <el-form v-else-if="curStep == 2" ref="step2Ref" :model="step2Form" :rules="step2Rules" class="login-form" hide-required-asterisk>
          <el-form-item prop="password">
            <el-input v-model="step2Form.password" type="password" show-password size="large" auto-complete="off" :placeholder="t('forgotPassword.pwdPlaceholder')" >
              <template #prefix>
                <svg-icon icon-class="inputLock1"  style="width: 30px;height: 30px;"/>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <password-validator v-if="step2Form.password" ref="pv1" v-model="step2Form.password" />
          </el-form-item>
          <el-form-item prop="password2">
            <el-input v-model="step2Form.password2" type="password" show-password size="large" auto-complete="off" :placeholder="t('forgotPassword.pwd2Placeholder')" >
              <template #prefix>
                <svg-icon icon-class="inputLock2"  style="width: 30px;height: 30px;"/>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="login-btn" :loading="loading" size="large" type="primary" @click.prevent="handleStep2" :disabled="!step2Form.password || !step2Form.password2" >
              <span>{{ t('forgotPassword.update') }}</span>
              <template #loading>
                <l-ring-2 size="20" stroke="2" stroke-length="0.25" bg-opacity="0.1" speed="0.8" color="white" style="margin-right: 17px;" ></l-ring-2>
              </template>
            </el-button>
          </el-form-item>
        </el-form>
        <div v-else-if="curStep == 3">
          <div style="width: 100%;display: flex;flex-direction: column;align-items: center;">
            <svg-icon icon-class="success" style="width: 80px;height: 80px;" />
            <div style="font-size: 32px;font-weight: 700;margin: 26px 0 10px">{{ t('forgotPassword.resetPwdSuccess') }}</div>
          </div>
          <el-button class="login-btn" size="large" type="primary" @click.prevent="goLogin" >
              <span>{{ t('forgotPassword.goIndex') }}</span>
          </el-button>
        </div>
      </div>
      <!--  底部  -->
      <div class="login-footer">
        <el-divider />
        <div v-html="footerText"></div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { computed, ref } from "vue";
  import { sendCodeForgot, checkCodeForgot, saveNewPwdForgot } from "@/api/login";
  import Cookies from "js-cookie";
  import { encrypt, decrypt } from "@/utils/jsencrypt";
  import useUserStore from '@/store/modules/user'
  import useAppStore from '@/store/modules/app'
  import { useLocale } from 'element-plus'
  import { getTemplateDetailByCode } from "@/api/common";
  import { serverLang, clientLang } from '@/utils/i18n'
  import I18n from "@/components/I18n"
  import PasswordValidator from "@/components/PasswordValidator"
  
  const { t } = useLocale()
  const userStore = useUserStore()
  const appStore = useAppStore()
  const route = useRoute();
  const router = useRouter();
  const { proxy } = getCurrentInstance();

  let timeInterval

  const checkEmail = (rule, value, callback) => {
    const pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    if (!value) {
      return callback(new Error(t('form.email.required')))
    }
    if (!pattern.test(value)) {
      return callback(new Error(t('form.email.invalid')))
    }
    callback()
  }

  const checkPwd = (rule, value, callback) => {
    if (!value) {
      return callback(new Error(t('forgotPassword.pwd2Placeholder')))
    }
    if (value != step2Form.value.password) {
      return callback(new Error(t('form.confirmPassword.invalid')))
    }
    callback()
  }
  const countdown = ref(((new Date().getTime() - appStore.countdown) / 1000) > 60 ? 0 : (60 - (new Date().getTime() - appStore.countdown) / 1000).toFixed(0));
  if (countdown.value > 0) {
    timeInterval = setInterval(() => {
      if ((new Date().getTime() - appStore.countdown) / 1000 > 0 && (new Date().getTime() - appStore.countdown) / 1000 < 60) {
        countdown.value--
      } else {
        clearInterval(timeInterval)
        appStore.setCountdown(0)
        countdown.value = 0
      }
    }, 1000)
  }

  const sendBtnText = computed(() => {
    if (countdown.value == 0) {
      return t('forgotPassword.sendCode')
    } else {
      return `( ${countdown.value} )`
    }
  })

  const disSend = computed(() => {
    return countdown.value > 0 || !step1Form.value.email
  })

  function sendCode() {
    countdown.value = 60
    appStore.setCountdown(new Date().getTime())
    timeInterval = setInterval(() => {
      if ((new Date().getTime() - appStore.countdown) / 1000 > 0 && (new Date().getTime() - appStore.countdown) / 1000 < 60) {
        countdown.value--
      } else {
        clearInterval(timeInterval)
        appStore.setCountdown(0)
        countdown.value = 0
      }
    }, 1000)
    sendCodeForgot({
      email: step1Form.value.email,
      qcc_language: serverLang()
    }).then(resp => {
      window.showTip({
        title: t('common.success.send'),
        status: 'success'
      })
    }).catch(() => {
      clearInterval(timeInterval)
      appStore.setCountdown(0)
      countdown.value = 0
    })
  }

  const pv1 = ref(null)
  
  const step1Form = ref({
    email: "",
    code: ""
  });

  const step2Form = ref({
    email: "",
    sign: ""
  });
  
  const step1Rules = {
    email: [{ required: true, trigger: "blur", message: t('form.email.required') }],
    code: [{ required: true, trigger: "change", message: t('form.captcha.required') }]
  };

  const step2Rules = {
    password: [{ required: true, trigger: "blur", message: t('forgotPassword.pwdPlaceholder') }],
    password2: [
      { required: true, trigger: "blur", message: t('forgotPassword.pwd2Placeholder') },
      { trigger: "blur", validator: checkPwd }
    ]
  };
  
  const loading = ref(false);
  
  const footerText = ref('')

  function goLogin() {
    router.replace({ path: '/' })
  }

  const curStep = ref(1)
  
  function handleStep1() {
    proxy.$refs.step1Ref.validate(valid => {
      if (valid) {
        step2Form.value.email = step1Form.value.email
        loading.value = true;
        checkCodeForgot(step1Form.value).then(resp => {
          loading.value = false;
          step2Form.value.sign = resp.data
          curStep.value = 2
        }).catch(() => {
          loading.value = false;
        });
      }
    });
  }

  function handleStep2() {
    proxy.$refs.step2Ref.validate(valid => {
      if (valid && pv1.value.check()) {
        loading.value = true;
        saveNewPwdForgot(step2Form.value).then(resp => {
          loading.value = false;
          curStep.value = 3
          step2Form.value.password = undefined
          step2Form.value.password2 = undefined
        }).catch(() => {
          loading.value = false;
        });
      }
    });
  }
  
  function getFooterText() {
    getTemplateDetailByCode({
      qcc_language: serverLang(),
      templateCode: 'COMPANY_INFO'
    }).then(resp => {
      if (resp.data && resp.data.content) {
        footerText.value = resp.data.content
      }
    })
  }
  
  function changeLang(lang) {
    getFooterText();
  }
  
  getFooterText();

  </script>
  
  <style lang='scss' scoped>
  .login-header, .login-footer {
    height: 60px;
    flex-shrink: 0;
    width: 100%;
  }
  
  .login-header {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: space-between;
    padding: 0 3.85%;
  
    .logo-img {
      align-self: center;
      width: 120px;
      height: 45px;
    }
  
    .lang-menu {
      margin-top: 30px;
    }
  }
  
  .login-footer {
    padding: 0 3.85%  1%;
    font-size: 12px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 27px;
    color: rgba(184, 184, 184, 1);
    text-align: left;
    vertical-align: top;
    flex-shrink: 0;
    height: auto;
  }

  .title {
    align-self: flex-start;
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 700;
    line-height: 24px;
    margin-left: -48px;

    .go-back-icon {
      cursor: pointer;
      width: 23px;
      height: 23px;
      margin-right: 24px;
    }
  }

  .step-wrap {
    width: 100%;
    min-height: 35px;
    margin: 30px 0;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    column-gap: 10px;
    flex-wrap: nowrap;

    .step-item {
      // max-width: calc((100% - 70px) / 3);
      flex-grow: 0;
      flex-shrink: 0;
      display: flex;
      align-items: flex-start;
      line-height: 26px;
      position: relative;

      .step-num {
        width: 26px;
        height: 26px;
        border-radius: 50%;
        border: 1px solid rgba(133, 140, 153, 1);
        color: rgba(133, 140, 153, 1);
        font-size: 14px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 8px;
        flex-shrink: 0;
      }

      .step-num-active {
        background: rgba(41, 187, 228, 1);
        color: #ffffff;
      }

      .step-text {
        font-size: 24px;
        color: rgba(133, 140, 153, 1);
        text-align: left;
      }

      .step-text-active {
        font-weight: 700;
        color: #000;
      }
    }

    .step-item-gap {
      margin: 13px auto 0;
      height: 1px;
      width: 35px;
      background-color: #D6D6D6;
    }
  }
  
  .login {
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    flex-grow: 1;
    // width: 564px;
  }
  
  .login-form {
    border-radius: 6px;
    background: #ffffff;
    width: 100%;
  
    :deep(.el-form-item__label) {
      margin-top: 25px;
      font-size: 20px;
      font-weight: 400;
      letter-spacing: 0px;
      color: rgba(51, 51, 51, 1);
    }
  
    :deep(.el-input__password) {
      font-size: 20px;
    }
  
    .el-input {
      height: 50px;
      width: 100%;
      font-size: 20px;
      input {
        height: 50px;
      }
    }
  
    :deep(.el-select) {
      height: 50px;
      width: 100%;
      font-size: 20px;
      input {
        height: 48px;
      }
    }
  }

  .send-btn {
    margin-left: auto;
    height: 50px;
    font-size: 20px;
    flex-grow: 1;
    flex-shrink: 0;
    --el-button-text-color: #29bbe4;
    --el-disabled-text-color: #29bbe4;
  }
  
  .login-btn {
    margin-top: 30px;
    width: 100%;
    height: 50px;
    font-size: 20px;
  }
  </style>
  