import { post } from '@vue2-client/services/api/restTools'
import notification from 'ant-design-vue/lib/notification'
import { logout } from '@vue2-client/services/user'
import Cookie from 'js-cookie'

const casApi = {
  // 根据用户信息校验服务访问权限并生成ST
  createSTByUserInfo: '/api/af-sso/logic/createSTByUserInfo',
  // 根据TGC生成ST
  createSTByTGC: '/api/af-sso/logic/createSTByTGC',
  // 验证ST
  serviceValidate: '/api/af-sso/logic/openapi/serviceValidate',
  // 其他验证
  otherValidate: '/api/af-sso/logic'
}

function setTGTCookie (cookie) {
  return Cookie.set('TGT-Cookie', cookie)
}
function removeTGTCookie () {
  return Cookie.remove('TGT-Cookie')
}
export function getTGTCookie () {
  return Cookie.get('TGT-Cookie')
}

export function CASLoginByAuth (serviceKey) {
  return new Promise((resolve, reject) => {
    post(casApi.createSTByUserInfo, {
      serviceKey: serviceKey
    }).then(res => {
      setTGTCookie(res.tgc)
      resolve(res)
    }).catch(msg => {
      reject(msg)
    })
  })
}

export function CASLogin (serviceKey, inner) {
  // 从第三方跳转登录
  const tgc = getTGTCookie()
  if (tgc && !inner) {
    return new Promise((resolve, reject) => {
      post(casApi.createSTByTGC, {
        serviceKey: serviceKey,
        tgc: tgc
      }).then(res => {
        resolve(res)
      }).catch(msg => {
        if (msg === '当前操作没有权限') {
          removeTGTCookie()
          notification.error({
            message: '授权已过期，请重新登录',
            description: '2秒后自动跳转回登陆页面'
          })
          logout().then(() => {
            setTimeout(() => {
              window.location.href = '/login?serviceKey=' + serviceKey
            }, 1500)
          })
        } else {
          reject(msg)
        }
      })
    })
  } else {
    return CASLoginByAuth(serviceKey)
  }
}

export function doOtherValidate (logicName, st, serviceKey) {
  return post(casApi.otherValidate + '/' + logicName, {
    st: st,
    serviceKey: serviceKey
  }, null)
}

export default casApi
