import Vue from 'vue'
import {
  ctos3Api
} from '../../../packages/api/manage.js'

import { ACCESS_TOKEN, USER_NAME, USER_INFO, USER_AUTH, SYS_BUTTON_AUTH, UI_CACHE_DB_DICT_DATA } from '@/store/mutation-types'
 import { welcome }  from '../../../packages/utils/util'

 const user = {
  state: {
    token: '',
    username: '',
    realname: '',
    welcome: '祝你开心每一天!',
    permissionList: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { username, realname, welcome }) => {
      state.username = username
      state.realname = realname
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {

    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        ctos3Api(userInfo).then(response => {
          if (response.responseData.statusCode === 0) {
            const result = response.responseData.resultData
            Vue.ls.set(ACCESS_TOKEN, result.tailInfos.token, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_NAME, result.userid, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_INFO, result, 7 * 24 * 60 * 60 * 1000)
            // Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', result.tailInfos.token)
            commit('SET_INFO', result)
            commit('SET_NAME', { username: result.userid, realname: result.username, welcome: welcome() })
            //  commit('SET_AVATAR', userInfo.avatar)
            resolve(response)
          } else {
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetPermissionList ({ commit }) {
      return new Promise((resolve, reject) => {
        const params = { }
        params.serviceName = 'userService'
        params.methodName = 'getUserPermissionByToken'
        params.rpcParams = []
        ctos3Api(params).then(response => {
          const menuData = response.responseData.resultData.menu
          const authData = response.responseData.resultData.auth
          const allAuthData = response.responseData.resultData.auth
          // Vue.ls.set(USER_AUTH,authData);
          sessionStorage.setItem(USER_AUTH, JSON.stringify(authData))
          sessionStorage.setItem(SYS_BUTTON_AUTH, JSON.stringify(allAuthData))
          if (menuData && menuData.length > 0) {
            menuData.forEach((item, index) => {
              if (item['children']) {
                item['redirect'] = null
                const hasChildrenMenu = item['children'].filter((i) => {
                  return !i.hidden || i.hidden === false
                })
                if (hasChildrenMenu === null || hasChildrenMenu.length === 0) {
                  item['hidden'] = true
                }
              }
            })
            commit('SET_PERMISSIONLIST', menuData)
          } else {
            // reject('getPermissionList: permissions must be a non-null array !')
          }
          resolve(response)
        }).catch(error => {
          commit('SET_TOKEN', '')
          commit('SET_PERMISSIONLIST', [])
          Vue.ls.remove(ACCESS_TOKEN)
          Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
          Vue.ls.clear()
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        const params = { }
        params.serviceName = 'userService'
        params.methodName = 'logOff'
        params.rpcParams = []
        ctos3Api(params).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_PERMISSIONLIST', [])
          Vue.ls.remove(ACCESS_TOKEN)
          Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
          Vue.ls.clear()
          resolve()
        }).catch(() => {
          resolve()
        })
      })
    }

  }
}

export default user
