/*
 * @Author: xuchaozou 52873083+xuchaozou@users.noreply.github.com
 * @Date: 2024-03-27 18:53:57
 * @LastEditors: xuchaozou 52873083+xuchaozou@users.noreply.github.com
 * @LastEditTime: 2024-11-06 17:53:16
 * @FilePath: \CivWeb\src\components\SoundAi\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { request, event } from '@wisdom-utils/utils'
import { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react'
import Context, { contextData } from './config'

const PandaUi = lazy(() => import("./PandaUi"))

const SoundAi = props => {
  const keyRef = useRef(null)
  const [visible, setVisible] = useState(false)
  const [globalConfig, setGlobalConfig] = useState(contextData())
  useEffect(async () => {
    try {
      await getKey()
      await getIsOpenConfig()
      setVisible(true)
    } catch (error) {
      
      console.warn(error)
    }
    return () => {
    }
  }, [])

  const getIsOpenConfig = () => new Promise((resolve, reject) => {
    request("/PandaOMS/OMS/DataManger/GetDicConfigs", {
      params: {
        ParentName: "智能语音",
        ChilName: "是否开启,是否开启人机交互,是否开启系统语音"
      }
    }).then(res => {
      if (res.code != 0) {
        reject("没有配置智能语音此条目")
        return
      }
      const data = res.data
      const config = data.find(item => item.nodeName == "是否开启")
      if (!config) {
        reject("没有配置是否开启字段")
      }
      const value = config.nodeValue
      if (value != "开") {
        reject("字段开启字段值为空")
        return
      }
      const spark = data.find(item => item.nodeName == "是否开启人机交互")
      keyRef.current['isOpenSparkModel'] = !!(spark && spark.nodeValue == "开")
      const systemSound = data.find(item => item.nodeName == "是否开启系统语音")
      keyRef.current['isOpenSystemSound'] = !!(systemSound && systemSound.nodeValue == "开")
      setGlobalConfig(globalConfig => globalConfig.set("key", {...keyRef.current}))
      resolve()
    }).catch(error => {
      reject(error)
    })
  })

  const getKey = () => new Promise((resolve, reject) => {
    fetch("https://civgis.panda-water.cn/system/pandaAiSoundWorker/key.json", {
      mode: "cors"
    }).then(res => res.json())
      .then(res => {
        keyRef.current = res
        resolve(res)
      }).catch(error => {
        reject(error)
      })
  })


  return (<>
    {
      visible && globalConfig.get("key") ? <Context.Provider value={{ globalConfig, setGlobalConfig }}>
        <Suspense fallback={<></>}>
          <PandaUi />
        </Suspense>
      </Context.Provider> : null
    }
  </>)
}

export default SoundAi