<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';

import type { TenantResp } from '#/api/core/auth';

import { computed, markRaw, onMounted, ref, useTemplateRef } from 'vue';

import { AuthenticationLogin, SliderCaptcha, z } from '@vben/common-ui';

import { tenantList } from '#/api/core/auth';
import { useAuthStore } from '#/store';

import { useLoginTenantId } from '../oauth-common';

defineOptions({ name: 'Login' });

const authStore = useAuthStore();
const loginFormRef = useTemplateRef('loginFormRef');
const DEFAULT_TENANT_ID = '1';
const { loginTenantId } = useLoginTenantId();

const tenantInfo = ref<TenantResp>({
  tenantEnabled: false,
  tenantVoList: [],
});

async function loadTenant() {
  const resp = await tenantList();
  tenantInfo.value = resp;
  // 选中第一个租户
  if (resp.tenantEnabled && resp.tenantVoList.length > 0) {
    const firstTenantId = resp.tenantVoList[0]!.tenantId;
    loginFormRef.value?.getFormApi().setFieldValue('tenantId', firstTenantId);
  }
}

onMounted(async () => {
  await loadTenant();
});

const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenSelect',
      componentProps: {
        options: tenantInfo.value.tenantVoList?.map((item) => ({
          label: item.companyName,
          value: item.tenantId,
        })),
        placeholder: '请选择公司',
      },
      defaultValue: DEFAULT_TENANT_ID,
      dependencies: {
        if: () => tenantInfo.value.tenantEnabled,
        // 可以把这里当做watch
        trigger: (model) => {
          // 给oauth登录使用
          loginTenantId.value = model?.tenantId ?? DEFAULT_TENANT_ID;
        },
        triggerFields: ['', 'tenantId'],
      },
      fieldName: 'tenantId',
      label: '选择公司',
      rules: z.string().min(1, { message: '选择公司' }).optional(),
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '请输入用户名',
      },
      defaultValue: 'admin',
      fieldName: 'username',
      label: '账号',
      rules: z.string().min(1, { message: '请输入用户名' }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: '密码',
      },
      defaultValue: '111111',
      fieldName: 'password',
      label: '密码',
      rules: z.string().min(5, { message: '请输入密码' }),
    },
    {
      component: markRaw(SliderCaptcha),
      fieldName: 'captcha',
      rules: z.boolean().refine((value) => value, {
        message: '请先完成验证',
      }),
    },
  ];
});
</script>

<template>
  <AuthenticationLogin
    ref="loginFormRef"
    :form-schema="formSchema"
    :loading="authStore.loginLoading"
    @submit="authStore.authLogin"
  />
</template>
