import {
  login,
  logout,
  getInfo,
  getRoule,
  isLandBased,
  companyInfo
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import {
  resetRouter
} from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
  }
}

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_ROLES: (state, roles) => {
    state.roles = roles
  },
}

const actions = {
  // user login
  async login({
    commit,
    dispatch
  }, userInfo) {
    const {
      companyName,
      username,
      password
    } = userInfo
    // return new Promise((resolve, reject) => {
    const data = await login({
      companyName: companyName,
      username: username.trim(),
      password: password
    })
    console.log(data,11111)
    // .then(response => {
    // const { data } = response
    // commit('SET_TOKEN', '')
    // setToken('')
    // commit('SET_TOKEN', data.token)
    // setToken(data.token)
    // commit('SET_TOKEN', 'Admin-Token')
    
    // resolve(response)
    // }).catch(error => {
    // reject(error)
    // })
    const {
      compId,
      tenantId,
      vesselId,
      vesselBankFlag,
      clientFag,
      userId
    } = data.data
    localStorage.setItem('wf-pf_admin-token1', 'Admin-Token')
    localStorage.setItem('ws-pf_compId', compId)
    localStorage.setItem('ws-pf_userId', userId)
    localStorage.setItem('ws-pf_tenantId', tenantId)
    localStorage.setItem('ws-pf_vesselId', vesselId) // 仅适用于一条船
    localStorage.setItem('ws-pf_vesselBankFlag', vesselBankFlag) // 当前登录人是船端还是岸端的人员
    localStorage.setItem('ws-pf_clientFag', clientFag)
    // notification.setSessionId(userId) // 设置通知唯一标识
    // notification.start() // 开始监听通知
    // })
    await isLandBased().then(response => {
      localStorage.setItem('ws-pf_serviceTypeFlag', response)
    })
    const {
      organizationMonetaryKey,
      compName,
      compDomainName,
      organizationMonetaryValue
    } = await companyInfo({
      compId: compId
    })
    localStorage.setItem('ws-pf_organMonetaryKey', organizationMonetaryKey)
    localStorage.setItem('ws-pf_compName', compName)
    localStorage.setItem('ws-pf_compDomainName', compDomainName)
    localStorage.setItem('ws-pf_organMonetaryValue', organizationMonetaryValue)
    dispatch('getInfo', {
      vesselBankFlag,
      compName
    })
    
    return data
  },
  async getInfo({
    commit,
    dispatch
  }, {
    vesselBankFlag = 'B',
    compName = ''
  }) {
    const response = await getInfo()
    const {
      staffName,
      deptId,
      deptName,
      deptNameEn,
      vessels = [],
      majorRole: {
        roleName = '',
        roleId = '',
        dutyId = ''
      },
      roles
    } = response.data
    const content = {
      ...response.data,
      showRoleName: roleName || roles[0].roleName,
      showRoleId: roleId || roles[0].roleId,
      showCompName: vesselBankFlag === 'V' ? vessels[0].vesselName : compName,
      avatar: 'img/user.png'
    }
    // setStore({
    //     name: 'userInfo',
    //     content: content,
    //     type: 'session'
    // })
    // dispatch('common/setLocalVessels', vessels, { root: true })
    // commit('SET_USER_INFO', content)

    localStorage.setItem('ws-pf_dutyId', dutyId || response.data.roles[0].dutyId)
    localStorage.setItem('ws-pf_roleName', roleName || roles[0].roleName)
    localStorage.setItem('ws-pf_staffName', staffName)
    localStorage.setItem('ws-pf_deptId', deptId)
    localStorage.setItem('ws-pf_deptName', deptName)
    localStorage.setItem('ws-pf_deptNameEn', deptNameEn)
    localStorage.setItem('ws-pf_vessels', JSON.stringify(vessels))
    localStorage.setItem('ws-pf_roleId', roleId || roles[0].roleId)
    
  },
  // // get user info
  // async getInfo({
  //   commit,
  //   state,
  //   dispatch
  // }) {
  //   return new Promise((resolve, reject) => {

  //     getInfo().then(response => {
  //       const {
  //         data
  //       } = response
  //       if (!data) {
  //         reject('Verification failed, please Login again.')
  //       }
  //       const {
  //         staffName,
  //         deptId,
  //         deptName,
  //         deptNameEn,
  //         vessels = [],
  //         majorRole: {
  //           roleName = '',
  //           roleId = '',
  //           dutyId = ''
  //         },
  //         roles
  //       } = data

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

  //       localStorage.setItem('ws-pf_dutyId', dutyId || data.roles[0].dutyId)
  //       localStorage.setItem('ws-pf_roleName', roleName || roles[0].roleName)

  //       localStorage.setItem('ws-pf_staffName', staffName)
  //       localStorage.setItem('ws-pf_deptId', deptId)
  //       localStorage.setItem('ws-pf_deptName', deptName)
  //       localStorage.setItem('ws-pf_deptNameEn', deptNameEn)
  //       localStorage.setItem('ws-pf_vessels', JSON.stringify(vessels))
  //       localStorage.setItem('ws-pf_roleId', roleId || roles[0].roleId)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  getRoule({
    commit,
    state
  }) {
    return new Promise(async (resolve, reject) => {
      try {
        const data = await getRoule(state.roles)
        data.forEach(route => {
          asyncRoutes.push(route)
        })
        commit('SET_ROUTES', asyncRoutes)
        resolve(asyncRoutes)
      } catch (error) {
        reject(error)
      }
    })
//   getRoule({
//     commit,
//     state
//   }) {
//     return new Promise(async (resolve, reject) => {
//       try {
//         const data = await getRoule(state.roles)
//         data.forEach(route => {
//           asyncRoutes.push(route)
//         })
//         console.log(asyncRoutes)
//         commit('SET_ROUTES', asyncRoutes)
//         resolve(asyncRoutes)
//       } catch (error) {
//         reject(error)
//       }
//     })
  },
  // user logout
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        // setToken('')
        localStorage.setItem('wf-pf_admin-token1', '')
        resetRouter()
        // console.log(getToken())
        // 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
}
