import { SETTING_KEY } from "common/storage"
import { SIDER_BREAK_POINT } from "util/global"

const defaultState = {
    siderCollapsed: false,
    allowSiderCollapsed: true,
    theme: 'default'
}

const localStorageState = () => {
    return JSON.parse(window.localStorage.getItem(SETTING_KEY)) || {}
}

const mergeState = {
    ...defaultState,
    ...localStorageState()
}

const layout = (state = mergeState, action) => {
    switch (action.type) {
        // 打开窗口
        case 'OPEN_WINDOW':
            return state
        // 关闭窗口
        case 'CLOSE_WINDOW':
            return state
        // 重新加载窗口
        case 'RELOAD_WINDOW':
            return state
        // 侧边收起状态
        case 'TOGGLE_COLLAPSED':
            {
                if (window.innerWidth <= SIDER_BREAK_POINT) {
                    return state
                }
                const _state = { ...state, siderCollapsed: action.siderCollapsed }
                window.localStorage.setItem(SETTING_KEY, JSON.stringify(_state))
                return _state
            }
        // 自动收起侧边
        case 'AUTO_TOGGLE_COLLAPSED':
            {
                const _state = {
                    ...state,
                    siderCollapsed: localStorageState().siderCollapsed || action.siderCollapsed,
                    allowSiderCollapsed: !action.siderCollapsed
                }
                return _state
            }
        // 切换主题
        case 'SET_THEME':
            {
                const _state = { ...state, theme: action.theme }
                window.localStorage.setItem(SETTING_KEY, JSON.stringify(_state))
                return _state
            }
        default:
            return state
    }
}

export default layout