import {
  LOGIN,
  MODIFY_PASSWORD,
  ROUTES,
  V4_GET_INFO,
  V4_LOGIN,
  V4_LOGOUT
} from '@vue2-client/services/apiService'
import { request, METHOD, removeAuthorization } from '@vue2-client/utils/request'
import EncryptUtil from '@vue2-client/utils/EncryptUtil'
import axios from 'axios'
import { V4_SESSION_KEY } from '@vue2-client/store/mutation-types'

/**
 * 登录服务
 * @param name 账户名
 * @param password 账户密码
 * @returns {Promise<AxiosResponse<T>>}
 */
export async function login (name, password) {
  let data = {
    name: name,
    password: password
  }
  data = '$' + EncryptUtil.RSAEncrypt(JSON.stringify(data))
  return request(LOGIN, METHOD.POST, data)
}

export async function modifyPassword (name, password, newPassword) {
  return request(MODIFY_PASSWORD, METHOD.POST, {
    data: {
      ename: name,
      password: password,
      newpassword: newPassword,
      affirmpassword: newPassword
    }
  })
}

export async function V4Login (name, password, routeName) {
  return request(V4_LOGIN, METHOD.POST, {
    username: name,
    password: password,
    resourceName: routeName
  })
}

export async function V4RefreshToken () {
  const { AESDecrypt } = EncryptUtil
  const info = AESDecrypt(localStorage.getItem('SinglePage_TOKEN'), '3KMKqvgwR8ULbR8Z')
  return axios.post(V4_LOGIN, {
    username: info.name,
    password: info.password,
    resourceName: '智慧燃气'
  })
}

export async function V4GetInfo () {
  return request(V4_GET_INFO, METHOD.POST, {})
}

export async function getRoutesConfig (value, routeName = '智慧燃气') {
  return request(ROUTES + '/' + routeName, METHOD.POST, value)
}

/**
 * 退出登录
 */
export function logout () {
  if (window.__MICRO_APP_ENVIRONMENT__) {
    window.microApp.dispatch({ type: 'logout' })
  }
  return new Promise((resolve, reject) => {
    request(V4_LOGOUT, METHOD.DELETE, {}).then(() => {
      resolve()
    }).catch(error => {
      reject(error)
    }).finally(() => {
      localStorage.removeItem(process.env.VUE_APP_ROUTES_KEY)
      localStorage.removeItem(process.env.VUE_APP_PERMISSIONS_KEY)
      localStorage.removeItem(process.env.VUE_APP_ROLES_KEY)
      localStorage.removeItem(V4_SESSION_KEY)
      removeAuthorization()
    })
  })
}
export default {
  login,
  logout,
  getRoutesConfig,
  V4RefreshToken
}
