import { to } from 'await-to-js';
import { getToken, removeToken, setToken } from '@/utils/auth';
import { login as loginApi, logout as logoutApi, getInfo as getUserInfo } from '@/api/login';
import { LoginData } from '@/api/types';
import defAva from '@/assets/images/profile.jpg';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { getSupplierContactlistById } from '@/api/supplier/contact';
import type { ContactVO } from '@/api/supplier/contact/types';

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken());
  const name = ref('');
  const nickname = ref('');
  const userId = ref<string | number>('');
  const tenantId = ref<string>('');
  const avatar = ref('');
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
  const permissions = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限
  
  // 供应商相关信息
  const supplierId = ref<string | number | null>(null); // 当前用户所属的供应商ID
  const supplierNo = ref<string>(''); // 供应商编号
  const contactInfo = ref<ContactVO | null>(null); // 当前用户的联系人完整信息

  /**
   * 登录
   * @param userInfo
   * @returns
   */
  const login = async (userInfo: LoginData): Promise<void> => {
    const [err, res] = await to(loginApi(userInfo));
    if (res) {
      const data = res.data;
      setToken(data.access_token);
      token.value = data.access_token;
      return Promise.resolve();
    }
    return Promise.reject(err);
  };

  // 获取用户信息
  const getInfo = async (): Promise<void> => {
    const [err, res] = await to(getUserInfo());
    if (res) {
      const data = res.data;
      const user = data.user;
      const profile = user.avatar == '' || user.avatar == null ? defAva : user.avatar;

      if (data.roles && data.roles.length > 0) {
        // 验证返回的roles是否是一个非空数组
        roles.value = data.roles;
        permissions.value = data.permissions;
      } else {
        roles.value = ['ROLE_DEFAULT'];
      }
      name.value = user.userName;
      nickname.value = user.nickName;
      avatar.value = profile;
      userId.value = user.userId;
      tenantId.value = user.tenantId;
      
      // 获取用户信息后，立即获取供应商信息
      await getSupplierInfo();
      
      return Promise.resolve();
    }
    return Promise.reject(err);
  };

  // 获取当前用户的供应商信息
  const getSupplierInfo = async (): Promise<void> => {
    try {
      if (!userId.value) {
        console.warn('userId 为空，无法获取供应商信息');
        return;
      }

      console.log('=== 开始获取供应商信息 ===');
      console.log('当前用户ID:', userId.value);

      // 通过 userId 查询联系人信息
      const res = await getSupplierContactlistById({
        userId: userId.value,
        pageNum: 1,
        pageSize: 1
      });

      console.log('getSupplierContactlistById 返回结果:', res.rows[0]);

      if (res.rows && res.rows.length > 0) {
        const contact = res.rows[0];
        contactInfo.value = contact;
        supplierId.value = contact.supplierId || null;
        supplierNo.value = contact.supplierNo || '';

        console.log('✓ 成功获取供应商信息');
        console.log('供应商ID:', supplierId.value);
        console.log('供应商编号:', supplierNo.value);
        console.log('联系人信息:', contactInfo.value);
      } else {
        console.warn('未找到当前用户的联系人信息');
        supplierId.value = null;
        supplierNo.value = '';
        contactInfo.value = null;
      }
    } catch (error) {
      console.error('获取供应商信息失败:', error);
      supplierId.value = null;
      supplierNo.value = '';
      contactInfo.value = null;
    }
  };

  // 注销
  const logout = async (): Promise<void> => {
    await logoutApi();
    token.value = '';
    roles.value = [];
    permissions.value = [];
    supplierId.value = null;
    supplierNo.value = '';
    contactInfo.value = null;
    removeToken();
  };

  const setAvatar = (value: string) => {
    avatar.value = value;
  };

  return {
    userId,
    tenantId,
    token,
    nickname,
    avatar,
    roles,
    permissions,
    supplierId,
    supplierNo,
    contactInfo,
    login,
    getInfo,
    getSupplierInfo,
    logout,
    setAvatar
  };
});
