import { request } from '@/utils/request'
import { getPageConfig } from './config'
import { 动爻数量 } from '@/utils/gua_64'
import { storeToRefs } from 'pinia'
import { useAIReponseStore, useTabStore } from '@/stores'
import * as TextEncoding from "text-encoding-shim";
import { watch } from 'vue'

const {
    responseText,
    showResponseText,
    isLoading,
    isDone
} = storeToRefs(useAIReponseStore())

const {
    tabIndex
} = storeToRefs(useTabStore())

const API_KEY = 'sk-b65f99c1b2ab416aaf340891cf4ca308'   // ds

const AI_URL = 'https://api.deepseek.com/chat/completions'
const AI_MODEL = 'deepseek-chat'

const errMessage = {
    401: 'API key 无效',
    403: 'API key 余额不足',
}

export const AIChat = async (
    q: string,            // 用户所问之事
    symbol_1: string,     // 本卦结果
    symbol_2: string,     // 变卦结果
    symbol_3: string,     // 动爻结果
    // count: number,     // 动爻数量
) => {
    const pageCfg = await getPageConfig()

    let callWord = pageCfg.call_word
    callWord = callWord
        .replace('[q]', q)
        .replace('[symbol_1]', symbol_1)
        .replace('[symbol_2]', symbol_2)
        .replace('[symbol_3]', symbol_3)

    console.log(callWord)

    // try {
    //     const requestTask = await StreamRequest({
    //         model: AI_MODEL,
    //         messages: [
    //             { role: "system", content: "You are a helpful assistant." },
    //             { role: "user", content: callWord }
    //         ],
    //         stream: true
    //     })
    //     requestTask.onHeadersReceived((e) => {
    //         console.log(e);
    //     })
    //     requestTask.onChunkReceived((e) => {
    //         console.log(e);
    //         const decoder = new TextDecoder('utf-8');
    //         const txt = decoder.decode(e.data);
    //         responseText.value = txt
    //     })
    // } catch (err) {
    //     console.log(err);
    // }

    return await new Promise<any>((resolve, reject) => {
        const requestTask: any = uni.request({
            url: AI_URL,
            method: 'POST',
            header: {
                'content-type': 'application/json',
                'Authorization': `Bearer ${API_KEY}`
            },
            data: {
                model: AI_MODEL,
                messages: [
                    { role: "system", content: "You are a helpful assistant." },
                    { role: "user", content: callWord }
                ],
                stream: true
            },
            enableChunked: true,
            responseType: 'arraybuffer',
            success: (res) => {
                if (res.statusCode !== 200) {
                    resolve({
                        code: res.statusCode,
                        message: errMessage[res.statusCode]
                    })
                }
                isDone.value = true
                // console.log('Data received 数据接受完毕:', res.data)
            },
            fail: (error) => {
                // console.log('打印***error 错误处理', error)
            },
            complete: (complete) => {
                // console.log('打印***complete 完成接收', complete)
            }
        } as any)

        requestTask.onChunkReceived(res => {
            const uint8Array = new Uint8Array(res.data);
            const decoder = new TextEncoding.TextDecoder("utf-8");
            const chunk = decoder.decode(uint8Array).toString().split('data: ')

            for (let i = 1; i < chunk.length; i++) {
                try {
                    const result = JSON.parse(chunk[i])
                    // console.log(result)
                    if (result.choices[0].delta.content) {
                        // showResponseText.value = true
                        isLoading.value = false
                        responseText.value += result.choices[0].delta?.content
                    }
                } catch (e) {}
            }
        })

        watch(
            () => tabIndex.value,
            (newVal, oldVal) => {
                if (newVal !== oldVal) {
                    requestTask.abort()
                    isLoading.value = false
                    responseText.value = ''
                    showResponseText.value = false
                    isDone.value = false
                    return
                }
            },
            {
                deep: true
            }
        )
    })
}