import { TOKEN_NAME, APP_COOKIE } from '@/config/global';
import Cookies from 'js-cookie';
import { getConfigPolicy, useLogout, getUserInfo } from '@/utils/api/userApi';
import { show_message } from '@/utils/tdesign_tool';

interface MyState {
  token: string | undefined | null;
  userInfo: any;
  uploadStrategy: any;
}
// 获取cookie
const getUserCookie = () => {
  const mode = import.meta.env.MODE;
  if (mode == 'app') {
    // 从本地取
    return window.localStorage.getItem(APP_COOKIE);
  } else {
    return Cookies.get(TOKEN_NAME);
  }
};
// 定义的state初始值
const state: MyState = {
  token: getUserCookie(),
  userInfo: {},
  uploadStrategy: {
    config: {},
  },
};
type StateType = typeof state;

const mutations = {
  setToken(state: StateType, obj: any) {
    Cookies.set(TOKEN_NAME, obj.token, {
      expires: obj.time / 60 / 60 / 24,
    });
    // app版
    if (import.meta.env.MODE == 'app') {
      window.localStorage.setItem(APP_COOKIE, obj.token);
    }
    state.token = obj.token;
  },
  removeToken(state: StateType) {
    Cookies.remove(TOKEN_NAME);
    state.token = '';
    // app版
    if (import.meta.env.MODE == 'app') {
      window.localStorage.setItem(APP_COOKIE, '');
    }
  },
  // 更新用户信息
  setUserInfo(state: StateType, info: any) {
    state.userInfo = info;
  },
  // 清空用户信息
  removeUserInfo(state: StateType) {
    state.userInfo = {};
  },

  // 更新上传策略
  setuploadStrategy(state: StateType, config: any) {
    // 上传配置
    state.uploadStrategy.config = config.config;
  },
};

const getters = {
  token: (state: StateType) => {
    return state.token;
  },
  // 获取用户信息
  userInfo: (state: StateType) => {
    return state.userInfo;
  },
  getuploadStrategy: (state: StateType) => {
    return state.uploadStrategy;
  },
};

const actions = {
  // 获取用户信息
  async UserInfo({ commit, state }: any) {
    if (state.token) {
      try {
        const result: any = await getUserInfo();
        if (result.code == 0) {
          commit('setUserInfo', result.data);
        }
      } catch (e) {
        console.log(e);
      }
    }
  },
  async AdminConfig({ commit }: any) {
    try {
      // 请求上传配置
      const result: any = await getConfigPolicy({
        // 视频上传策略
        id: 1,
      });
      if (result.code == 0) {
        commit('setuploadStrategy', {
          config: result.data,
        });
      }
    } catch (e) {
      console.log(e);
    }
  },
  // 退出登录
  async Logout({ commit }: any) {
    try {
      await useLogout();
      commit('removeToken');
      // 清空用户信息
      commit('removeUserInfo');
      show_message('退出成功', 'success');
      return true;
    } catch (e) {
      console.log(e);
      return false;
    }
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
