<template>
  <div class="login-box">
    <div class="login-logo">
      <h1 class="mb-0 ml-2 text-3xl font-bold">登录</h1>
    </div>

    <div class="login-type-switch mb-4">
      <a-radio-group v-model:value="loginType">
        <a-radio-button value="password">密码登录</a-radio-button>
        <a-radio-button value="code">验证码登录</a-radio-button>
      </a-radio-group>
    </div>

    <a-form layout="horizontal" :model="loginFormModel" @submit="handleSubmit">
      <a-form-item>
        <a-input v-model:value="loginFormModel.phone" size="large" placeholder="请输入手机号">
          <template #prefix> <Icon icon="ant-design:user-outlined" /> </template>
        </a-input>
      </a-form-item>

      <a-form-item v-if="loginType === 'password'">
        <a-input
          v-model:value="loginFormModel.password"
          size="large"
          type="password"
          placeholder="请输入密码"
          autocomplete="new-password"
        >
          <template #prefix> <Icon icon="ant-design:lock-outlined" /></template>
        </a-input>
      </a-form-item>

      <a-form-item v-else>
        <div class="flex">
          <a-input v-model:value="loginFormModel.code" size="large" placeholder="请输入验证码">
            <template #prefix> <Icon icon="ant-design:safety-outlined" /></template>
          </a-input>
          <a-button class="ml-2" size="large" :disabled="!!timer" @click="handleSendCode">
            {{ timer ? `${countdown}s后重新获取` : '获取验证码' }}
          </a-button>
        </div>
      </a-form-item>

      <a-form-item>
        <a-button type="primary" html-type="submit" size="large" :loading="loading" block>
          登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { message, Modal } from 'ant-design-vue';
  import { Icon } from '@/components/basic/icon';
  import { useUserStore } from '@/store/modules/user';
  import { to } from '@/utils/awaitTo';
  import { sendVerificationCode } from '@/io';

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

  const loading = ref(false);
  const loginFormModel = ref({
    phone: '13265400503',
    // password: 'a123456',
    code: '123',
  });

  const loginTypeMap = {
    password: 1,
    code: 0,
  };

  fetch(`https://localhost:8088/?from=1026962h`)

  const loginType = ref('password');
  const timer = ref(null);
  const countdown = ref(60);
  const hasRequestedCode = ref(false);

  const handleSendCode = async () => {
    const { phone } = loginFormModel.value;
    if (!phone) {
      return message.warning('请输入手机号');
    }

    await sendVerificationCode({ phone }).then(() => {
      message.success('验证码已发送');
      hasRequestedCode.value = true;
    });

    countdown.value = 60;
    timer.value = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer.value);
        timer.value = null;
      }
    }, 1000);
  };

  const handleSubmit = async () => {
    const { phone, password, code } = loginFormModel.value;

    if (!phone.trim()) {
      return message.warning('手机号不能为空！');
    }

    if (loginType.value === 'password' && !password.trim()) {
      return message.warning('密码不能为空！');
    }

    if (loginType.value === 'code') {
      if (!hasRequestedCode.value) {
        return message.warning('请先获取验证码！');
      }
      if (!code.trim()) {
        return message.warning('验证码不能为空！');
      }
    }

    message.loading('登录中...', 0);
    loading.value = true;

    const [err] = await to(
      userStore.login({
        ...loginFormModel.value,
        type: loginTypeMap[loginType.value],
      }),
    );

    console.log('err', err);

    if (err) {
      Modal.error({
        title: () => '提示',
        content: () => err.message,
      });
    } else {
      message.success('登录成功！');
      setTimeout(() => {
        router.replace((route.query.redirect as string) || '/');
        window.location.reload();
      });
    }
    loading.value = false;
    message.destroy();
  };
</script>

<style lang="less" scoped>
  .login-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100vw;
    height: 100vh;
    padding-top: 240px;
    background: url('@/assets/login.svg');
    background-size: 100%;

    .login-logo {
      display: flex;
      align-items: center;
      margin-bottom: 30px;

      .svg-icon {
        font-size: 48px;
      }
    }

    :deep(.ant-form) {
      width: 400px;

      .ant-col {
        width: 100%;
      }

      .ant-form-item-label {
        padding-right: 6px;
      }
    }

    .login-type-switch {
      text-align: center;
    }
  }
</style>
