/**
 * ai聊天模块
 */

import { ERRORENUM } from "../../config/errorEnum"
import { BizError } from "../../util/bizError"
import { cozeGet, cozePost, post } from "../../util/request"

const request = require('request')
const AK = "SjRG4fWy8ByvLSmpBX3X7zyl"
const SK = "vA1jj6TbQoY4bXqzgZBEewNoi1eZAFoS"

/**
 * 使用 AK，SK 生成鉴权签名（Access Token）
 * @return string 鉴权签名信息（Access Token）
 */
function getAccessToken() {

    let options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
    }
    return new Promise((resolve, reject) => {
        request(options, (error, response) => {
            if (error) { reject(error) }
            else { resolve(JSON.parse(response.body).access_token) }
        })
    })
}

export async function checkMsg(msg:string, preConditions?) {
    if (!preConditions) preConditions = [];
    let messages = [];
    preConditions.forEach(str => {
        messages.push({"role":"user", "content":str});
        messages.push({"role":"assistant", "content":"好的"});
    });
    messages.push({"role":"user", "content":msg});
    let access_token = await getAccessToken();
    var options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=' + access_token,
        'headers': {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({messages})
    };

    return new Promise((resolve, reject) => {
        request(options, function (error, response) {
            if (error) throw new Error(error);
            if (error) { 
                reject(error); 
            }
            else { 
                resolve(JSON.parse(response.body).result);
            }
        });
    })

   
}

/**
 * 字节智能体
 */
export async function cozeMsg(msg:string, conversationId:string, chatId:string, messageList) {
    let additional_messages = [];
    //拼接上下文
    let i = messageList.length <= 10 ? 0 : (messageList.length - 10)-1;
    for (; i < messageList.length; i++) {
        let {role, msg} = messageList[i];
        let type = role != 'user' ? 'question' : 'answer'
        additional_messages.push({
            role,
            type,
            content:msg,
            content_type:'text'
        });
    }

    /**请求头 */
    const Header = {
        Authorization:'Bearer pat_KORy65MIpPSGQ8cx4rLLipsAZhgjkk5neIv0o1IWKb2svC3t2RbECSMpSBHWyDuN',
        "Content-Type":"application/json"
    };
    const botId = '7395108996510089266';
    /**创建会话 */
    if (!conversationId) {
        let creatChartUrl = 'https://api.coze.cn/v1/conversation/create';
        let conversationRes:any = await cozePost(creatChartUrl, {}, Header);
        conversationId = conversationRes.data.id;
    }
    /**创建消息 */
    let messageBody = {
        role:'user',
        content:msg,
        content_type:"text"
    };
    let createMessageRes:any = await cozePost(`https://api.coze.cn/v1/conversation/message/create?conversation_id=${conversationId}`, messageBody, Header);
    //判断创建情况，如果消息创建失败，后面轮询会报错
    if (!createMessageRes.data) {
        throw new BizError(ERRORENUM.智能体调用出错请联系管理员, '创建消息失败');
    }

    /**发起对话 */
    let chatUrl = `https://api.coze.cn/v3/chat?conversation_id=${conversationId}`;
    let chatBody = {
        bot_id :botId,
        conversation_id:conversationId,
        user_id:"user",
        stream:false,
        auto_save_history:true,
        additional_messages
    };
    let chatResult:any = await cozePost(chatUrl, chatBody, Header);
    //判断创建情况，如果消息创建失败，后面轮询会报错
    if (!createMessageRes.data) {
        throw new BizError(ERRORENUM.智能体调用出错请联系管理员, '发起对话失败');
    }
    chatId = chatResult.data.id;


    /**查询对话状态 */
    let max = 100;
    for (let i = 0; i < max; i++) {
        await sleep(1000);
        let queryInfo = {conversation_id:conversationId, chat_id:chatId};
        // let itemUrl =`https://api.coze.cn/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
        let itemUrl =`https://api.coze.cn/v3/chat/retrieve`;
        let itemRes:any = await cozeGet(itemUrl, queryInfo, Header);
        console.log(`第${i+1}次等待`);
        if (!itemRes.data || !itemRes.data.status || itemRes.data.status == "failed") {
            throw new BizError(ERRORENUM.智能体调用出错请联系管理员, '轮询对话状态失败');
        }
        
        if (["completed","required_action","canceled","failed"].indexOf( itemRes.data.status) != -1) {
            break;
        }
    }

    /**查看消息列表 */
    let allres:any = await cozeGet('https://api.coze.cn/v3/chat/message/list', {conversation_id:conversationId, chat_id:chatId}, Header);
    if (!allres.data) throw new BizError(ERRORENUM.智能体调用出错请联系管理员, '查看消息列表失败');
    let msgList = allres.data;
    let resMsg = msgList[msgList.length -1 ].content;
    console.log(`提问：${msg}`, `回答：${resMsg}`);
    return {answer:resMsg, conversationId, chatId};
}

function sleep(time) {
    return new Promise((resolve, reject) => {
        setTimeout(()=> {
            resolve({});
        }, time);
    });
}
