<template>
  <n-form
    ref="formRef"
    :show-label="false"
    :show-require-mark="false"
    size="large"
    :model="formInline"
    :rules="rules"
  >
    <n-form-item path="mobile">
      <n-input v-model:value="formInline.mobile" placeholder="请输入手机号码">
        <template #prefix>
          <n-icon size="18" color="#808695">
            <MobileOutlined />
          </n-icon>
        </template>
      </n-input>
    </n-form-item>
    <n-form-item path="code">
      <n-input
        @keyup.enter="handleSubmit"
        v-model:value.trim="formInline.code"
        placeholder="验证码"
      >
        <template #prefix>
          <n-icon size="18" color="#808695">
            <SafetyCertificateOutlined />
          </n-icon>
        </template>
        <template #suffix>
          <n-button quaternary :disabled="isGetCode" @click="getCode">
            {{ codeMsg }}<span v-if="isGetCode">s</span>
          </n-button>
        </template>
      </n-input>
    </n-form-item>
    <n-form-item :show-label="false">
      <n-button class="w-full" type="primary" @click="handleSubmit" size="large" :loading="loading">
        登录
      </n-button>
    </n-form-item>
  </n-form>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { FormRules, useMessage } from 'naive-ui';
  import { ResultEnum } from '@/enums/httpEnum';
  import { getInfoCaptcha } from '@/api/system/user';
  import { PageEnum } from '@/enums/pageEnum';
  import { MobileOutlined, SafetyCertificateOutlined } from '@vicons/antd';
  const captchaImg = ref('');
  // 动态加载滑块验证码组件

  interface FormState {
    username: string;
    password: string;
    code: string;
    key: string;
  }

  const formRef = ref();

  const loading = ref(false);
  const message = useMessage();
  const codeMsg: any = ref('获取验证码');
  const isGetCode = ref(false);
  const autoLogin = ref(true);
  const LOGIN_NAME = PageEnum.BASE_LOGIN_NAME;

  const formInline = reactive({
    mobile: '',
    code: '',
    key: '',
  });

  const rules: FormRules = {
    mobile: { key: 'a', required: true, message: '请输入手机号码', trigger: 'blur' },
    code: { required: true, message: '请输入验证码', trigger: 'blur' },
  };
  const userStore = useUserStore();

  const router = useRouter();
  const route = useRoute();
  function getCode() {
    if (!formInline.mobile) {
      formRef.value?.validate(
        (errors) => {},
        (rule) => {
          return rule?.key === 'a';
        },
      );
      return;
    }
    codeMsg.value = 60;
    isGetCode.value = true;
    let time = setInterval(() => {
      codeMsg.value--;
      if (codeMsg.value <= 0) {
        clearInterval(time);
        codeMsg.value = '获取验证码';
        isGetCode.value = false;
      }
    }, 1000);
  }
  const handleSubmit = () => {
    if (!formRef.value) return;
    formRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true;

        const params: FormState = {
          username: formInline.username,
          password: formInline.password,
          code: formInline.code,
          key: formInline.key,
        };

        try {
          const { code, msg } = await userStore.login(params);
          if (code == ResultEnum.SUCCESS) {
            const toPath = decodeURIComponent((route.query?.redirect || '/') as string);
            message.success('登录成功，即将进入系统');
            if (route.name === LOGIN_NAME) {
              router.replace('/');
            } else router.replace(toPath);
          } else {
            message.error(msg || '登录失败');
          }
        } finally {
          loading.value = false;
        }
      } else {
        message({
          message: '请填写完整信息',
          type: 'error',
        });
      }
    });
  };

  const getCaptcha = async () => {
    let { key, captcha } = await getInfoCaptcha();
    formInline.key = key;
    captchaImg.value = captcha;
  };

  getCaptcha();
</script>

<style lang="less" scoped>
  .forget {
    margin-bottom: 16px;
    margin-top: -10px;
  }
</style>
<style lang="less">
  input:-webkit-autofill,
  textarea:-webkit-autofill,
  select:-webkit-autofill {
    -webkit-box-shadow: 0 0 0px 1000px transparent inset !important;
    background-color: transparent !important;
    background-image: none;
    transition: background-color 50000s ease-in-out 0s;
  }
</style>
