import Cookies from 'js-cookie'
import { getConfigKey, getConfigByKeys } from "@/api/system/config";
const state = {
  sidebar: {
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false,
    hide: false
  },
  device: 'desktop',
  size: Cookies.get('size') || 'medium',
  language: Cookies.get('language') || 'en'
}

const mutations = {
  TOGGLE_SIDEBAR: state => {
    if (state.sidebar.hide) {
      return false;
    }
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  SET_SIZE: (state, size) => {
    state.size = size
    Cookies.set('size', size)
  },
  SET_SIDEBAR_HIDE: (state, status) => {
    state.sidebar.hide = status
  },
  SET_SYSTEM_PARAMS: (state, systemParams) => {
    state.systemParams = systemParams
  },
  SET_LANGUAGE: (state, language) => {
    state.language = language
    Cookies.set('language', language)
  }
}

const actions = {
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  setSize({ commit }, size) {
    commit('SET_SIZE', size)
  },
  toggleSideBarHide({ commit }, status) {
    commit('SET_SIDEBAR_HIDE', status)
  },
  // 获取系统参数配置
  getSystemParams({ commit }) {
    return new Promise((resolve) => {
      getConfigByKeys(["EXTRANET_ADDRESS", "EXTRANET_FTP_VIEW_ADDRESS", "INTRANET_FTP_VIEW_ADDRESS", "VIRTUAL_RTC_MEDIAURL", "EXTRANET_MEDIA_URL", "INTRANET_MEDIA_URL", "VIRTUAL_FLV_MEDIAURL", "INTRANET_FLV_MEDIA_URL", "EXTRANET_FLV_MEDIA_URL"]).then((res) => {
        const systemParams = {}
        res.data.forEach((x) => {
          systemParams[x.configKey] = x.configValue;
        });
        systemParams.PREFIX = location.hostname === systemParams.EXTRANET_ADDRESS ? 'EXTRANET' : 'INTRANET';
        systemParams.ftpViewAddress = systemParams[systemParams.PREFIX + '_FTP_VIEW_ADDRESS']
        systemParams.MEDIA_URL = systemParams[systemParams.PREFIX + '_MEDIA_URL']
        systemParams.FLV_MEDIA_URL = systemParams[systemParams.PREFIX + '_FLV_MEDIA_URL']
        commit("SET_SYSTEM_PARAMS", systemParams)
      });
      resolve()
    })
  },
  setLanguage({ commit }, language) {
    commit('SET_LANGUAGE', language)
  }
}

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