import { login, loginUserName, logout, queryMenus } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import service from '@/components/Device/service'
import bridge, { isInApp } from '@/utils/bridge'
import store from '../index'

export const FIRM = {
  SR: 'SR',
  KT: 'KT'
}

const getDefaultState = () => {
  const userInfo = JSON.parse(localStorage.getItem('login-user'))
  return {
    token: getToken(),
    tenantNo: '',
    name: '',
    avatar: '',
    roles: [],
    device: {
      firm: FIRM.SR,
      showTakePhoto: false,
      showReadCard: false
    },
    deviceType: 'pc',
    organId: '',
    organName: '',
    initDevice: false,
    ...userInfo
  }
}

const state = getDefaultState()

// app的参数
const appParamExt = {
  appKey: '61E27E40712A40E09A96F047130E8B4F',
  appSecret: 'B3D31A1301124E708BE2C37FFCA3653E',
  appPassword: 'FB0881949A814D6FAAF672F739409675'
}

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
  },
  SET_DEVICE: (state, device) => {
    state.device = device
  },
  SET_ORGAN_ID: (state, organId) => {
    state.organId = organId
  },
  SET_ORGAN_NAME: (state, organName) => {
    state.organName = organName
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { type } = userInfo // type：'msg'：验证码登录；'password': 密码登录
    delete userInfo.type
    const { phone, sms, tenantNo } = userInfo
    const params = type === 'msg' ? { phone: phone.trim(), tenantNo, sms, platformSource: 'Web' } : userInfo
    return new Promise((resolve, reject) => {
      (type === 'msg' ? login : loginUserName)(params).then(response => {
        const data = response || {}
        // 将数据保存到缓存中
        localStorage.setItem('login-user', JSON.stringify({
          name: data.loginName,
          avatar: '',
          tenantNo,
          organId: data.organId,
          organName: data.organName
        }))
        commit('SET_TOKEN', data.accessToken)
        commit('SET_NAME', data.loginName)
        commit('SET_AVATAR', require('@/assets/img/default-avatar.png'))
        commit('SET_ORGAN_ID', data.organId)
        commit('SET_ORGAN_NAME', data.organName)
        setToken(data.accessToken)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user menus
  getMenus({ commit, state }) {
    return new Promise((resolve, reject) => {
      queryMenus(state.token).then(response => {
        const data = response.list || []
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

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

  getDeviceInfo({ commit, state }) {
    // 如果当前初始化过数据了，则不在初始化
    if (state.initDevice) {
      return
    }
    // 标记当前已经初始化过设备了
    state.initDevice = true
    return new Promise(resolve => {
      // 如果当前在pad内
      if (isInApp) {
        bridge.geOtgReadType(code => {
          console.log('当前app设备type:', code)
          const { model } = store.getters
          // 如果当前是pad设备
          if (model.pad.includes(code.toUpperCase())) {
            state.deviceType = 'pad'
          }
          // 如果当前是一体机设备
          if (model.aio.includes(code.toUpperCase())) {
            state.deviceType = 'aio'
          }
          commit('SET_DEVICE', {
            firm: FIRM.SR,
            showTakePhoto: false,
            showReadCard: state.deviceType !== 'pc'
          })
          resolve()
        })
        return
      }
      // 设置秘钥
      // 获取森瑞的设备
      Promise.all([
        service.getVideoInfo(),
        service.setAppParamEx(appParamExt.appKey, appParamExt.appSecret, appParamExt.appPassword)
      ]).then(data => {
        if (data[0].length === 2) {
          commit('SET_DEVICE', {
            firm: FIRM.SR,
            showTakePhoto: true,
            showReadCard: true
          })
          resolve()
        } else {
          service.listCard().then(card => {
            commit('SET_DEVICE', {
              firm: FIRM.SR,
              showTakePhoto: false,
              showReadCard: !!card
            })
            resolve()
          })
        }
      }).catch(err => {
        // 标记当前已经初始化过设备了
        state.initDevice = false
        console.error(err)
        resolve()
      })
      // 卡尔的设备
      service.listKtCard().then(data => {
        // 如果读取到设备了
        if (data.length > 0) {
          commit('SET_DEVICE', {
            firm: FIRM.KT,
            showTakePhoto: false,
            showReadCard: true
          })
        }
      })
    })
  },

  // 退出登录
  logout({ dispatch }) {
    // 退出登录接口调用成功后清空token
    logout().then(() => dispatch('resetToken'))
  }
}

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

