/**
 * 用于报告生成
 */

import { ERRORENUM } from "../../config/errorEnum";
import { findFuHuaQiList } from "../../data/fuHuaQi/fuhuaqi";
import { createChatInfo, selectChatInfo } from "../../data/guanWeiHui/chart";
import { BizError } from "../../util/bizError";
import { TARGET } from "./enum";
import { checkMsg, cozeMsg } from "./gpt";
import { getIndicationRate, getIndicationValueStr, getIndicationValue } from "./indicatorPool";

const officegen = require('officegen');
const fs = require('fs');
const path = require('path');

/**提问大纲 */
let outline = [];
export function initOutline() {
    outline = [
        { title:'概述', msg:"写一段话，概述孵化器的作用与意义来表达孵化器的重要性", removeParagraph:true },
        { title:'孵化器分析', msg:"请根据已知条件，从经济学的角度分析孵化器的运行情况，要求2000个字。", context:[fuHuaQiCombinationMessage()]},
        { title:'企业分析', msg:"请根据已知条件，从经济学的角度分析企业的运行情况， 要求2000个字。", context:[enterpriseCombinationMessage()]},
        { title:'改进与规划', msg:"请根据已知条件，从经济学的角度提出孵化器的不足和改进方向。", context:[fuHuaQiCombinationMessage(), enterpriseCombinationMessage()]}
    ];
}


/**
 * 生成报告
 * @param token 
 */
