import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './modules/app'
import settings from './modules/settings'
import user from './modules/user'
import { login, loginERP, logout, getInfo, getInfo2 } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '../router/index'
/* Layout */
import Layout from '@/layout'

Vue.use(Vuex)


const getDefaultState = () => {
    return {
        token: getToken(),
        name: '',
        avatar: '',
        nickName: '',
        routes: []
    }
}

const state = getDefaultState()

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },

    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_NICKNAME: (state, nickName) => {
        state.nickName = nickName
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
        state.permissions = permissions
    },
    // 移除用户
    REMOVE: (state) => {
        state.name = ''
        state.addRoutes = []
            //退出后，改变还原静态路由
        removeArrayData(constantRoutes)
    },
    ADD_ROUTES: (state, routes) => {
        state.addRoutes = routes
        routes.forEach((i, index) => {
            // 从第3+index个位置插入
            // constantRoutes.splice(3 + index, 0, i)
        })
    },
    SET_MENULIST: (state, menuList) => {
        state.menuList = menuList
    }
}

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { username, password, code, uuid } = userInfo
        return new Promise((resolve, reject) => {
            login({ username: username.trim(), passWord: password, code: code, uuid: uuid }).then(response => {
                if (response.status == "SUCCESS") {
                    commit('SET_TOKEN', response.data)
                    setToken(response.data)
                    resolve(response.data)
                } else {
                    reject(response.msg)
                }
            }).catch(error => {
                reject(error)
            })
        })
    },
    // 登录PER
    LoginERP({ commit }, userInfo) {
        return new Promise((resolve, reject) => {
            loginERP({ username: userInfo.username, password: userInfo.password }).then(response => {
                if (response.status == "SUCCESS") {
                    setToken(response.data)
                    commit('SET_TOKEN', response.data)
                    resolve(response.data)
                } else {
                    reject(response.msg)
                }
            }).catch(error => {
                reject(error)
            })
        })
    },
    // get user info
    getInfo({ commit }) {
        return new Promise((resolve, reject) => {
            getInfo().then(response => {
                let data = response.data
                var arrayList = [];
                for (let i = 0; i < data.length; i++) {
                    arrayList.push({
                        path: (data[i].path).slice(1, 8),
                        component: Layout,
                        redirect: (data[i].path).slice(1, 8),
                        name: "",
                        meta: {
                            title: data[i].meta.title,
                            icon: data[i].meta.icon
                        },
                        children: []
                    })
                    for (let j = 0; j < data[i].children.length; j++) {
                        var new_response = data[i].children[j].meta
                        var url = data[i].children[j].path
                        arrayList[i].children.push({
                            path: url,
                            name: '',
                            component: (resolve) => require([`@/views${data[i].children[j].path}`], resolve),
                            meta: {
                                title: new_response.title,
                                icon: new_response.icon
                            }

                        })
                    }
                }
                var header = [{
                            path: '/index',
                            component: () =>
                                import ('@/views/index/index'),
                            hidden: true,
                        },
                        {
                            path: '/',
                            component: Layout,
                            redirect: '/index',
                            children: [{
                                path: 'index',
                                name: '',
                                component: () =>
                                    import ('@/views/index/index'),
                                meta: { title: '首页', icon: 'home' }
                            }]
                        },


                    ]
                    // 404 page must be placed at the end !!!
                let footer = {
                    path: '*',
                    redirect: '/404',
                    hidden: true
                }
                header[2] = arrayList[0]
                arrayList.unshift(header[1])
                arrayList.unshift(header[0])
                arrayList.push(footer)
                router.options.routes = arrayList
                state.app.routes = router.options.routes

                router.addRoutes(arrayList)

            }).catch(error => {
                reject(error)
            })
            getInfo2().then(response => {
                commit('SET_NICKNAME', response.data.user.nickName)
            })
        })
    },

    // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            logout().then((response) => {
                removeToken() // must remove  token  first
                    // resetRouter()
                commit('RESET_STATE')

                commit('SET_TOKEN', '')
                commit('SET_ROLES', [])
                commit('SET_PERMISSIONS', [])
                removeToken()
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            removeToken() // must remove  token  first
            commit('RESET_STATE')
            resolve()
        })
    }
}

const store = new Vuex.Store({
    modules: {
        app,
        settings,
        user
    },
    getters,
    actions,
    state,
    mutations,
    router
})

export default store
