<template>
  <n-form
    ref="formRef"
    :show-label="false"
    :show-require-mark="false"
    size="large"
    :model="formInline"
    :rules="rules"
  >
    <n-form-item path="username">
      <n-input v-model:value="formInline.username" placeholder="请输入登录账号">
        <template #prefix>
          <n-icon size="18" color="#808695">
            <UserOutlined />
          </n-icon>
        </template>
      </n-input>
    </n-form-item>
    <n-form-item path="password">
      <n-input
        v-model:value="formInline.password"
        show-password-on="mousedown"
        type="password"
        placeholder="请输入登录密码"
        @keyup.enter="handleSubmit"
      >
        <template #prefix>
          <n-icon size="18" color="#808695">
            <LockOutlined />
          </n-icon>
        </template>
      </n-input>
    </n-form-item>
    <n-form-item path="code">
      <div style="display: flex">
        <n-input
          @keyup.enter="handleSubmit"
          v-model:value.trim="formInline.code"
          placeholder="验证码"
        >
          <template #prefix>
            <n-icon size="18" color="#808695">
              <SafetyCertificateOutlined />
            </n-icon>
          </template>
        </n-input>
        <img
          style="
            width: 108px;
            height: 40px;
            border-radius: 4px;
            margin-left: 8px;
            border: 1px solid #d9d9d9;
            cursor: pointer;
          "
          @click="getCaptcha"
          v-if="captchaImg"
          :src="captchaImg"
        />
      </div>
    </n-form-item>

    <div class="flex items-center justify-between forget">
      <div class="flex-initial">
        <n-checkbox v-model:value:checked="autoLogin">记住密码</n-checkbox>
      </div>
    </div>

    <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>
  <div class="flex items-center justify-between">
    <div class="flex items-center">
      <span>其他登录方式</span>
      <n-icon size="20" color="#1890ff" style="cursor: pointer">
        <GithubOutlined />
      </n-icon>
      <n-icon size="20" color="#1890ff" style="cursor: pointer">
        <AlipayCircleOutlined />
      </n-icon>
    </div>
    <div style="cursor: pointer" @click="goRegister">注册账号</div>
  </div>
</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 {
    UserOutlined,
    LockOutlined,
    SafetyCertificateOutlined,
    GithubOutlined,
    AlipayCircleOutlined,
  } from '@vicons/antd';
  const captchaImg = ref('');
  // 动态加载滑块验证码组件

  interface FormState {
    username: string;
    password: string;
    code: string;
    key: string;
  }
  const message = useMessage();
  const emit = defineEmits(['backLogin']);
  const formRef = ref();

  const loading = ref(false);
  const autoLogin = ref(true);
  const LOGIN_NAME = PageEnum.BASE_LOGIN_NAME;

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

  const rules: FormRules = {
    username: { required: true, message: '请输入登录账号', trigger: 'blur' },
    password: { required: true, message: '请输入密码', trigger: 'blur' },
    code: { required: true, message: '请输入验证码', trigger: 'blur' },
  };
  const userStore = useUserStore();

  const router = useRouter();
  const route = useRoute();

  const handleSubmit = () => {
    if (!formRef.value) return;
    formRef.value
      .validate()
      .then(async () => {
        loading.value = true;

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

        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 {
            getCaptcha();
            message.error(msg || '登录失败');
          }
        } finally {
          loading.value = false;
        }
      })
      .catch((error) => {
        message.error('请填写完整信息');
      });
  };

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

  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>
