<template>
  <div class="login" @keyup.enter="submit">
    <div class="login-spin">
      <h1>欢迎使用</h1>
      <h4>知学知考-图片导出工具</h4>
    </div>
    <div class="login-body">
      <div class="login-head">
        <div class="login-head-left">
          <h2 class="login-head-title">登录</h2>
          <h4 class="login-head-subtitle">请选择输入</h4>
        </div>
        <div class="login-head-right">
          <a-button class="login-btn btn-setting" @click="toSet">设置</a-button>
        </div>
      </div>
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :label-col-props="{ span: 0, offset: 0 }"
        :wrapper-col-props="{ span: 24, offset: 0 }"
      >
        <a-form-item field="schoolCode">
          <a-select
            v-model="formData.schoolCode"
            placeholder="请选择学校"
            name="schoolCode"
            :options="schools"
            allow-search
          >
          </a-select>
        </a-form-item>
        <a-form-item field="loginName">
          <a-input
            v-model.trim="formData.loginName"
            placeholder="请输入账号"
            name="username"
            allow-clear
          >
          </a-input>
        </a-form-item>
        <a-form-item field="password">
          <a-input-password
            v-model.trim="formData.password"
            placeholder="请输入密码"
            allow-clear
          >
          </a-input-password>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" :loading="loading" long @click="submit"
            >登录</a-button
          >
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import type { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import { login, schoolList, sysMenu } from '@/api/user';
  import { AESEncode } from '@/utils/crypto';
  import { useAppStore, useUserStore } from '@/store';
  import { UserSchoolInfoType } from '@/store/modules/user/types';
  import type { LoginData } from '@/api/types/user';
  import { FormRules, OptionListItem } from '@/types/global';
  import { objAssign } from '@/utils/utils';
  import { DEVICE_ID, PLATFORM } from '@/constants/app';

  defineOptions({
    name: 'Login',
  });

  const router = useRouter();
  const appStore = useAppStore();
  const userStore = useUserStore();
  userStore.resetInfo();

  const formRef = ref<FormInstance>();
  const formData = reactive<LoginData>({
    schoolCode: '',
    type: 'ACCOUNT',
    loginName: '',
    password: '',
    code: 'qmth',
  });

  const rules: FormRules<keyof LoginData> = {
    loginName: [
      {
        required: true,
        message: '请输入账号',
      },
    ],
    password: [
      {
        required: true,
        message: '请输入密码',
      },
    ],
    schoolCode: [
      {
        required: true,
        message: '学校编码缺失',
      },
    ],
  };

  function toSet() {
    router.push({ name: 'Setting' });
  }

  const schools = ref<OptionListItem[]>([]);
  async function getSchools() {
    if (!appStore.domain) return;
    const resData = await schoolList();
    schools.value = (resData || []).map((item) => {
      return { value: item.code, label: item.name };
    });

    formData.schoolCode = schools.value[0].value;
  }

  /* submit */
  const { loading, setLoading } = useLoading();
  async function submit() {
    const err = await formRef.value?.validate();
    if (err) return;

    setLoading(true);
    const datas = objAssign(formData, {});
    datas.password = AESEncode(formData.password);
    const data = await login(datas).catch(() => {});
    setLoading(false);
    if (!data) return;

    if (data.schoolInfo && data.schoolInfo.length) {
      const curSchool = data.schoolInfo.find(
        (item) => item.code === formData.schoolCode
      );
      data.curSchoolInfo = curSchool || ({} as UserSchoolInfoType);
    }

    userStore.setInfo({ ...data, deviceId: DEVICE_ID, platform: PLATFORM });

    const menuRes = await sysMenu();
    const validMenu = menuRes.privileges.find(
      (item) => item.url === 'ScoreManage'
    );
    if (!validMenu) {
      userStore.resetInfo();
      Message.error('您没有权限！');
      return;
    }
    data.privilegeId = validMenu.id;
    userStore.setInfo({ ...data, deviceId: DEVICE_ID, platform: PLATFORM });

    router.push({
      name: 'TrackExport',
    });
  }

  async function initData() {
    const domain = await window.db.getDict('domain');
    if (!domain) return;
    appStore.setInfo({ domain });
    await getSchools();
  }

  onMounted(() => {
    initData();
  });
</script>
