import { loginApi } from '@services'
import tools from '@tools'
import hmacSHA256 from 'crypto-js/hmac-sha256'
import Base64 from 'crypto-js/enc-base64'

export default class LoginAction {
  /**
   * 当前登录用户，检测是否该系统有权限
   */
  getInfo (callback) {
    return loginApi.getInfo().then(res => {
      // callback(res) // 可以不使用callback 因为使用then
      return res
    })
  }
  /**
   * 调用登录接口
   */
  userLogin (obj, callback) {
    return loginApi.userLogin(obj).then(res => {
      /* 设置cookie */
      let expires = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
      // 翻转、加盐、base64
      const salt = '0ZSGxuBkSJS5'
      let sup = res.ticket.split('').reverse().join('')
      let rad = Math.random()
      let token = salt + sup + rad
      sup = new Buffer(token).toString('base64') // eslint-disable-line
      // yii格式加密 hmac sha256
      let serialize = `a:2:{i:0;s:4:"_SUP";i:1;s:${sup.length}:"${sup}";}`
      let hamc = Base64.stringify(hmacSHA256(serialize, 'VzpR5JMDNqUsOZ0IFQARNLU9_0KLr9UC'))
      sup = encodeURIComponent(hamc + serialize)
      // 设置到cookie
      let opts = { path: '/', domain: '.ezijing.com', expires: expires }

      tools.cookies.setCookie('_SUP', sup, opts)
      // result.data.uid = result.data.sso_id
      // callback(res) // 可以不使用callback 因为使用then
      return res
    })
  }
}
