import Vue from 'vue'
import {
  ctos3Api
} from '../../../packages/api/manage.js'
import { login, loginSys, getInfo, logout } from '@/api/material/login'
import {
  ACCESS_TOKEN,
  USER_NAME,
  OPERATOR,
  EXPORT_ID,
  COMPANY_NAME,
  USER_INFO,
  USER_AUTH,
  SYS_BUTTON_AUTH,
  ORG_ID
} from '@/store/mutation-types'
import {
  welcome, requestBuilder
} 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) => {
        return loginSys(requestBuilder('login', userInfo)).then(response => {
          if (response.code === '0000') {
            console.log('response', response)
            const expires = 7 * 24 * 60 * 60 * 1000
            const result = response.result || {}
            const data = result.data || {}
            const userNo = data.loginName || ''
            const token = result.token || ''
            const userName = data.userName || ''
            Vue.ls.set(ACCESS_TOKEN, token, expires)
            Vue.ls.set(OPERATOR, userNo, expires)
            Vue.ls.set(EXPORT_ID, response.result.data.companyCod, expires)
            Vue.ls.set(USER_NAME, userName, expires)
            Vue.ls.set(COMPANY_NAME, response.result.data.companyName, expires)
            localStorage.setItem(ACCESS_TOKEN, JSON.stringify({
              'value': token
            }), 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_INFO, response.result.data, 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', token)
            commit('SET_INFO', response.result.data)
            commit('SET_NAME', {
              username:userName,
              realname: 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 => {
          reject(error)
        })
      })
    },

    // 登出
    Logout({ dispatch, commit, state }) {
      return logout(requestBuilder('loginout', {}))
        .catch(() => { })
        .finally(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          commit('SET_BUTTONS', {})
          dispatch('DelAllTags', [])
          Vue.ls.remove(ACCESS_TOKEN)
          Vue.ls.remove(OPERATOR)
          Vue.ls.remove(ORG_ID)
        })
    }

  }
}

export default user