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

const getDefaultState = () => {
  return {
    token: getToken(), // token
    fanruanToken: getFanruanToken(),
    userid: getUserid(), // 用户id
    name: '', // 用户名称
    phone: '', // 用户手机
    menus: '', // 菜单
    customerId: '', // 经销商ID
    customerName: '', // 经销商名称
    customerNumber: '', // 经销商编码
    showMessages: null, //
    isNotice: false,
    websitNumber: '',
    isCollapse: true,
    isZbService: false,
    isService: false,
    isWebsite: false,
    isCenter: false,
    isAdmin: false,
    isMessageGroup: false,
    isSettlementGroup: false,
    roleList: [],
    websitId: null,
    greemall_user: null
  }
}

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_FANRUAN_TOKEN: (state, token) => {
    state.fanruanToken = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_PHONE: (state, phone) => {
    state.phone = phone
  },
  SET_IS_ZB_SERVICE: (state, isZbService) => {
    state.isZbService = isZbService
  },
  SET_IS_SERVICE: (state, isService) => {
    state.isService = isService
  },
  SET_IS_ADMIN: (state, isAdmin) => {
    state.isAdmin = isAdmin
  },
  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
  },
  showMessage: (state, value) => {
    if (value == 'yes') {
      state.showMessages = true
    } else {
      state.showMessages = false
      state.isNotice = true
    }
  },
  set_greemall_user: (state, value) => {
    state.greemall_user = value
  },
  SET_ROLELIST: (state, roleList) => {
    roleList.find(v => {
      if (v.code === 'serviceProviderSite') {
        state.isWebsite = true
      } else {
        state.isWebsite = false
      }

      // if (v.code === 'topServiceProvider') {
      //   state.isCenter = true
      // } else {
      //   state.isCenter = false
      // }

      if (v.code === 'topMessenger') {
        state.isMessageGroup = true
      } else {
        state.isMessageGroup = false
      }

      if (v.code == 'topSettlement') {
        state.isSettlementGroup = true
      } else {
        state.isSettlementGroup = false
      }
    })
  },

  SET_ROLELIST: (state, roleList) => {
    roleList.find(v => {
      if (v.code === 'serviceProviderSite') {
        state.isWebsite = true
      }
      // if (v.code === 'topServiceProvider') {
      //   state.isCenter = true
      // } else {
      //   state.isCenter = false
      // }

      if (v.code === 'topMessenger') {
        state.isMessageGroup = true
      }

      if (v.code == 'topSettlement') {
        state.isSettlementGroup = true
      }
    })
  },
  SET_ROLE_LIST: (state, roleList) => {
    state.roleList = roleList
  },
  SET_WEBSIT_ID: (state, websitId) => {
    state.websitId = websitId
  }
}

const actions = {
  // erweima  login
  scanWwLogin({ commit }, userInfo) {
    const { code, source } = userInfo
    // console.log(code, userInfo);
    return new Promise((resolve, reject) => {
      scanWwLogin({
        code: code,
        source: source
      })
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          commit('SET_FANRUAN_TOKEN', data.fanruanToken)
          commit('SET_USERID', data.adminUserId)
          setToken(data.token)
          setFanruanToken(data.fanruanToken)
          setUserid(data.adminUserId)
          // commit('SET_USERCODE', data.accountBase.accountCode)
          // setUsercode(data.accountBase.accountCode)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 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,
        clientType: '1',
        smsCode
      })
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          commit('SET_FANRUAN_TOKEN', data.fanruanToken)
          commit('SET_USERID', data.adminUserId)
          setToken(data.token)
          setFanruanToken(data.fanruanToken)
          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

          if (!data) {
            return reject('Verification failed, please Login again.')
          }
          console.log(data);
          const { nickName, userName } = data

          commit('SET_NAME', nickName)
          commit('SET_PHONE', userName)

          localStorage.setItem('greemall_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.filter(item => item.flag !== 1)
          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()
          // 页面并清除当前页面的history记录
          window.history.replaceState(null, '', '')
          window.history.go(0)
          // commit('RESET_STATE')
          // 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
}
