<template>
  <LoginFormTitle v-show="getShow" class="enter-x" />
  <Form
    class="p-4 enter-x"
    :model="formData"
    :rules="getFormRules"
    ref="formRef"
    v-show="getShow"
    @keypress.enter="handleLogin"
    layout="vertical"
  >
    <FormItem name="username" class="enter-x">
      <Input
        size="large"
        v-model:value="formData.username"
        :placeholder="locales.login.userName"
        class="fix-auto-fill"
      />
    </FormItem>
    <FormItem name="password" class="enter-x">
      <InputPassword
        size="large"
        visibilityToggle
        v-model:value="formData.password"
        :placeholder="locales.login.password"
      />
    </FormItem>

    <Row class="enter-x" v-show="formState.showCaptcha">
      <Col span="16">
        <FormItem class="code-input" name="code" label="验证码">
          <Input
            size="large"
            visibilityToggle
            v-model:value="formData.captchaCode"
            placeholder="验证码"
          />
        </FormItem>
      </Col>
      <Col span="8">
        <img
          v-show="true"
          :src="formState.captchaSrc"
          @click="loadCaptcha"
          alt="captcha"
          class="code-image"
        />
      </Col>
    </Row>

    <Row class="enter-x" v-show="formState.showCaptcha">
      <Col span="16" />
      <!-- <Col span="8">
        <img
          v-show="true"
          :src="formState.captchaSrc"
          @click="loadCaptcha"
          alt="captcha"
          class="code-image"
        />
      </Col> -->
    </Row>

    <Row class="enter-x">
      <Col :span="12">
        <FormItem>
          <!-- No logic, you need to deal with it yourself -->
          <Checkbox v-model:checked="formState.rememberMe" size="small">
            {{ locales.login.rememberMe }}
          </Checkbox>
        </FormItem>
      </Col>
      <Col :span="12">
        <FormItem :style="{ 'text-align': 'right' }">
          <!-- No logic, you need to deal with it yourself -->
          <Button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
            {{ locales.login.forgetPassword }}
          </Button>
        </FormItem>
      </Col>
    </Row>

    <FormItem class="enter-x">
      <Button type="primary" size="large" block @click="handleLogin" :loading="formState.loading">
        {{ locales.login.loginButton }}
      </Button>
      <!-- <Button size="large" class="mt-4 enter-x" block @click="handleRegister">
        {{ locales.login.registerButton }}
      </Button> -->
    </FormItem>
  </Form>
</template>
<script lang="ts" setup>
  import { reactive, ref, unref, computed, onMounted } from 'vue';
  import { Checkbox, Form, Input, Row, Col, Button } from 'ant-design-vue';
  import LoginFormTitle from './LoginFormTitle.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { LoginStateEnum, useLoginState, useFormRules, useFormValid } from './useLogin';
  import { useDesign } from '/@/hooks/web/useDesign';
  import locales from '/@/utils/locales';
  import { buildUUID } from '/@/utils/uuid';
  import Cookies from 'js-cookie';
  import { getCaptcha } from '/@/api/sys/oauthApi';
  import { sysConfigCurrent } from '/@/api/sys/sysConfigApi';
  import { encryptByBase64, decodeByBase64 } from '/@/utils/cipher';
  import { useRoute } from 'vue-router';
  import { useGlobSetting } from '/@/hooks/setting';

  //import { onKeyStroke } from '@vueuse/core';
  onMounted(() => {
    if (Cookies.get('username') && Cookies.get('password')) {
      formData.username = decodeByBase64(Cookies.get('username')) || '';
    }
    sysConfigCurrent().then(res => {
      formState.showCaptcha = res.captchaOpen;
      if (res.captchaOpen) {
        formState.captchaSrc = getCaptcha(formData.captchaKey);
      }
    });
  });

  const FormItem = Form.Item;
  const InputPassword = Input.Password;
  const { notification, createErrorModal } = useMessage();
  const { prefixCls } = useDesign('login');
  const userStore = useUserStore();
  const { clientId, clientSecret } = useGlobSetting();

  const { setLoginState, getLoginState } = useLoginState();
  const { getFormRules } = useFormRules();

  const route = useRoute();
  const formRef = ref();
  const formData = reactive<any>({
    username: 'admin',
    password: '123456',
    captchaKey: buildUUID(),
  });

  const formState = reactive({
    captchaSrc: getCaptcha(formData.captchaKey),
    showCaptcha: true,
    rememberMe: true,
    loading: false,
  });

  const { validForm } = useFormValid(formRef);

  //onKeyStroke('Enter', handleLogin);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);

  // 加载验证码
  async function loadCaptcha() {
    formData.captchaKey = buildUUID();
    formState.captchaSrc = getCaptcha(formData.captchaKey);
  }

  async function handleLogin() {
    const data = await validForm();
    if (!data) return;
    try {
      formState.loading = true;
      const redirect = route.query?.redirect || '';
      const userInfo = await userStore.login({
        username: data.username,
        password: data.password,
        loginType: 'login', //不要默认的错误提示
        mode: 'none',
        captchaKey: formData.captchaKey,
        captchaCode: formData.captchaCode,
        grant_type: '',
        redirect,
        client_id: clientId,
        client_secret: clientSecret,
        captchaVerification: '',
      });
      if (userInfo) {
        if (formState.rememberMe) {
          Cookies.set('username', encryptByBase64(formData.username), { expires: 30 });
          Cookies.set('password', encryptByBase64(formData.password), { expires: 30 });
        }
        notification.success({
          message: locales.login.loginSuccessTitle,
          description: `${locales.login.loginSuccessDesc}: ${userInfo.nickname}`,
          duration: 3,
        });
      }
    } catch (error) {
      if (formState.showCaptcha) {
        loadCaptcha();
      }
      createErrorModal({
        title: locales.api.errorTip,
        content: (error as unknown as Error).message || locales.api.networkExceptionMsg,
        getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
      });
    } finally {
      formState.loading = false;
    }
  }
</script>

<style lang="less" scoped>
  ::v-deep(.ant-form-item-required::before) {
    content: '' !important;
  }

  ::v-deep(.ant-input) {
    border: 0;
    background-color: #eef1f7 !important;
  }

  ::v-deep(.ant-form-item-label > label) {
    font-weight: 700;
  }

  ::v-deep(.ant-input-affix-wrapper) {
    border: 0;
    background-color: #eef1f7 !important;
    height: 42px;
  }

  ::v-deep(.code-input .ant-input) {
    min-width: 120px !important;
    max-width: 260px;
  }

  ::v-deep(input:-webkit-autofill) {
    box-shadow: none !important;
  }

  input[type='text'] {
    height: 42px;
  }

  .code-image {
    width: 100%;
    height: 42px;
    margin-top: 30px;
  }

  .btn-login {
    font-size: 18px;
    height: 44px;
  }
</style>
