const hmacSHA256 = require('crypto-js/hmac-sha256')
// const Base64 = require('crypto-js/enc-base64')
const Hex = require('crypto-js/enc-hex')

const setCookie = (ticket, res) => {
  /* 设置cookie */
  let expires = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
  // 翻转、加盐、base64
  const salt = '0ZSGxuBkSJS5'
  let sup = 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 = Hex.stringify(hmacSHA256(serialize, 'VzpR5JMDNqUsOZ0IFQARNLU9_0KLr9UC'))
  sup = hamc + serialize // encodeURIComponent(hamc + serialize)
  // 设置到cookie
  let opts = { path: '/', domain: '.ezijing.com', expires: expires, httpOnly: true }
  res.cookie('_SUP', sup, opts)
}

const getTicket = (_SUP) => {
  /* 服务端 解析ticket */
  let s = decodeURIComponent(_SUP || '') // tools.cookies.getCookie('_SUP') ||
  let ticket = ''
  s = s.match(/"([\d\w=]+)";\}$/)
  if (s && s.length === 2) {
    s = new Buffer(s[1], 'base64').toString() // eslint-disable-line
    s = s.slice(12, s.search('-TGT') + 4)
    ticket = s.split('').reverse().join('')
  }
  return ticket
}

module.exports = {
  getTicket: getTicket,
  setCookie: setCookie
}
