import { TOKEN_NAME, APP_COOKIE } from '@/config/global';
import Cookies from 'js-cookie';
import { getConfigPolicy } from '@/utils/api/userApi';
interface MyState {
  token: String | undefined | null;
  account: number | string;
  adminConfig: string;
  uploadStrategy: any;
  options: any[];
}
// 获取cookie
const getUserCookie = () => {
  let 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(),
  account: '',
  adminConfig: '',
  uploadStrategy: {
    config: {},
  },
  options: [],
};
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, '');
    }
  },
  // 更新上传策略
  setuploadStrategy(state: StateType, config: any) {
    // 上传配置
    state.uploadStrategy.config = config.config;
  },
};

const getters = {
  token: (state: StateType) => {
    return state.token;
  },
  getuploadStrategy: (state: StateType) => {
    return state.uploadStrategy;
  },
};

const actions = {
  async AdminConfig({ commit }: any) {
    try {
      // 请求上传配置
      let result: any = await getConfigPolicy({
        // 视频上传策略
        id: 1,
      });
      if (result.code == 0) {
        commit('setuploadStrategy', {
          config: result.data,
        });
      }
    } catch (e) {
      console.log(e);
    }
  },
};

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