<script lang="ts" setup>
import { computed, reactive, ref, unref } from 'vue'
import { Form, Input } from 'ant-design-vue'
import { useAsyncState } from '@vueuse/core'
import CryptoJS from 'crypto-js'
import { LoadingOutlined } from '@ant-design/icons-vue'
import LoginFormTitle from './LoginFormTitle.vue'
import { LoginStateEnum, useFormRules, useFormValid, useLoginState } from './useLogin'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { useUserStore } from '@/store/modules/user'
import { useDesign } from '@/hooks/web/useDesign'
import { getLoginCaptcha } from '@/api/base/user'
import type { LoginParams } from '@/api/base/user/types'

const FormItem = Form.Item
const InputPassword = Input.Password

const { t } = useI18n()
const { notification, createErrorModal } = useMessage()
const { prefixCls } = useDesign('login')
const userStore = useUserStore()

const { getLoginState } = useLoginState()
const { getFormRules } = useFormRules()

const formRef = ref()
const loading = ref(false)

const formData = reactive<LoginParams>({
  tenantId: '345618',
  username: 'admin',
  password: '&demo8&!',
  captchaKey: '',
  captchaCode: '',
})

const { validForm } = useFormValid(formRef)
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)

async function handleLogin() {
  const data = await validForm()
  if (!data)
    return
  try {
    loading.value = true
    const userInfo = await userStore.login({
      ...formData,
      captchaKey: captcha.value!.key,
      password: CryptoJS.MD5(formData.password).toString(),
      mode: 'none',
    })
    if (userInfo) {
      notification.success({
        message: t('sys.login.loginSuccessTitle'),
        description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.user.real_name}`,
        duration: 3,
      })
    }
  }
  catch (error) {
    refreshCaptcha()
    createErrorModal({
      title: t('sys.api.errorTip'),
      content: (error as unknown as Error).message || t('sys.api.networkExceptionMsg'),
      getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
    })
  }
  finally {
    loading.value = false
  }
}

const { state: captcha, execute: refreshCaptcha, isLoading: isLoadingCaptcha } = useAsyncState(getLoginCaptcha, undefined)
</script>

<template>
  <LoginFormTitle v-show="getShow" class="enter-x" />
  <Form
    v-show="getShow" ref="formRef" class="enter-x p-4" :model="formData" :rules="getFormRules"
    @keypress.enter="handleLogin"
  >
    <FormItem name="tenantId" class="enter-x">
      <Input v-model:value="formData.tenantId" size="large" placeholder="租户编码" class="fix-auto-fill" />
    </FormItem>
    <FormItem name="username" class="enter-x">
      <Input
        v-model:value="formData.username" size="large" :placeholder="t('sys.login.userName')"
        class="fix-auto-fill"
      />
    </FormItem>
    <FormItem name="password" class="enter-x">
      <InputPassword
        v-model:value="formData.password"
        size="large"
        visibility-toggle
        :placeholder="t('sys.login.password')"
        class="fix-auto-fill"
      />
    </FormItem>
    <FormItem>
      <div flex="~ justify-between items-center gap-12px">
        <Input v-model:value="formData.captchaCode" size="large" placeholder="验证码" class="fix-auto-fill w-0 flex-1 min-w-auto!" />
        <div w="100px" text="center">
          <LoadingOutlined v-if="isLoadingCaptcha" />
          <img v-else w-full :src="captcha?.image" @click="refreshCaptcha()">
        </div>
      </div>
    </FormItem>

    <FormItem class="enter-x">
      <a-button type="primary" size="large" block :loading="loading" @click="handleLogin">
        {{ t('sys.login.loginButton') }}
      </a-button>
    </FormItem>
  </Form>
</template>
