<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"
  >
    <FormItem name="account" class="enter-x">
      <Input
        size="large"
        v-model:value="formData.account"
        :placeholder="t('sys.login.userName')"
        class="fix-auto-fill"
      />
    </FormItem>
    <FormItem name="password" class="enter-x">
      <InputPassword
        size="large"
        visibilityToggle
        v-model:value="formData.password"
        :placeholder="t('sys.login.password')"
      />
    </FormItem>

    <ARow class="enter-x">
      <ACol :span="12">
        <FormItem>
          <Checkbox v-model:checked="rememberMe" size="small">
            {{ t('sys.login.rememberMe') }}
          </Checkbox>
        </FormItem>
      </ACol>
      <ACol :span="12">
        <FormItem style="text-align: right">
          <Button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
            {{ t('sys.login.forgetPassword') }}
          </Button>
        </FormItem>
      </ACol>
    </ARow>

    <FormItem class="enter-x">
      <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
        {{ t('sys.login.loginButton') }}
      </Button>
    </FormItem>
    <ARow class="enter-x flex justify-between">
      <ACol :md="11" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.LOGIN)">
          {{ t('sys.login.userNameInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="11" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.MOBILE)">
          {{ t('sys.login.mobileSignInFormTitle') }}
        </Button>
      </ACol>
    </ARow>
  </Form>
</template>
<script lang="ts" setup>
  import { reactive, ref, unref, computed } from 'vue';
  import { Checkbox, Form, Input, Row, Col, Button } from 'ant-design-vue';
  import LoginFormTitle from './LoginFormTitle.vue';

  import { useI18n } from '/@/hooks/web/useI18n';
  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 { getPlatForm } from '/@/api/oem';
  import { createLocalStorage, createSessionStorage } from '/@/utils/cache';

  const ACol = Col;
  const ARow = Row;
  const FormItem = Form.Item;
  const InputPassword = Input.Password;
  const { t } = useI18n();
  const { notification, createMessage } = useMessage();
  const { prefixCls } = useDesign('login');
  const userStore = useUserStore();

  const { setLoginState, getLoginState } = useLoginState();
  const { getFormRules } = useFormRules();
  const storage = createLocalStorage();
  const sStorage = createSessionStorage();
  const formRef = ref();
  const loading = ref(false);
  const rememberMe = ref(false);
  const userInfo = storage.get('userInfo') || sStorage.get('userInfo');
  const formData = reactive({
    account: userInfo?.account ?? 'sysadmin',
    password: userInfo?.password ?? 'Sysadmin@123',
  });

  const { validForm } = useFormValid(formRef);

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

  async function handleLogin() {
    const data = await validForm();
    if (!data) return;
    if (unref(rememberMe)) {
      storage.set('userInfo', formData);
      sStorage.set('userInfo', formData);
    } else {
      storage.set('userInfo', null);
      sStorage.set('userInfo', null);
    }
    loading.value = true;
    const userInfo = await userStore
      .login({
        password: data.password,
        username: data.account,
        mode: 'modal', //不要默认的错误提示
      })
      .catch((data) => {
        //登录失败如果是502，返回的html,那么提示框什么都没有
        if (data.message == 'Invalid username or password' && typeof data.message == 'string') {
          createMessage.error(data.message);
        } else if (data.message == '账号已过期,请联系管理员') {
          createMessage.error(data.message);
        } else {
          createMessage.error(data.message);
        }
      });
    if (userInfo) {
      notification.success({
        message: t('sys.login.loginSuccessTitle'),
        description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.realName}`,
        duration: 3,
      });
      const res = await getPlatForm();
      storage.set('platformInfo', res);
      userStore.setPlatInfo(res);
      // 设置icon
      let link = (document.querySelector("link[rel*='icon']") ||
        document.createElement('link')) as HTMLLinkElement;
      link.type = 'image/x-icon';
      link.rel = 'shortcut icon';
      link.href = res.icon ?? '/favicon.ico';
      document.getElementsByTagName('head')[0].appendChild(link);

      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement('script');
        hm.src = 'https://hm.baidu.com/hm.js?909f8e22a361b08e4f5ea3918500aede';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(hm, s);
      })();
    }
    loading.value = false;
  }
</script>
