import axios from 'axios'
import { message } from 'antd'

const appId = 'i-ri1jxut3edfmz'
const appKey = 'z3d69f164i698e3nph68'

/**
 * 使用 Web Crypto API 实现 HMAC-SHA256
 * 由于 HmacSHA256 通常是同步的，但 Web Crypto 是异步的，
 * 我们需要调整拦截器以支持异步签名生成。
 */
const hmacSHA256 = async (data, key) => {
  const encoder = new TextEncoder()
  const keyData = encoder.encode(key)
  const msgData = encoder.encode(data)
  
  const cryptoKey = await window.crypto.subtle.importKey(
    'raw',
    keyData,
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['sign']
  )
  
  const signature = await window.crypto.subtle.sign('HMAC', cryptoKey, msgData)
  return Array.from(new Uint8Array(signature))
    .map(b => b.toString(16).padStart(2, '0'))
    .join('')
}

const buildSign = async () => {
  // 生成当前时间 + 1小时后的时间戳
  const time = new Date(new Date().getTime() + 60 * 60 * 3000).toISOString()
  // 使用 Web Crypto API 生成签名
  const signature = await hmacSHA256(appId + time, appKey)
  // 返回Authorization头格式: appId/signature/time
  return `${appId}/${signature}/${time}`
}

const request = axios.create({ baseURL: '/api/xiling' })

request.interceptors.request.use(async (config) => {
  config.headers.Authorization = await buildSign()
  return config
})

request.interceptors.response.use((response) => {
  if (response.data.code == 0) {
    return response.data
  } else {
    const errorMsg = response.data.message?.global || '请求失败'
    message.error(errorMsg)
    return Promise.reject(response)
  }
}, (error) => {
  message.error('网络请求错误')
  return Promise.reject(error)
})

/**
 * 文件上传
 * https://cloud.baidu.com/doc/AI_DH/s/5m11r7clu
 */
export const upload = async (data, options = {}) => {
  const response = await request.post('/api/digitalhuman/open/v1/file/upload', data, {
    headers: { 'Content-Type': 'multipart/form-data' },
    ...options,
  })
  return response.result
}

// 获取数字人列表
export const getDigitalHumanList = async (params, options) => {
  const { systemFigure, item = 'VIDEO-DH_2D', pageSize = 1000 } = params
  const response = await request.get('/api/digitalhuman/open/v1/figure/query', {
    params: { systemFigure, item, pageSize },
    ...options,
  })
  return response.result?.result || []
}

/**
 * 提交生成式数字人形象定制任务
 */
export const submitGenerativeFigure = async (params, options = {}) => {
  return request.post('/api/digitalhuman/open/v1/figure/generative/train', params, options)
}

/**
 * 查询生成式数字人形象定制状态
 */
export const queryGenerativeFigure = async (params, options = {}) => {
  return request.get('/api/digitalhuman/open/v1/figure/lite2d/query', { params, ...options })
}

/**
 * 提交123数字人视频任务
 */
export const submitVideoFast = async (params, options = {}) => {
  return request.post('/api/digitalhuman/open/v1/video/submit/fast', params, options)
}

/**
 * 提交基础视频合成任务
 */
export const submitVideo = async (params, options = {}) => {
  return request.post('/api/digitalhuman/open/v1/video/submit', params, options)
}

/**
 * 查询视频任务状态
 */
export const getVideoTask = async (params, options = {}) => {
  return request.get('/api/digitalhuman/open/v1/video/task', { params, ...options })
}

/**
 * 提交高级视频合成任务
 */
export const submitVideoAdvanced = async (params, options = {}) => {
  return request.post('/api/digitalhuman/open/v1/video/advanced/submit', params, options)
}

/**
 * 查询高级视频任务状态
 */
export const getVideoAdvancedTask = async (params, options = {}) => {
  return request.get('/api/digitalhuman/open/v1/video/advanced/task', { params, ...options })
}
