import CryptoJS from 'crypto-js'
import axios from 'axios'
import { API_KEY, API_SECRET, APPID } from './secret'
import { user } from '~/store/index'
// const total_res = '' // 保存回答历史

function getHttpUrl(): Promise<string> {
  return new Promise((resolve, reject) => {
    const apiKey = API_KEY
    const apiSecret = API_SECRET
    let url = 'https://spark-api.cn-huabei-1.xf-yun.com/v2.1/tti'
    const host = location.host
    // const host = url
    const date = new Date().toGMTString()
    // const date = Date.now()
    const algorithm = 'hmac-sha256'
    const headers = 'host date request-line'
    const signatureOrigin = `host: ${host}\ndate: ${date}\nPOST /v2.1/tti HTTP/1.1`
    const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret)
    const signature = CryptoJS.enc.Base64.stringify(signatureSha)
    const authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
    const authorization = btoa(authorizationOrigin)
    url = `${url}?authorization=${authorization}&date=${date}&host=${host}`
    // url = `${url}?authorization=${encodeURIComponent(authorization)}&date=${encodeURIComponent(date)}&host=${encodeURIComponent(host)}`
    console.log('getHttpUrl : ', authorizationOrigin, url)
    resolve(url)
  })
}

export function startTTI() {
  getHttpUrl().then((url) => {
    console.log('getHttpUrl : ', url)
    axios.post(url, {
      header: {
        app_id: APPID,
        uid: user.value?.user_id,
      },
      parameter: {
        chat: {
          domain: 'general',
          width: 512,
          height: 512,
        },
      },
      payload: {
        message: {
          text: [
            {
              role: 'user',
              content: '帮我画一座山',
            },
          ],
        },
      },
    }).then((res) => {
      console.log('res : ', res)
    })
  })
}
