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';

// 添加两个函数用于操作localStorage
const saveSelectedProjectToStorage = (project) => {
  localStorage.setItem('selectedProject', JSON.stringify(project));
};

const getSelectedProjectFromStorage = () => {
  const stored = localStorage.getItem('selectedProject');
  return stored ? JSON.parse(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 avatar = ref('');
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
  const permissions = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限

  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 [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.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;

      // **新增项目数据获取**
      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]);
        }
      }

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

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

  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;
    // 将选中的项目保存到localStorage
    saveSelectedProjectToStorage(project);

    // ** 切换项目后，需要清空当前项目下的所有缓存数据 **
    // 清空 pinia 缓存
    // store.$reset();
    // console.log("选择的新项目名称：" + selectedProject.value.name)
    // console.log("选择的新项目id：" + selectedProject.value.id)
  };

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

export default useUserStore;

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