<!-- 账号密码登录表单 -->
<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';
import type { LoginDTO, TenantResp } from '@/api/auth/types';
import { onMounted, reactive, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { login, tenantList } from '@/api';
import { useLoginTenantId } from '@/hooks/useLoginTenantId';
import { useUserStore } from '@/stores';
import { useLoginFormStore } from '@/stores/modules/loginForm';
import { useSessionStore } from '@/stores/modules/session';

// 定义 emits
const emit = defineEmits<{
  success: [];
}>();

const userStore = useUserStore();
const sessionStore = useSessionStore();
const loginFromStore = useLoginFormStore();

// 使用全局租户ID状态
const { loginTenantId } = useLoginTenantId();

const formRef = ref<FormInstance>();

// 租户信息
const tenantInfo = ref<TenantResp>({
  tenantEnabled: false,
  voList: [],
});

const formModel = reactive<LoginDTO>({
  username: '',
  password: '',
  clientId: import.meta.env.VITE_CLIENT_ID,
  grantType: 'password',
  tenantId: loginTenantId.value, // 使用全局状态
  uuid: 'a5705def96be468f80e4b8bde3127c31',
});

const rules = reactive<FormRules<LoginDTO>>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
});

// 监听表单中的租户ID变化，同步到全局状态（添加防抖，避免循环触发）
watch(() => formModel.tenantId, (newTenantId, oldTenantId) => {
  // 仅在值真正改变时更新全局状态
  if (newTenantId !== oldTenantId && newTenantId !== loginTenantId.value) {
    console.log('租户ID变化:', oldTenantId, '->', newTenantId);
    loginTenantId.value = newTenantId || '000000';
    console.log('全局状态已同步:', loginTenantId.value);
  }
});

// 加载租户列表
async function loadTenant() {
  try {
    console.log('开始加载租户列表，当前全局租户ID:', loginTenantId.value);
    const resp = await tenantList();
    tenantInfo.value = resp;
    console.log('租户列表加载完成，启用多租户:', resp.tenantEnabled, '租户数量:', resp.voList.length);

    // 仅在全局租户ID为默认值时才设置第一个租户
    if (resp.tenantEnabled && resp.voList.length > 0 && loginTenantId.value === '000000') {
      const firstTenantId = resp.voList[0].tenantId;
      console.log('全局租户ID为默认值，设置第一个租户:', firstTenantId);
      loginTenantId.value = firstTenantId;
      formModel.tenantId = firstTenantId;
    }
    else {
      // 如果全局状态已有值，同步到表单
      console.log('使用全局租户ID:', loginTenantId.value);
      formModel.tenantId = loginTenantId.value;
    }
    console.log('最终表单租户ID:', formModel.tenantId);
  }
  catch (error) {
    console.error('加载租户列表失败:', error);
  }
}

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

const router = useRouter();
const loading = ref(false);

async function handleSubmit() {
  try {
    loading.value = true;

    // 表单验证
    await formRef.value?.validate();

    // 发起登录请求
    const res = await login(formModel);
    console.log('登录响应:', res);

    // 登录成功
    if (res.data?.access_token) {
      // 保存 token
      userStore.setToken(res.data.access_token);

      // 如果返回了用户信息，保存用户信息
      if (res.data.userInfo) {
        userStore.setUserInfo(res.data.userInfo);
      }
      else {
        // 如果登录响应没有返回用户信息，创建默认用户信息
        userStore.setUserInfo({
          userId: 1,
          username: formModel.username,
          nickName: formModel.username,
          roles: [{ roleId: 1, roleName: '企业员工', roleKey: 'employee' }],
          deptName: '企业部门',
        });
      }

      ElMessage.success('登录成功');
      userStore.closeLoginDialog();

      // 获取会话列表
      await sessionStore.requestSessionList(1, true);

      // 触发成功事件
      emit('success');

      // 跳转到首页或 redirect 页面
      const redirect = router.currentRoute.value.query.redirect as string;
      router.replace(redirect || '/');
    }
  }
  catch (error: any) {
    // 错误已经在 request.ts 的拦截器中处理并显示了
    // 这里只需要记录日志，不需要再次显示错误信息
    console.error('登录失败:', error);
  }
  finally {
    loading.value = false;
  }
}
</script>

<template>
  <div class="custom-form">
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      style="width: 230px"
      @submit.prevent="handleSubmit"
    >
      <!-- 租户选择（仅当启用多租户时显示） -->
      <el-form-item v-if="tenantInfo.tenantEnabled" prop="tenantId">
        <el-select v-model="formModel.tenantId" placeholder="请选择租户" style="width: 100%">
          <el-option
            v-for="tenant in tenantInfo.voList"
            :key="tenant.tenantId"
            :label="tenant.companyName"
            :value="tenant.tenantId"
          />
        </el-select>
      </el-form-item>

      <el-form-item prop="username">
        <el-input v-model="formModel.username" placeholder="请输入用户名">
          <template #prefix>
            <el-icon>
              <User />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="formModel.password"
          placeholder="请输入密码"
          type="password"
          show-password
        >
          <template #prefix>
            <el-icon>
              <Lock />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 100%" native-type="submit" :loading="loading">
          登录
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 注册登录 -->
    <div class="form-tip font-size-12px flex items-center">
      <span>没有账号？</span>
      <span
        class="c-[var(--el-color-primar,#409eff)] cursor-pointer"
        @click="loginFromStore.setLoginFormType('RegistrationForm')"
      >
        立即注册
      </span>
    </div>
  </div>
</template>

<style scoped lang="scss">
.custom-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.form-group {
  display: flex;
  gap: 8px;
  align-items: center;
}
.login-btn {
  padding: 12px;
  margin-top: 24px;
  color: white;
  cursor: pointer;
  background: #409eff;
  border: none;
  border-radius: 4px;
}
</style>
