import { to } from 'await-to-js';
import { getToken, removeToken, setToken } from '@/utils/auth';
import { login as loginApi, logout as logoutApi, getInfo as getUserInfo, getUserProject } from '@/api/login';
import { LoginData, UserProject } from '@/api/types';
import defAva from '@/assets/images/profile.jpg';
import store from '@/store';
import { defineStore } from 'pinia';
import $cache from '@/plugins/cache';
// 添加两个函数用于操作localStorage
const saveSelectedProjectToStorage = (project) => {
  // localStorage.setItem('selectedProject', JSON.stringify(project));
  $cache.local.setJSON('selectedProject', project);
};

const getSelectedProjectFromStorage = () => {
  // localStorage.getItem('selectedProject');
  const stored = $cache.local.getJSON('selectedProject');
  return stored ? stored : null;
};

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 deptId = ref<string | number>('');
  const avatar = ref('');
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
  const permissions = ref<Array<any>>([]); // 用户权限编码集合 → 判断按钮权限
  const permissionList = ref<Array<any>>([]); // 用户所有权限列表
  const roleList = ref<Array<any>>([]); // 用户所有角色列表

  const projects = ref<Array<{ id: string; name: string }>>([]);
  // 从localStorage获取缓存的项目，如果没有则默认为null
  const selectedProject = ref<{ id: string; name: string } | null>(getSelectedProjectFromStorage());

  /**
   * 登录
   * @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 [projectErr, projectRes] = await to(getUserProject());
    if (projectRes?.data) {
      const projectList = projectRes.data.map((p) => ({
        id: p.projectId,
        name: p.projectName || '未知项目'
      }));

      setProjects(projectList);

      // 如果有缓存的选中项目，且该项目在当前项目列表中存在，则使用缓存的项目
      const storedProject = getSelectedProjectFromStorage();
      if (storedProject && projectList.some((p) => p.id === storedProject.id)) {
        setSelectedProject(storedProject);
      } else if (projectList.length > 0) {
        // 否则默认选择第一个项目
        setSelectedProject(projectList[0]);
      }
    }
    const [err, res] = await to(getUserInfo());
    console.log(111111111111);

    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) {
        permissionList.value = data.permissions;
        roleList.value = data.roles;
        setRoles();
      } else {
        roles.value = ['ROLE_DEFAULT'];
      }
      name.value = user.userName;
      nickname.value = user.nickName;
      avatar.value = profile;
      userId.value = user.userId;
      tenantId.value = user.tenantId;
      deptId.value = user.deptId;

      return Promise.resolve();
    }
    return Promise.reject(err);
  };

  const setInfo = async () => {
    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) {
        permissionList.value = data.permissions;
        roleList.value = data.roles;
        setRoles();
      } else {
        roles.value = ['ROLE_DEFAULT'];
      }
      name.value = user.userName;
      nickname.value = user.nickName;
      avatar.value = profile;
      userId.value = user.userId;
      tenantId.value = user.tenantId;
      deptId.value = user.deptId;
    }
  };

  const setRoles = () => {
    const projectRole = roleList.value.find((item) => item.projectId == selectedProject.value?.id)?.projectRoles || [];
    roles.value = projectRole;
    const projectPermissions = permissionList.value.find((item) => item.projectId == selectedProject.value?.id)?.projectPermissions || [];
    console.log('🚀 ~ setRoles ~ projectPermissions:', projectPermissions, permissionList.value, selectedProject.value?.id);
    permissions.value = projectPermissions;
  };

  // 注销
  const logout = async (): Promise<void> => {
    await logoutApi();
    token.value = '';
    roles.value = [];
    permissions.value = [];
    removeToken();
    // 清除项目缓存
    $cache.local.remove('selectedProject');
    $cache.local.remove('ProjectTeamList');
  };

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

  const setProjects = (projectList: Array<{ id: string; name: string }>) => {
    projects.value = projectList;
  };

  const setSelectedProject = (project: { id: string; name: string }) => {
    selectedProject.value = project;
    saveSelectedProjectToStorage(project);
  };

  return {
    userId,
    tenantId,
    deptId,
    token,
    nickname,
    avatar,
    roles,
    permissions,
    login,
    getInfo,
    logout,
    setAvatar,
    setProjects,
    setSelectedProject,
    projects,
    selectedProject,
    setInfo,
    setRoles
  };
});

export default useUserStore;

// 非 setup 方式
export function useUserStoreHook() {
  return useUserStore(store);
}