export async function generateReport() {
    
    // return {fileName:"2023年采集数据分析.docx", size:'17kb', url:'/doc/2023年采集数据分析.docx'};
    let docx = officegen('docx');
    let pObj = docx.createP();

    /**绑定事件 */
    docx.on('finalize', function(written) {
        console.log(
            '报告已生成'
        )
    });
    docx.on('error', function(err) {
        console.log(err)
    });

    /**生成大标题 */
    pObj.addText(`${new Date().getFullYear()}孵化器运行分析报告\n`,{ font_size:18, bold:true });

    let index = 1;
    for (let key in outline) {
        let {title, msg, context, removeParagraph} = outline[key];

        /**组合小标题 */
        pObj.addText(`${index}、${title}\n`, { font_size:16, bold:true });

        context = context || [];
        let chartStr:any = await checkMsg(msg, context);
        if (removeParagraph && chartStr) {
            let rmvList = chartStr.split('\n');
            let rmvStr = ``;
            rmvList.forEach(itemStr => {rmvStr += itemStr});
            chartStr = rmvStr;
        }

        pObj.addText('        '+chartStr+`\n`, { font_size:14 });

        index ++;
    }
   
    let out = fs.createWriteStream( path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", 'test.docx' ));
    docx.generate(out);
    return {isSuccess:true};
}

export async function zjAiChart(token:string) {
    let str = fuHuaQiCombinationMessage();
    let enterpriseStr = enterpriseCombinationMessage();
    let preConditions = [];
    preConditions.push(str);
    preConditions.push(enterpriseStr);
    let resultMsg:any = await checkMsg(token, preConditions);

    return {message:resultMsg};
}


export async function aiChart(userId:string, token:string, messageList) {
    if (!token) throw new BizError(ERRORENUM.请输入聊天内容);
    let chatInfo = await selectChatInfo(userId);
    if (!chatInfo || !chatInfo.userId) {
        await createChatInfo(userId);
        chatInfo = await selectChatInfo(userId);
    }
    let contextList = JSON.parse(chatInfo.additionalMessages);
    let {answer, chatId, conversationId} = await cozeMsg(token, chatInfo.conversationId, chatInfo.chatId, contextList);

    /**更新对话记录 */
    let newContextList = [];
    if (contextList.length >= 10) {
        for (let i = 2; i < contextList.length; i++) {
            newContextList.push(contextList[i]);
        }
    }
    newContextList.push({ role:'user', msg:token});
    newContextList.push({ role:'bot', msg:answer});
    chatInfo.additionalMessages = JSON.stringify(newContextList);

    /**更新参数 */
    chatInfo.chatId = chatId;
    chatInfo.conversationId = conversationId;
    chatInfo.conversationMs = new Date().valueOf();
    
    return {message:answer};
}


/**
 * 组合数据前置条件
 * 孵化器
 */
function fuHuaQiCombinationMessage() {
    const Unit = "家";
    let fhqCount = getIndicationValueStr(TARGET.孵化器数量, Unit);
    let str = `已知:上海张江共计${fhqCount}孵化器，`;
    str += `其中${getIndicationValueStr(TARGET.孵化器孵化领域分布, Unit)}，${fhqCount}孵化器中${getIndicationRate(TARGET.布局新模式孵化器占比)}。`;
    str += `共计${getIndicationValueStr(TARGET.创投基金数量, Unit)}孵化器成立创投基金。`;
    let rate = Math.ceil(getIndicationValue(TARGET.孵化器具备投资功能的数量和占比)/getIndicationValue(TARGET.孵化器数量)*10000)/100;
    str +=`${getIndicationValueStr(TARGET.孵化器具备投资功能的数量和占比, Unit)}孵化器具备投资功能，占比${rate}%，共计投融资${getIndicationValueStr(TARGET.孵化器投融资金额, "万元")}。`
    str +=`${getIndicationValueStr(TARGET.搭建专业技术平台的数量, Unit)}孵化器搭建专业技术平台，占比${getIndicationValueStr(TARGET.搭建专业技术平台的占比)}。`;
    str += `${fhqCount}家孵化器中，共有${getIndicationValue(TARGET.国际化合作数量)}个国际化合作。`;
    str += `${getIndicationValue(TARGET.创业导师数量)}个创业导师，在这${getIndicationValue(TARGET.创业导师数量)}个创业导师中，${getIndicationValueStr(TARGET.创业导师专业分布, "个")}。`
    str += `所有孵化器从业人员中：${getIndicationRate(TARGET.国际一流人才与国内一流人才占比)}。`;
    str +=`本年度孵化器总营收${getIndicationValue(TARGET.孵化器营收总金额)}元，其中${getIndicationValueStr(TARGET.孵化器营收季度趋势, "元")}。`;
    str +=`本年度孵化器纳税共计${getIndicationValue(TARGET.孵化器纳税金额)}元，其中${getIndicationValueStr(TARGET.孵化器纳税季度趋势, "元")}。`;
    return str;
}

function enterpriseCombinationMessage() {
    let str = `已知：孵化器已采集的${getIndicationValue(TARGET.企业总数)}家企业数据情况如下，行业领域分布：${getIndicationRate(TARGET.行业领域分布)}。`;
    str += `创业创新方向各类型分布:${getIndicationRate(TARGET.创业创新方向各类型占比)}。`;
    str += `在统计范围之内共有${getIndicationValueStr(TARGET.企业融资数量, '次')}融资行为，共计融资${getIndicationValueStr(TARGET.企业融资金额, '万元')}，`;
    str += `其中融资轮次分布情况：${getIndicationRate(TARGET.融资企业的融资轮次分布)}，`;
    let maxIn = getIndicationValue(TARGET.融资事件最多的领域);
    str += `融资行业领域占比${getIndicationRate(TARGET.融资行业领域占比)}，其中${maxIn["领域"]}领域融资事件最多，有${maxIn["次数"]}次。`;
    str += `其中融资最多企业金额和占比${getIndicationValue(TARGET.融资最多企业金额和占比)}。`;
    str += `在统计范围内共有上市企业${getIndicationValue(TARGET.上市企业数量)}家。`;
    str += `在统计范围内在孵企业的营收总额${getIndicationValue(TARGET.在孵企业营收总金额)}元，其中${getIndicationValueStr(TARGET.在孵企业营收季度趋势, "元")}，`;
    str += `在孵企业纳税总额${getIndicationValue(TARGET.在孵企业纳税金额)}元，其中${getIndicationValueStr(TARGET.在孵企业纳税季度趋势, "元")}，`;
    str += `在孵企业纳税总额${getIndicationValue(TARGET.在孵企业研发投入金额)}元，其中${getIndicationValueStr(TARGET.在孵企业研发投入季度趋势, "元")}。`;
    str += `在统计范围内企业资质情况${getIndicationRate(TARGET.企业资质占比)}。`;
    str += `在统计范围内企业专利情况${getIndicationRate(TARGET.企业专利占比)}。`;
    
    return str;
}


export async function test() {
    let chartStr:any = await checkMsg("分析当前所有再孵企业的行业优势", [enterpriseCombinationMessage()]);
    let str = "";
    if ( chartStr) {
        let rmvList = chartStr.split('\n');
        let rmvStr = ``;
        rmvList.forEach(itemStr => {rmvStr += itemStr});
        str = rmvStr;
    }
    console.log(str);
    console.log();

}