import {
  login,
  lineLogin,
  logout,
  getInfo
} from '@/api/login'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
const state = {
  token: getToken(),
  name: null, //用户名
  userId: null, //用户ID
  nickName:null,//用户昵称
  userInfo: null, //用户基本信息
  distributionId:null,//分销人ID
  language:'ja',//语言
  companyinfo:{},
  liffId: null,
}

const mutations = {
  //---新的数据---
  //存储token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERID(state, userId) {
    state.userId = userId
  },
  //用户基本信息
  SET_USERINFO: (state, data) => {
    state.userInfo = data
  },
  SET_DISTR_BUTION_ID: (state, data) => {
    state.distributionId = data
  },
  SET_NICK_NAME: (state, data) => {
    state.nickName = data
  },
  SET_LANGUAGE: (state, data) => {
    state.language = data
  },
  SET_COMPANY_INFO_DATA: (state, data) => {
      state.companyinfo = data
  },
  SET_LIFF_ID: (state, data) => {
    state.liffId = data
  },
}

const actions = {
  // 登录
  Login({
    commit
  }, userInfo) {
    const username = userInfo.phone.trim()
    const password = userInfo.password
    return new Promise((resolve, reject) => {
      login({username, password}).then(res => {
        setToken(res.msg)
        commit('SET_TOKEN', res.msg)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  LineLogin({
      commit
  }, userInfo) {
    const username = userInfo.username.trim()
    const password = userInfo.password
    const name = userInfo.name
    const liffId = userInfo.liffId
    return new Promise((resolve, reject) => {
      lineLogin({username, password, name, liffId}).then(res => {
        setToken(res.data.token)
        commit('SET_TOKEN', res.data.token)
        commit('SET_COMPANY_INFO_DATA', res.data.companyinfo)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户信息
  GetInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo().then(res => {
        const user = res.data
        commit('SET_NAME', user.name);//用户名
        commit('SET_USERID', user.id);//用户ID
        commit('SET_USERINFO', user);//用户基本信息
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // // 退出系统
  // LogOut({
  //   commit,
  //   state
  // }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token).then(() => {
  //       commit('SET_TOKEN', '')
  //       commit('SET_ROLES', [])
  //       commit('SET_PERMISSIONS', [])
  //       removeToken()
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // // 前端 登出
  // FedLogOut({
  //   commit
  // }) {
  //   return new Promise(resolve => {
  //     commit('SET_TOKEN', '')
  //     removeToken()
  //     resolve()
  //   })
  // }
}

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