<template>
  <div class="aui-content">
    <div class="aui-container">
      <div class="aui-form">
        <div class="aui-image">
          <div class="aui-image-text">
            <img :src="adTextImg" alt="" />
          </div>
        </div>
        <div class="aui-formBox">
          <div class="aui-formWell">
            <div class="aui-step-box">
              <div class="aui-step-item" :class="activeKey === 1 ? 'activeStep' : ''">
                <div class="aui-step-tags">
                  <em>1</em>
                  <p><% if (enableTranslation) { %>{{t('sys.login.authentication')}}<% } else { %>t$t('sys.login.authentication')$t$<% } %></p>
                </div>
              </div>
              <div class="aui-step-item" :class="activeKey === 2 ? 'activeStep' : ''">
                <div class="aui-step-tags">
                  <em>2</em>
                  <p><% if (enableTranslation) { %>{{t('sys.login.resetLoginPassword')}}<% } else { %>t$t('sys.login.resetLoginPassword')$t$<% } %></p>
                </div>
              </div>
              <div class="aui-step-item" :class="activeKey === 3 ? 'activeStep' : ''">
                <div class="aui-step-tags">
                  <em>3</em>
                  <p><% if (enableTranslation) { %>{{t('sys.login.resetSuccess')}}<% } else { %>t$t('sys.login.resetSuccess')$t$<% } %></p>
                </div>
              </div>
            </div>
            <div class="" style="height: 230px; position: relative">
              <Form ref="formRef" :model="formData" v-if="activeKey === 1">
                <!-- 身份验证 begin -->
                <div class="aui-account aui-account-line aui-forgot">
                  <FormItem>
                    <div class="aui-input-line">
                      <Input type="text" <% if (enableTranslation) { %>:placeholder="t('sys.login.mobile')"<% } else { %>placeholder="t$t('sys.login.mobile')$t$"<% } %> v-model:value="formData.mobile" />
                    </div>
                  </FormItem>
                  <div class="aui-input-line">
                    <FormItem>
                      <Input type="text" <% if (enableTranslation) { %>:placeholder="t('sys.login.smsCode')"<% } else { %>placeholder="t$t('sys.login.smsCode')$t$"<% } %> v-model:value="formData.smscode" />
                    </FormItem>
                    <div v-if="showInterval" class="aui-code-line" @click="getLoginCode"><% if (enableTranslation) { %>{{ t('component.countdown.normalText') }}<% } else { %>t$t('component.countdown.normalText')$t$<% } %></div>
                    <div v-else class="aui-code-line"><% if (enableTranslation) { %>{{t('component.countdown.sendText',[unref(timeRuning)])}}<% } else { %>{{`${unref(timeRuning)}秒后重新获取`}}<% } %></div>
                  </div>
                </div>
                <!-- 身份验证 end -->
              </Form>
              <Form ref="pwdFormRef" :model="pwdFormData" v-else-if="activeKey === 2">
                <!-- 重置密码 begin -->
                <div class="aui-account aui-account-line aui-forgot">
                  <FormItem>
                    <div class="aui-input-line">
                      <Input type="password" <% if (enableTranslation) { %>:placeholder="t('sys.login.passwordPlaceholder')"<% } else { %>placeholder="t$t('sys.login.passwordPlaceholder')$t$"<% } %> v-model:value="pwdFormData.password" />
                    </div>
                  </FormItem>
                  <FormItem>
                    <div class="aui-input-line">
                      <Input type="password" <% if (enableTranslation) { %>:placeholder="t('sys.login.confirmPassword')"<% } else { %>placeholder="t$t('sys.login.confirmPassword')$t$"<% } %> v-model:value="pwdFormData.confirmPassword" />
                    </div>
                  </FormItem>
                </div>
                <!-- 重置密码 end -->
              </Form>
                <!-- 重置成功 begin -->
                <div class="aui-success" v-else>
                  <div class="aui-success-icon">
                    <img :src="successImg"/>
                  </div>
                  <h3>恭喜您，重置密码成功！</h3>
                </div>
                <!-- 重置成功 end -->
            </div>
            <div class="aui-formButton" style="padding-bottom: 40px">
              <div class="aui-flex" v-if="activeKey === 1 || activeKey === 2">
                <a class="aui-link-login aui-flex-box" @click="nextStepClick"><% if (enableTranslation) { %>{{t('sys.login.nextStep')}}<% } else { %>t$t('sys.login.nextStep')$t$<% } %></a>
              </div>
              <div class="aui-flex" v-else>
                <a class="aui-linek-code aui-flex-box" @click="toLogin"><% if (enableTranslation) { %>{{t('sys.login.goToLogin')}}<% } else { %>t$t('sys.login.goToLogin')$t$<% } %></a>
              </div>
              <div class="aui-flex">
                <a class="aui-linek-code aui-flex-box" @click="goBack"><% if (enableTranslation) { %>{{ t('sys.login.backSignIn') }}<% } else { %>t$t('sys.login.backSignIn')$t$<% } %></a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
    <!-- 图片验证码弹窗 -->
    <CaptchaModal @register="captchaRegisterModal" @ok="getLoginCode" />
