/**
 * @description 用户信息、登录、退出登录
 */
import $storage from '@/sheep/utils/storage';
import admin from '@/app/admin/api';
import localAdmin from '@/sheep/local-data/admin';
import { defineStore } from 'pinia';
import app from './app';

const account = defineStore({
  id: 'account',
  state: () => ({
    isLogin: !!$storage.get('token'),
    info: {
      nickname: '',
      avatar: '',
    },
    menuRules: [], // 菜单权限
    pageRules: [], // 页面权限
    apiRules: [], // 请求权限
  }),
  actions: {
    /**
     * @description 登录
     * @param {*} formData
     */
    async login(formData) {
      const response = await admin.account.login(formData);

      // 登录成功后设置 token
      if (response.code == '200' && response.data && response.data.token) {
        this.setToken(response.data.token);

        // 如果返回了用户信息，也设置到 store 中
        if (response.data) {
          this.info = response.data;
          $storage.set('userInfo', response.data);
        }
      }

      return response;
    },

    /**
     * @description 设置token
     * @param {*} token
     */
    setToken(token = '') {
      this.token = token;
      if (token == '') {
        this.isLogin = false;
        $storage.remove('token');
      } else {
        this.isLogin = true;
        $storage.set('token', token);
      }
    },

    /**
     * @description 获取用户信息
     */
    async getInfo() {
      let lastLogin = $storage.get('lastLogin');
      const userInfo = $storage.get('userInfo');
      if (lastLogin) {
        lastLogin.info = {
          avatar: userInfo.avatar,
          nickname: userInfo.name,
          account: userInfo.loginAccount,
        };
        $storage.set('lastLogin', lastLogin);
      }
      this.info = userInfo;
      return userInfo;
    },

    /**
     * @description 获取用户菜单权限规则
     */
    async getRules() {
      const { code, data } = await admin.account.queryMenu();
      if (code == 200) {
        this.menuRules = data; // 设置菜单规则
        // this.pageRules = data.permission; // 设置页面权限
        // this.apiRules = data.permission; // 设置功能权限
        return data;
      }
    },

    /**
     * @description 退出登录
     * @param force
     */
    async logout(force = false) {
      let that = this;
      // if (!force) {
      //   await admin.account.logout();
      // }
      setTimeout(function () {
        that.info = {};
        that.setToken();
        that.setRules({ menu: [], page: [], api: [] });
        app().setTaskbar({ list: [], history: [] });
        window.location = location.pathname;
      }, 0);
    },

    /**
     * @description 设置菜单规则
     * @param payload
     */
    setRules(payload) {
      this.menuRules = payload.menu; // 设置菜单规则
      this.pageRules = payload.permission; // 设置页面权限
      this.apiRules = payload.permission; // 设置功能权限
    },
  },
});

export default account;
