import { login, getInfo, getCertificationStatus } from '@/api/user'
import { getMyEnterprise } from '@/api/myTrade/salesContract'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: {},
    tradeRelationType: '',
    myTradeType: '',
    mySettlement: '',
    authStatus: '',
    showAllMenu: 'show',
    mySalesBillType: '',
    myPurchaseBillType: '',

    enterpriseInfo: {
      enterpriseType: '', // 企业类型     1内资2外商3外贸9其他
      exportType: '', // 出口类型  self_export--自营         proxy_export--代理出口
      proxyDistrictCode: '', // 代理公司区域  CN_MAINLAND-中国大陆   CN_HK-香港   CN_MO-澳门   CN_TW-台湾   FOREIGN-境外

      purchaseFunction: 'show' // 生产企业 + 自营出口  无采购相关功能
    }
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO: (state, info) => {
    state.userInfo = info
  },
  SET_TRADE_RELATION_TYPE: (state, info) => {
    state.tradeRelationType = info
  },
  SET_TRADE_TYPE: (state, info) => {
    state.myTradeType = info
  },
  SET_SETTLMENT_TYPE: (state, info) => {
    state.mySettlement = info
  },
  SET_AUTH_STATUS: (state, info) => {
    state.authStatus = info
  },
  SET_SHOW_ALLMENU: (state, info) => {
    state.showAllMenu = info
  },
  SET_SALES_BILL_TYPE: (state, info) => {
    state.mySalesBillType = info
  },
  SET_PURCHASE_BILL_TYPE: (state, info) => {
    state.myPurchaseBillType = info
  },
  SET_ENTERPRISE_TYPE: (state, info) => { // 企业区域
    state.enterpriseInfo.enterpriseType = info
  },
  SET_EXPORT_TYPE: (state, info) => { // 出口类型
    state.enterpriseInfo.exportType = info
  },
  SET_PROXY_DISTRICT_CODE: (state, info) => { // 代理公司所属区域
    state.enterpriseInfo.proxyDistrictCode = info
  },
  SET_PURCHASE_FUNCTION: (state, info) => { // 采购相关功能
    state.enterpriseInfo.purchaseFunction = info
  }
}

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 } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const { nickname } = data
        commit('SET_NAME', nickname)
        commit('SET_USERINFO', data)
        // commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get auth status
  getAuthStatus({ commit, state }) {
    return new Promise((resolve, reject) => {
      getCertificationStatus().then(response => {
        const { data } = response
        const { certificationStatus, showAllFunctions } = data
        commit('SET_AUTH_STATUS', certificationStatus)
        commit('SET_SHOW_ALLMENU', showAllFunctions ? 'show' : 'hide')
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get enterprise baseInfo
  getEnterpriseBasicInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getMyEnterprise().then(response => {
        const { data } = response
        if (data) {
          const { exportType, proxyDistrictCode, enterpriseType } = data

          commit('SET_ENTERPRISE_TYPE', enterpriseType)
          commit('SET_PROXY_DISTRICT_CODE', proxyDistrictCode)
          commit('SET_EXPORT_TYPE', exportType)

          // 生产企业 + 自营出口  无采购相关功能
          if (exportType === 'self_export' && ['1', '2'].includes(enterpriseType)) {
            commit('SET_PURCHASE_FUNCTION', 'hide')
          } else {
            commit('SET_PURCHASE_FUNCTION', 'show')
          }
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

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

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

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