import CryptoJS from 'crypto-js'
import { ref } from 'vue'
import { API_KEY, API_SECRET, APPID } from './secret'
import RecorderManager from './other/recorder.esm.js'

export const recorder = new RecorderManager('/sdk/recorder')
recorder.onStart = () => {
  changeIatStatus('OPEN')
}

let iatWS: any
let resultText = ''
let resultTextTemp = ''
export const iatStatus = ref('UNDEFINED')

function changeIatStatus(status) {
  iatStatus.value = status
  if (status === 'CONNECTING') {
    resultText = ''
    resultTextTemp = ''
    iatWS?.onWillResultStart && iatWS?.onWillResultStart()
  }
}

function getWebSocketUrl() {
  // 请求地址根据语种不同变化
  let url = 'wss://iat-api.xfyun.cn/v2/iat'
  const host = location.host
  const apiKey = API_KEY
  const apiSecret = API_SECRET
  const date = new Date().toGMTString()
  const algorithm = 'hmac-sha256'
  const headers = 'host date request-line'
  const signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2/iat 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}`
  return url
}

function toBase64(buffer) {
  let binary = ''
  const bytes = new Uint8Array(buffer)
  const len = bytes.byteLength
  for (let i = 0; i < len; i++)
    binary += String.fromCharCode(bytes[i])

  return window.btoa(binary)
}

function renderResult(resultData) {
  // 识别结束
  const jsonData = JSON.parse(resultData)
  if (jsonData.data && jsonData.data.result) {
    const data = jsonData.data.result
    let str = ''
    const ws = data.ws
    for (let i = 0; i < ws.length; i++)
      str = str + ws[i].cw[0].w

    // 开启wpgs会有此字段(前提：在控制台开通动态修正功能)
    // 取值为 "apd"时表示该片结果是追加到前面的最终结果；取值为"rpl" 时表示替换前面的部分结果，替换范围为rg字段
    if (data.pgs) {
      if (data.pgs === 'apd') {
        // 将resultTextTemp同步给resultText
        resultText = resultTextTemp
      }
      // 将结果存储在resultTextTemp中
      resultTextTemp = resultText + str
    }
    else {
      resultText = resultText + str
    }
    iatWS?.onWillResultChange(resultTextTemp || resultText || '')
  }
  if (jsonData.code === 0 && jsonData.data.status === 2) {
    iatWS.close()
    iatWS?.onWillResultFinish(resultTextTemp || resultText || '')
  }

  if (jsonData.code !== 0) {
    iatWS.close()
    console.error(jsonData)
  }
}

export function connectIatWS() {
  const websocketUrl = getWebSocketUrl()
  if ('WebSocket' in window) {
    iatWS = new WebSocket(websocketUrl)
  }
  else if ('MozWebSocket' in window) {
    iatWS = new MozWebSocket(websocketUrl)
  }
  else {
    alert('浏览器不支持WebSocket')
    return
  }
  changeIatStatus('CONNECTING')
  iatWS.onopen = (e) => {
    // 开始录音
    recorder.start({
      sampleRate: 16000,
      frameSize: 1280,
    })
    const params = {
      common: {
        app_id: APPID,
      },
      business: {
        language: 'zh_cn',
        domain: 'iat',
        accent: 'mandarin',
        vad_eos: 5000,
        dwa: 'wpgs',
      },
      data: {
        status: 0,
        format: 'audio/L16;rate=16000',
        encoding: 'raw',
      },
    }
    iatWS.send(JSON.stringify(params))
  }
  iatWS.onmessage = (e) => {
    renderResult(e.data)
  }
  iatWS.onerror = (e) => {
    console.error(e)
    recorder.stop()
    changeIatStatus('CLOSED')
  }
  iatWS.onclose = (e) => {
    recorder.stop()
    changeIatStatus('CLOSED')
  }

  return iatWS
}

recorder.onFrameRecorded = ({ isLastFrame, frameBuffer }) => {
  if (iatWS.readyState === iatWS.OPEN) {
    iatWS.send(
      JSON.stringify({
        data: {
          status: isLastFrame ? 2 : 1,
          format: 'audio/L16;rate=16000',
          encoding: 'raw',
          audio: toBase64(frameBuffer),
        },
      }),
    )
    if (isLastFrame)
      changeIatStatus('CLOSING')
  }
}
recorder.onStop = () => {
  //
}

// function () {
//   if (iatStatus.value === 'UNDEFINED' || iatStatus.value === 'CLOSED') {
//     connectIatWS()
//   }
//   else if (iatStatus.value === 'CONNECTING' || iatStatus.value === 'OPEN') {
//     // 结束录音
//     recorder.stop()
//   }
// }
