<template>
  <CommonRoot>
    <FlexCol gap="gap.xl" padding="space.lg">
      <FlexCol center>
        <Text fontConfig="subText">欢迎使用闽南文化数字资源采集</Text>
        <Text fontConfig="subText">技术支持：18649931391</Text>
      </FlexCol>
      <FlexCol position="relative" radius="radius.md" backgroundColor="white" overflow="hidden">
        <LoadingPage :loading="loading" loadingText="登录中..." />
        <DynamicForm
          ref="formRef"
          :model="formModel"
          :options="formDefine"
        />
      </FlexCol>
      <FlexCol gap="gap.md">
        <Button type="primary" block :loading="loading" @click="handleSubmit">
          登录
        </Button>
        <Button block @click="back()">
          返回
        </Button>
      </FlexCol>
      <XBarSpace />
    </FlexCol>
  </CommonRoot>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useAuthStore } from '@/store/auth';
import { showError } from '@/common/composeabe/ErrorDisplay';
import { waitTimeOut } from '@imengyu/imengyu-utils';
import { confirm, toast } from '@/components/dialog/CommonRoot';
import { back, redirectTo } from '@/components/utils/PageAction';
import Button from '@/components/basic/Button.vue';
import XBarSpace from '@/components/layout/space/XBarSpace.vue';
import DynamicForm from '@/components/dynamic/DynamicForm.vue';
import type { IDynamicFormOptions, IDynamicFormRef } from '@/components/dynamic';
import type { FormProps } from '@/components/form/Form.vue';
import type { RadioValueProps } from '@/components/dynamic/wrappers/RadioValue';
import FlexCol from '@/components/layout/FlexCol.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import Text from '@/components/basic/Text.vue';
import LoadingPage from '@/components/display/loading/LoadingPage.vue';
import MemoryTimeOut from '@/components/composeabe/MemoryTimeOut';
import CommonRoot from '@/components/dialog/CommonRoot.vue';

const authStore = useAuthStore();
const formRef = ref<IDynamicFormRef>();
const loading = ref(true);

const formModel = ref({
  mobile: '',
  account: '',
  password: '',
  type: 0,
});

const formDefine: IDynamicFormOptions = {
  formAdditionaProps: {
    labelFlex: 4,
    inputFlex: 8,
  } as FormProps,
  formRules: {
    mobile: [{ required: true, message: '请输入账号' }],
    account: [{ required: true, message: '请输入账号' }],
    password: [{ required: true, message: '请输入密码' }],
  },
  formItems: [
    {
      label: '账号',
      name: 'mobile',
      type: 'text',
      defaultValue: '',
      show: { callback: (_, m) => (m as { type: number }).type === 0 },
      additionalProps: {
        placeholder: '请输入账号',
      },
    },
    {
      label: '账号',
      name: 'account',
      type: 'text',
      defaultValue: '',
      show: { callback: (_, m) => (m as { type: number }).type === 1 },
      additionalProps: {
        placeholder: '请输入账号',
      },
    },
    {
      label: '密码',
      name: 'password',
      type: 'text',
      defaultValue: '',
      formProps: {
        type: 'password',
      },
      additionalProps: {
        placeholder: '请输入密码',
      },
    },
    {
      label: '登录类型',
      name: 'type',
      type: 'radio-value',
      defaultValue: 0,
      additionalProps: {
        options: [
          { text: '传承人', value: 0 },
          { text: '管理员/保护单位', value: 1 },
        ],
      } as RadioValueProps,
    },
  ],
};

const tipBindWechat = new MemoryTimeOut('TipBindWechat', 1000 * 3600 * 72);

async function handleSubmit() {
  if (!formRef.value)
    return;
  try {
    await formRef.value.validate();
  } catch {
    toast({
      content: '有必填项未填写，请检查',
    });
    return;
  }

  const loginType = Number(formModel.value.type);
  const account =
    loginType === 1
      ? formModel.value.account.trim()
      : formModel.value.mobile.trim();
  if (!account) {
    toast({
      content: '请输入账号',
    });
    return;
  }

  loading.value = true;
  try {
    await authStore.loginCollect(account, formModel.value.password, loginType);
    toast('您已成功登录');
    await new Promise((r) => setTimeout(r, 200));

    let nextPage = '';
    if (authStore.loginType === 0) {
      nextPage = '/pages/collect/inheritor';
    } else if (authStore.loginType === 1) {
      nextPage = '/pages/collect/admin';
    }

    //如果用户未绑定微信，提示用户绑定微信
    if (!authStore.userInfo?.openId && !authStore.isLoginMp && tipBindWechat.isTimeout()) {
      tipBindWechat.recordTime();

      if (await confirm({
        title: '提示',
        content: '绑定微信账号后登录更方便，是否前往绑定？',
        confirmText: '前往绑定',
        cancelText: '稍后绑定',
        width: 580,
      })) {
        redirectTo('bind-wx', {
          nextPage
        });
        return;
      }
    }
    redirectTo(nextPage);
  } catch (e) {
    showError(e);
  } finally {
    loading.value = false;
  }
}

onMounted(async () => {
  await waitTimeOut(1000);
  if (authStore.isLogged) {
    console.log(authStore.loginType);
    if (authStore.isCollect) {
      redirectTo('/pages/collect/inheritor');
    } else if (authStore.isCollectReviewer || authStore.isCollectAdmin) {
      redirectTo('/pages/collect/admin');
    }
  }
  loading.value = false;
});
</script>

<style lang="scss">
</style>
