import { login, logout, getInfo } from '@/api/user'
import { GetDataByName } from '@/api/common'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Message } from 'element-ui'
import Cookies from 'js-cookie'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  pastureid: '',
  pasturename: '',
  pasturenumber: '',
  employename: '',
  employeid: '',
  departmentid: '',
  departmentname: '',
  depids:'',
  sumamount: '',
  roles: [],
  buttons: [],
  meslist: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
    Cookies.set('name', name)
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PASTUREID: (state, pastureid) => {
    Cookies.set('pastureid', pastureid)
    state.pastureid = pastureid
  },
  SET_PASTURENAME: (state, pasturename) => {
    Cookies.set('pasturename', pasturename)
    state.pasturename = pasturename
  },
  SET_PASTURENUMBER: (state, pasturenumber) => {
    Cookies.set('pasturenumber', pasturenumber)
    state.pasturenumber = pasturenumber
  },
  SET_EMPLOYEID: (state, employeid) => {
    Cookies.set('employeid', employeid)
    // console.log('Cookies.set.employeid', employeid)
    state.employeid = employeid
  },
  SET_EMPLOYENAME: (state, employename) => {
    Cookies.set('employename', employename)
    state.employename = employename
  },
  SET_DEPARTMENTID: (state, departmentid) => {
    Cookies.set('departmentid', departmentid)
    state.departmentid = departmentid
  },
  SET_DEPARTMENTNAME: (state, departmentname) => {
    Cookies.set('departmentname', departmentname)
    state.departmentname = departmentname
  },
  SET_DEPIDS: (state, depids) => {
    Cookies.set('depids', depids)
    state.depids = depids
  },
  SET_SUMAMOUNT: (state, sumamount) => {
    Cookies.set('sumamount', sumamount)
    sessionStorage.setItem('sumamount', JSON.stringify(sumamount))
    state.sumamount = sumamount
  },
  SET_MESLIST: (state, meslist) => {
    sessionStorage.setItem('meslist', JSON.stringify(meslist))
    state.meslist = meslist
  },
  SET_BUTTONS: (state, buttons) => {
    Cookies.set('buttons', buttons)
    sessionStorage.setItem('buttons', JSON.stringify(buttons))
    state.buttons = buttons
  },
  SET_ISHOMEPAGE: (state, isHomePage) => {
    Cookies.set('isHomePage', isHomePage)
    sessionStorage.setItem('isHomePage', JSON.stringify(isHomePage))
    state.isHomePage = isHomePage
  },

}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data, msg } = response
        if (msg !== 'ok') {
          Message({
            message: data,
            type: 'error',
            duration: 5 * 1000
          })
          reject(data)
        }
        commit('SET_TOKEN', data.token)
        if (Cookies == null) {
          console.log(1)
        }
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { role, username, avatar } = data

        // roles must be a non-empty array
        if (!role || role.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        GetDataByName({ 'name': 'getUserPCButtons', 'parammaps': { 'jwt_username': username }}).then(response => {
          console.log("getUserPCButtons=================",response)
          if(response.data.list !== null){
            commit('SET_BUTTONS', response.data.list)
          } else{
            commit('SET_BUTTONS', [])
          }
        })

        GetDataByName({ 'name': 'findByUserPastureName', 'parammaps': { 'jwt_username': username }}).then(response => {
          if (response.data.list.length > 0) {
            commit('SET_PASTUREID', response.data.list[0].pastureId)
            commit('SET_PASTURENAME', response.data.list[0].pastureName)
            commit('SET_PASTURENUMBER', response.data.list[0].pastureNumber)
            commit('SET_EMPLOYEID', response.data.list[0].employeId)
            commit('SET_EMPLOYENAME', response.data.list[0].employeName)
            commit('SET_DEPARTMENTID', response.data.list[0].departmentId)
            commit('SET_DEPARTMENTNAME', response.data.list[0].departmentName)
            commit('SET_DEPIDS', response.data.list[0].depIds)
          }
          GetDataByName({ 'name': 'getNoMesCount', 'parammaps': { 'empId': response.data.list[0].employeId, 'pastureId': response.data.list[0].pastureId, deptId: response.data.list[0].departmentId }}).then(response => {
            commit('SET_SUMAMOUNT', response.data.list[0].sumAmount)
          })
          // 获取消息通知前五条
          GetDataByName({ 'name': 'getNoMesList', 'page': 1, 'offset': 1, 'pagecount': 5, 'parammaps': { 'empId': response.data.list[0].employeId, 'pastureId': response.data.list[0].pastureId, deptId: response.data.list[0].departmentId }}).then(response => {
            commit('SET_MESLIST', response.data.list)
          })
          GetDataByName({ 'name': 'gethomepagemenu', 'parammaps': { }}).then(response => {
            commit('SET_ISHOMEPAGE', response.data.list[0].cou)
          })
        })
        // 获取消息通知数量

        window.setInterval(() => {
          setTimeout(() => {
            // console.log(Cookies.get('employeid'))
            GetDataByName({ 'name': 'getNoMesCount', 'parammaps': { 'empId': Cookies.get('employeid'), 'pastureId': Cookies.get('pastureid'), deptId: Cookies.get('departmentid') }}).then(response => {
              commit('SET_SUMAMOUNT', response.data.list[0].sumAmount)
            })
            // 获取消息通知前五条
            GetDataByName({ 'name': 'getNoMesList', 'page': 1, 'offset': 1, 'pagecount': 5, 'parammaps': { 'empId': Cookies.get('employeid'), 'pastureId': Cookies.get('pastureid'), deptId: Cookies.get('departmentid') }}).then(response => {
              commit('SET_MESLIST', response.data.list)
            })
          }, 0)
        }, 1800000)
        commit('SET_ROLES', role)
        commit('SET_NAME', username)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_BUTTONS', [])
        // console.log('-------------', state)
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        Cookies.remove('employename')
        Cookies.remove('employeid')
        Cookies.remove('pastureid')
        removeToken()
        resetRouter()
        resolve()
        location.reload()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
