import { login, logout, getInfo, getRouter } from '@/api/user'
import { getToken, setToken, removeToken, getUserid, setUserid, removeUserid } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(), // token
    userid: getUserid(), // 用户id
    name: '', // 用户名称
    phone: '', // 用户手机
    menus: '', // 菜单
    customerId: '', // 经销商ID
    customerName: '', // 经销商名称
    customerNumber: '', // 经销商编码
    isTradeExaminer: '',
    showMessages: null, //
    isNotice: false,
    websitNumber: '',
    isCollapse: true,
    changeNum: 1,
    userInfo: JSON.parse(localStorage.getItem('supply_user')) || {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_STATUS(state, status) {
    state.isNotice = status
  },
  SET_USERID: (state, userid) => {
    state.userid = userid
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_PHONE: (state, phone) => {
    state.phone = phone
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_CUSTOMERID: (state, customerId) => {
    state.customerId = customerId
  },
  SET_CUSTOMERNAME: (state, customerName) => {
    state.customerName = customerName
  },
  SET_CUSTOMERNUMBER: (state, customerNumber) => {
    state.customerNumber = customerNumber
  },

  SET_IS_COLLAPSE(state, bool) {
    state.isCollapse = !bool.isCollapse
  },
  SET_WEBSIT_NUMBER: (state, websitNumber) => {
    state.websitNumber = websitNumber
  },
  SET_USETINFO(state, data) {
    state.userInfo = data
  },
  SET_CHANGEUNM(state, data) {
    state.changeNum = data || 1
  },
  showMessage: (state, value) => {
    if (value == 'yes') {
      state.showMessages = true
    } else {
      state.showMessages = false
    }
  },
  SET_MESSAGE(state, value) {
    state.isNotice = value
  },
  SET_TRADEEXAMINER: (state, isTradeExaminer) => {
    state.isTradeExaminer = isTradeExaminer
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, code, codeValue, loginType, smsCode } = userInfo
    return new Promise((resolve, reject) => {
      login({
        userName: username.trim(),
        password: password,
        code: code,
        codeValue: codeValue,
        loginType,
        smsCode
      })
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          commit('SET_USERID', data.adminUserId)
          setToken(data.token)
          setUserid(data.adminUserId)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

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

          if (!data) {
            return reject('Verification failed, please Login again.')
          }
          console.log(data)
          let websitNumber
          const { nickName, userName, customerId, customerName, customerNumber, changeNum, isFront, isTradeExaminer } = data

          if (data.adminWebsit) {
            websitNumber = data.adminWebsit.websitNumber
            commit('SET_WEBSIT_NUMBER', websitNumber)
          }
          // 模拟请求数据
          // const menus = [
          // {
          //   'path': '/example',
          //   'component': 'Layout',
          //   'redirect': '/example/table',
          //   'name': 'Example',
          //   'meta': { 'title': 'Example', 'icon': 'el-icon-s-help', 'roles': ['admin'] },
          //   'children': [
          //     {
          //       'path': 'table',
          //       'name': 'Table',
          //       'component': 'table/index',
          //       'meta': { 'title': 'Table', 'icon': 'table' }
          //     },
          //     {
          //       'path': 'tree',
          //       'name': 'Tree',
          //       'component': 'tree/index',
          //       'meta': { 'title': 'Tree', 'icon': 'tree' }
          //     }
          //   ]
          // },
          // ]
          // menus.push({ path: '*', redirect: '/404', hidden: true })
          commit('SET_CHANGEUNM', changeNum)

          commit('SET_CUSTOMERID', customerId)
          commit('SET_CUSTOMERNAME', customerName)
          commit('SET_CUSTOMERNUMBER', customerNumber)
          commit('SET_TRADEEXAMINER', isTradeExaminer)
          commit('SET_NAME', nickName)
          commit('SET_PHONE', userName)
          commit('SET_USETINFO', data)
          // commit("SET_MENUS", menus) // 触发vuex SET_MENUS 保存路由表到vuex

          localStorage.setItem('supply_user', JSON.stringify(data))

          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  getRouter({ commit, state }) {
    return new Promise((resolve, reject) => {
      getRouter({ adminUserId: state.userid })
        .then(response => {
          const menus = response.data
          // 模拟请求数据
          // const menus = [
          //   {
          //     'path': '/example',
          //     'component': 'Layout',
          //     'redirect': '/example/table',
          //     'name': 'Example',
          //     'meta': { 'title': 'Example', 'icon': 'el-icon-s-help' },
          //     'children': [
          //       {
          //         'path': 'table',
          //         'name': 'Table',
          //         'component': 'table/index',
          //         'meta': { 'title': 'Table', 'icon': 'table' }
          //       },
          //       {
          //         'path': 'tree',
          //         'name': 'Tree',
          //         'component': 'tree/index',
          //         'meta': { 'title': 'Tree', 'icon': 'tree' }
          //       }
          //     ]
          //   },
          // ]
          // menus.push({ path: '*', redirect: '/404', hidden: true })
          commit('SET_MENUS', menus)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken() // must remove  token  first
          removeUserid()
          resetRouter()
          commit('RESET_STATE')
          localStorage.removeItem('user_change_num')
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

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

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