import { defineStore } from "pinia";
import {
  type userType,
  store,
  router,
  resetRouter,
  routerArrays,
  storageLocal
} from "../utils";
import {
  type UserResult,
  getLogin,
  getProfile,
  getDictList
} from "@/api/user";
import { useMultiTagsStoreHook } from "./multiTags";
import { type DataInfo, setToken, removeToken, userKey } from "@/utils/auth";
import Cookies from "js-cookie";

// 简单的 Session 存储
const Session = {
  set: (key: string, value: any) => {
    sessionStorage.setItem(key, JSON.stringify(value));
  },
  get: (key: string) => {
    const value = sessionStorage.getItem(key);
    return value ? JSON.parse(value) : null;
  },
  clear: () => {
    sessionStorage.clear();
  }
};

export const useUserStore = defineStore("pure-user", {
  state: (): userType => ({
    // 头像
    avatar: storageLocal().getItem<DataInfo<number>>(userKey)?.avatar ?? "",
    // 用户名
    username: storageLocal().getItem<DataInfo<number>>(userKey)?.username ?? "",
    // 昵称
    nickname: storageLocal().getItem<DataInfo<number>>(userKey)?.nickname ?? "",
    // 页面级别权限
    roles: storageLocal().getItem<DataInfo<number>>(userKey)?.roles ?? [],
    // 按钮级别权限
    permissions:
      storageLocal().getItem<DataInfo<number>>(userKey)?.permissions ?? [],
    // 前端生成的验证码（按实际需求替换）
    verifyCode: "",
    // 判断登录页面显示哪个组件（0：登录（默认）、1：手机登录、2：二维码登录、3：注册、4：忘记密码）
    currentPage: 0,
    // 是否勾选了登录页的免登录
    isRemembered: false,
    // 登录页的免登录存储几天，默认7天
    loginDay: 7
  }),
  actions: {
    /** 存储头像 */
    SET_AVATAR(avatar: string) {
      this.avatar = avatar;
    },
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储昵称 */
    SET_NICKNAME(nickname: string) {
      this.nickname = nickname;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    /** 存储按钮级别权限 */
    SET_PERMS(permissions: Array<string>) {
      this.permissions = permissions;
    },
    /** 存储前端生成的验证码 */
    SET_VERIFYCODE(verifyCode: string) {
      this.verifyCode = verifyCode;
    },
    /** 存储登录页面显示哪个组件 */
    SET_CURRENTPAGE(value: number) {
      this.currentPage = value;
    },
    /** 存储是否勾选了登录页的免登录 */
    SET_ISREMEMBERED(bool: boolean) {
      this.isRemembered = bool;
    },
    /** 设置登录页的免登录存储几天 */
    SET_LOGINDAY(value: number) {
      this.loginDay = Number(value);
    },
    /** 登入 */
    async loginByUsername(data) {
      return new Promise<UserResult>((resolve, reject) => {
        getLogin(data)
          .then((res: any) => {
            // 兼容多种返回格式：
            // 1. {code: 200, data: {accessToken: 'xxx'}}
            // 2. {code: 200, message: 'ok', data: {id: 1, accessToken: 'xxx'}}
            // 3. {accessToken: 'xxx'} (直接返回)
            let loginData;
            if (res?.data?.accessToken) {
              loginData = res.data;
            } else if (res?.accessToken) {
              loginData = res;
            } else {
              loginData = res?.data || res;
            }
                    
            if (loginData?.accessToken) {
              // 先设置 token，这样后续请求才能携带正确的认证信息
              setToken({
                accessToken: loginData.accessToken,
                refreshToken: '',
                expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
                username: '',
                nickname: '',
                avatar: '',
                roles: [],
                permissions: []
              });
                  
              // 获取用户信息
              getProfile().then((profileRes: any) => {
                const userList = profileRes?.data || profileRes;
                if (userList && userList[0]) {
                  const user = userList[0];
                  const perms = typeof user.permissions === 'string' 
                    ? user.permissions.split(',').filter((p: string) => p.trim())
                    : (user.permissions || []);
                  const roles = user.roles ? [user.roles] : [];
                          
                  // 更新用户信息
                  setToken({
                    accessToken: loginData.accessToken,
                    refreshToken: '',
                    expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
                    username: user.username,
                    nickname: user.nickname || user.username,
                    avatar: user.avatar || '',
                    roles: roles,
                    permissions: perms
                  });
                          
                  this.SET_USERNAME(user.username);
                  this.SET_AVATAR(user.avatar || '');
                  this.SET_NICKNAME(user.nickname || user.username);
                  this.SET_ROLES(roles);
                  this.SET_PERMS(perms);
                }
                        
                // 获取字典数据
                getDictList().then((dictRes: any) => {
                  const dictList = dictRes?.data || dictRes;
                  if (dictList && Array.isArray(dictList)) {
                    const dictGroup = {};
                    dictList.forEach(item => {
                      if (!dictGroup[item.code]) {
                        dictGroup[item.code] = [];
                      }
                      dictGroup[item.code].push(item);
                    });
                    Session.set('dicts', dictGroup);
                  }
                }).catch((dictErr) => {
                  console.warn('字典加载失败，但不影响登录:', dictErr);
                });
                        
                resolve({ ...loginData, success: true });
              }).catch((err) => {
                reject(err);
              });
            } else {
              reject(new Error(res?.msg || res?.message || '登录失败'));
            }
          })
          .catch(error => {
            console.error('登录请求失败:', error);
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.username = "";
      this.roles = [];
      this.permissions = [];
      removeToken();
      Session.clear();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      router.push("/login");
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