</template>
<script lang="ts" setup>
  import { reactive, ref, toRaw, unref } from 'vue';
  import { Form, FormItem, Button } from 'ant-design-vue';
  <%_ if (enableTranslation) { _%>
  import { useI18n } from '@/hooks/web/useI18n';
  <%_ } _%>
  import { SmsEnum, useFormRules, useFormValid, useLoginState } from '@/views/account/login/useLogin';
  import { useMessage } from '@/hooks/web/useMessage';
  import { getImageCaptcha, passwordChange, phoneVerify } from '@/api-service/sys/user';
  import adTextImg from '@/assets/loginmini/icon/jeecg_ad_text.png'
  import successImg from '@/assets/loginmini/icon/icon-success.png';
  import { useModal, CaptchaModal } from '@begcode/components';
  import { ExceptionEnum } from '@/enums/exceptionEnum';
  const [captchaRegisterModal, { openModal: openCaptchaModal }] = useModal();

  defineOptions({
    name: 'MiniForgotpad',
  });

  //下一步控制
  const activeKey = ref<number>(1);
  <%_ if (enableTranslation) { _%>
  const { t } = useI18n();
  <%_ } _%>
  const { notification, createMessage, createErrorModal } = useMessage();
  //是否显示获取验证码
  const showInterval = ref<boolean>(true);
  //60s
  const timeRuning = ref<number>(60);
  //定时器
  const timer = ref<any>(null);
  const formRef = ref();
  const pwdFormRef = ref();
  //账号数据
  const accountInfo = reactive<any>({});
  //手机号表单
  const formData = reactive({
    mobile: '',
    smscode: '',
  });
  //密码表单
  const pwdFormData = reactive<any>({
    password: '',
    confirmPassword: '',
  });
  const emit = defineEmits(['go-back', 'success', 'register']);

  /**
   * 下一步
   */
  async function handleNext() {
    if (!formData.mobile) {
      createMessage.warn(<% if (enableTranslation) { %>t('sys.login.mobilePlaceholder')<% } else { %>'t$t('sys.login.mobilePlaceholder')$t$'<% } %>);
      return;
    }
    if (!formData.smscode) {
      createMessage.warn(<% if (enableTranslation) { %>t('sys.login.smsPlaceholder')<% } else { %>'t$t('sys.login.smsPlaceholder')$t$'<% } %>);
      return;
    }
    const resultInfo = await phoneVerify(
      toRaw({
        phone: formData.mobile,
        smscode: formData.smscode,
      })
    );
    if (resultInfo.success) {
      Object.assign(accountInfo, {
        username: resultInfo.result.username,
        phone: formData.mobile,
        smscode: formData.smscode,
      });
      activeKey.value = 2;
      setTimeout(()=>{
        pwdFormRef.value.resetFields();
      },300)
    } else {
      notification.error({
        message: '错误提示',
        description: resultInfo.message || <% if (enableTranslation) { %>t('sys.api.networkExceptionMsg')<% } else { %>'t$t('sys.api.networkExceptionMsg')$t$'<% } %>,
        duration: 3,
      });
    }
  }

  /**
   * 完成修改密码
   */
  async function finishedPwd() {
    if (!pwdFormData.password) {
      createMessage.warn(<% if (enableTranslation) { %>t('sys.login.passwordPlaceholder')<% } else { %>'t$t('sys.login.passwordPlaceholder')$t$'<% } %>);
      return;
    }
    if (!pwdFormData.confirmPassword) {
      createMessage.warn(<% if (enableTranslation) { %>t('sys.login.confirmPassword')<% } else { %>'t$t('sys.login.confirmPassword')$t$'<% } %>);
      return;
    }
    if (pwdFormData.password !== pwdFormData.confirmPassword) {
      createMessage.warn(<% if (enableTranslation) { %>t('sys.login.diffPwd')<% } else { %>'t$t('sys.login.diffPwd')$t$'<% } %>);
      return;
    }
    const resultInfo = await passwordChange(
      toRaw({
        username: accountInfo.username,
        password: pwdFormData.password,
        smscode: accountInfo.smscode,
        phone: accountInfo.phone,
      })
    );
    if (resultInfo.success) {
      accountInfo.password = pwdFormData.password;
      //修改密码
      activeKey.value = 3;
    } else {
      //错误提示
      createErrorModal({
        title:  <% if (enableTranslation) { %>t('sys.api.errorTip')<% } else { %>'t$t('sys.api.errorTip')$t$'<% } %>,
        content: resultInfo.message || <% if (enableTranslation) { %>t('sys.api.networkExceptionMsg')<% } else { %>'t$t('sys.api.networkExceptionMsg')$t$'<% } %>,
      });
    }
  }
  /**
   * 下一步
   */
  function nextStepClick() {
    if (unref(activeKey) === 1) {
      handleNext();
    } else if (unref(activeKey) === 2) {
      finishedPwd();
    }
  }

  /**
   * 去登录
   */
  function toLogin() {
    emit('success', { username: accountInfo.username, password: accountInfo.password });
    initForm();
  }

  /**
   * 返回
   */
  function goBack() {
    emit('go-back');
    initForm();
  }

  /**
   * 获取手机验证码
   */
  async function getLoginCode() {
    if (!formData.mobile) {
      createMessage.warn(<% if (enableTranslation) { %>t('sys.login.mobilePlaceholder')<% } else { %>'t$t('sys.login.mobilePlaceholder')$t$'<% } %>);
      return;
    }
    const result = await getImageCaptcha({ mobile: formData.mobile, smsmode: SmsEnum.FORGET_PASSWORD }).catch((res) =>{
      if(res.code === ExceptionEnum.PHONE_SMS_FAIL_CODE){
        openCaptchaModal(true, {});
      }
    });
    if (result) {
      const TIME_COUNT = 60;
      if (!unref(timer)) {
        timeRuning.value = TIME_COUNT;
        showInterval.value = false;
        timer.value = setInterval(() => {
          if (unref(timeRuning) > 0 && unref(timeRuning) <= TIME_COUNT) {
            timeRuning.value = timeRuning.value - 1;
          } else {
            showInterval.value = true;
            clearInterval(unref(timer));
            timer.value = null;
          }
        }, 1000);
      }
    }
  }

  /**
   * 初始化表单
   */
  function initForm() {
    activeKey.value = 1;
    Object.assign(formData, { phone: '', smscode: '' });
    Object.assign(pwdFormData, { password: '', confirmPassword: '' });
    Object.assign(accountInfo, {});
    if(unref(timer)){
      clearInterval(unref(timer));
      timer.value = null;
      showInterval.value = true;
    }
    setTimeout(()=>{
      formRef.value.resetFields();
    },300)
  }

  defineExpose({
    initForm,
  });
</script>
<style lang="less" scoped>
@import '@/assets/loginmini/style/home.less';
@import '@/assets/loginmini/style/base.less';
</style>
