import { loginByUsername, getUserInfo, loginByDemo, get_employee_map, get_point_types, get_site_info, get_dept_tree } from '@/api/login'
import { getToken, setToken, removeToken, removeAllToken } from '@/utils/auth'
import router from '@/router'
const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    jtoken: '',
    Atoken: '',
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    },
    logo: '',
    point_types: [],
    employee_map: {},
    user_info: {},
    site_info: {},
    dept_tree: {},
    pastDue:false,
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_PASTDUE: (state, pastDue) => {
      state.pastDue = pastDue
    },
    SET_DEPT_TREE: (state, tree) => {
      state.dept_tree = tree
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_JTOKEN: (state, token) => {
      state.jtoken = token
    },
    SET_Atoken: (state, token) => {
      state.Atoken = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_POINT_TYPES: (state, data) => {
      state.point_types = data
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_EMPLOYEE_MAP: (state, data) => {
      state.employee_map = data
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_SITEID: (state, site_id) => {
      state.site_id = site_id
    },
    SET_MANAGERTYPE: (state, manager_type) => {
      state.manager_type = manager_type
    },
    SET_USERINFO: (state, data) => {
      state.user_info = data
    },
    SET_SETTINGS: (state, data) => {
      state.system_setting = data
    },
    CHANGE_TYPE: (state, data) => {
      state.newtype = data
    },
    SET_SITEINFO: (state, data) => {
      state.site_info = data
    },
    SET_DELETE_USER (state, data) {
      if(state) state = data
    },
  },

  actions: {
    // 人员列表
    get_employee_map({ commit }) {
      return new Promise((resolve, reject) => {
        // let employee_map = employee_map = JSON.parse(localStorage.getItem('SET_EMPLOYEE_MAP'))
        // if (employee_map) {
        //   commit('SET_EMPLOYEE_MAP', employee_map)
        //   resolve(employee_map)
        // } else {

          get_employee_map().then(response => {
            if (response.data.code == 1) {
              const data = {}
              for (const i in response.data.data.list) {
                data[response.data.data.list[i].id] = response.data.data.list[i]
              }
              commit('SET_EMPLOYEE_MAP', data)
              if (window.plus) {
                plus.storage.setItem('SET_EMPLOYEE_MAP', JSON.stringify(data))
              } else {
                localStorage.setItem('SET_EMPLOYEE_MAP', JSON.stringify(data))
              }
            }
            resolve([])
          }).catch(error => {
            reject(error)
          })

        // }
      })
    },
    // 公司信息
    get_site_info({ state, commit, rootState }) {
      return new Promise((resolve, reject) => {
        // const site_info = JSON.parse(localStorage.getItem('site_info'))
        // if (site_info) {
        //   commit('SET_SITEINFO', site_info)
        //   resolve(site_info)
        // } else {
          get_site_info().then(response => {
            if (response.data.code == 1) {
              commit('SET_SITEINFO', response.data.data)
              localStorage.setItem('site_info', JSON.stringify(response.data.data))
              resolve(response.data.data)
            }
          }).catch(error => {
            reject(error)
          })
        // }
      })
    },
    // 部门树
    get_dept_tree({ commit }) {
      return new Promise((resolve, reject) => {
        // if (!localStorage.getItem('dept_tree')) {
          get_dept_tree().then(response => {
            if (response.data.code == 1) {
              localStorage.setItem('dept_tree', JSON.stringify(response.data.data.list))
              commit('SET_DEPT_TREE', response.data.data.list)
              resolve(response.data)
            } else {
              reject(response.data.msg)
            }
          }).catch(error => {
            reject(error)
          })
        // }
      })
    },
    // 积分类型
    get_point_types({ commit }) {
      return new Promise((resolve, reject) => {
        // let point_types = point_types = JSON.parse(localStorage.getItem('SET_POINT_TYPES'))
        // if (point_types) {
        //   commit('SET_POINT_TYPES', point_types)
        //   resolve(point_types)
        // } else {
          get_point_types().then(response => {
            if (response.data.code == 1) {
              commit('SET_POINT_TYPES', response.data.data.list)
              if (window.plus) {
                plus.storage.setItem('SET_POINT_TYPES', JSON.stringify(response.data.data.list))
              } else {
                localStorage.setItem('SET_POINT_TYPES', JSON.stringify(response.data.data.list))
              }
            }
            resolve(response.data.data.list)
          }).catch(error => {
            reject(error)
          })
        // }
      })
    },



    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.tel.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(response => {
          if (response.data.code == 1) {
            const data = response.data
            localStorage.setItem('user_token_temp', data.data.token)
            localStorage.setItem('site_list_temp', JSON.stringify(data.data.account_site))
            resolve(response.data)
          } else {
            reject(response.data.msg)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    loginByDemo({ commit }) {
      return new Promise((resolve, reject) => {
        loginByDemo().then(response => {
          if (response.data.code == 0) {
            reject(response.data.info)
          } else {
            const data = response.data
            commit('SET_TOKEN', data.data.token)
            setToken(response.data.data.token)
            localStorage.setItem('user_info', JSON.stringify(response))
            resolve(response.data)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo(state.token).then(response => {
          if (!response.data) {
            reject('error')
          }
          if(response.data.code == 1){
            if(response.data.data.user.is_official == 0){
              router.push({
                path: '/noAccess',
                query: {
                  msg: '当前用户未授权进入系统，请联系管理员为您【启用积分管理】，<br/>如需咨询客服，请到您企业专属的功道云服务群咨询'
                }
              })
              return
            }
            const data = response.data
            commit('SET_ROLES', ['admin'])
            commit('SET_NAME', data.data.user.name)
            commit('SET_AVATAR', data.data.user.img_url)
            commit('SET_INTRODUCTION', '')
            commit('SET_SITEID', data.data.user.site_id)
            commit('SET_MANAGERTYPE', 4)
            commit('SET_USERINFO', data.data.user)
            commit('SET_SETTINGS', {})
            resolve(response)
          }else{
            reject(response.data)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    LoginByToken({ commit }, token) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', token)
        commit('SET_JTOKEN', token)
        setToken(token)
        resolve(token)
      })
    },

    // 登出
    LogOut({ commit, state }) {
      localStorage.clear()
      sessionStorage.clear()
      removeAllToken()
      location.reload() // 重新刷新页面会清空VUEX数据,所以不用清空VUEX
    },

    // 动态修改权限
    ChangeRoles({ commit }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          resolve()
        })
      })
    }
  }
}

export default user
