import { defineStore } from 'pinia'
import { ElMessage, ElMessageBox } from 'element-plus'
import md from '@/assets/icons/aiBox/2.md?raw'

export const useWrittingAsstaintStore = defineStore('writtingAsstaint', {
    state: () => ({
        // 基础状态
        isGenerating: false,
        isShowProcess: false, // 初始隐藏执行步骤面板
        isShowSteps: false, // 步骤侧边栏显隐控制
        isShowClauseTranslation: false, // 翻译侧边栏显隐控制
        isEditMode: false,
        writtingTitle: '',
        descText: '',
        reportContent: '', // 报文内容（核心）
        curTempTitle: '政令',
        tempActiveIndex: 0,
        curAgentTool: '',
        uploadFileList: [],
        // 路由相关状态
        _isDisableTemplate: false,
        routeQuery: {},
        // 步骤日志（用于流式更新）
        processLog: '',

        // 条款翻译相关状态
        clauseTranslationMessages: [], // 存收到的条款翻译消息
        highlightClauseId: null, // 当前高亮的条款 ID (clause_number)
        isShowOriginal: true, // 是否显示原文内容
        pdfMetadata: null, // PDF 解析元数据

        // 静态数据
        tabList: [
            { name: '写报', active: true },
            { name: '收藏', active: false },
            { name: '问答', active: false }
        ],
        tempList: [
            { title: '政令', desc: '基于政令内容生成各维度的综合分析报告' },
            { title: '法案', desc: '基于政令内容生成各维度的综合分析报告' },
            { title: '智库', desc: '基于智库内容生成各维度的综合分析报告' },
            { title: '清单', desc: '基于清单内容生成各维度的综合分析报告' }
        ],

        // 内部控制器
        abortController: null,
        isShowSearchBar: false,
        searchBillText:'',
        searchData:{
            placeholder:'',
            areaName:'',
            containerRef:null
        },


        // ==================================
        // 显示全部进度
        isProcessLog:false,
        // ====头
        isSsearchFor:false,
        //list
        tabList:[
            {
                type:'translate',
                name:'翻译',
                active: true
            },
            {
                type:'mind',
                name:'思维导图',
                active: false
            },
            {
                type:'message',
                name:'写报',
                active: false
            }
        ],
        headerTabType:'translate',
        // 底部
        bottomProgressNum:0, //文档解析 假进度
        resultWriteData:null, //文档分析结束之后 写报使用
        // 写报
        isWriteStart:false,// 写报进行中
        processLogAlone:'', //写报步骤
        writeProgressNum:0, //写报 假进度
    }),

    getters: {
        isDisableTemplate: (state) => state._isDisableTemplate,

        formattedTime: () => {
            const now = new Date()
            const pad = n => n.toString().padStart(2, '0')
            return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`
        },
        
    },

    actions: {
        // ========== 基础状态修改 ==========
        toggleEditMode() {
            this.isEditMode = !this.isEditMode
        },
        // 设置navbar是否显示搜索框
        changeIsShowSearchBar(value){
            this.isShowSearchBar = value
        },
        setSearchData({placeholder,areaName,containerRef}){
            this.searchData.placeholder = placeholder
            this.searchData.areaName = areaName
            this.searchData.containerRef = containerRef
        },
        resetGenerateState() {
            
            this.isGenerating = false;
            this.isShowProcess = false;
            this.isShowSteps = false;
            this.curAgentTool = '';
            this.processLog = '';
            this.clauseTranslationMessages = [];
            this.pdfMetadata = null;
            this.isShowClauseTranslation = false;
            this.highlightClauseId = null;
            this.isShowOriginal = true;
            this.abortController?.abort();
            this.abortController = null;


            this.isProcessLog=false
            this.headerTabType='translate',
            // 底部
            this.bottomProgressNum=0, //文档解析 假进度
            this.resultWriteData=null, //文档分析结束之后 写报使用
            this.processLogAlone='', //写报步骤
            // 写报
            this.isWriteStart=false,// 写报进行中
            // this.processWriteLog='', //写报步骤
            this.writeProgressNum=0, //写报 假进度
            this.tabList[1].active=false
            this.tabList[2].active=false
            this.reportContent='' //写报内容
        },

        backToInputAndClear() {
            this.resetGenerateState();
            this.reportContent = '';
            this.writtingTitle = '';
            this.descText = '';
            this.uploadFileList = [];
            this.routeQuery = {};
            this._isDisableTemplate = false;
            this.curTempTitle = '政令';
            this.tempActiveIndex = 0;
        },

        updateTempActiveIndex(index, title) {
            this.tempActiveIndex = index;
            this.curTempTitle = title;
        },

        _keepStepsViewOnError() {
            this.isGenerating = false;
            this.isShowProcess = true;
            this.isShowSteps = true;
            this.abortController?.abort();
            this.abortController = null;
        },

        async _showErrorDialog(message) {
            await ElMessageBox.alert(message || '写报生成失败', '提示', {
                confirmButtonText: '确认',
                type: 'error'
            });
        },

        async _handleGenerateError(message) {
            this._keepStepsViewOnError();
            await this._showErrorDialog(message);
        },
        //header tab切换 
        async handleHeaderTab(type){
            this.headerTabType=type
        },
        // 关闭搜索栏
        handleIsSsearchFor(){
            this.isSsearchFor=!this.isSsearchFor
        },
        // 智能写报
        async generateWrite(){
            this.isWriteStart=true
            
            // const obj={}
            // await this.fetchReportData(obj);
            // this.isShowClauseTranslation=true
            // this.headerTabType='message'


            // this.reportContent=md
            // this.tabList[2].active=true //写报生成之后放开写报按钮
            // this.bottomProgressNum=100
            // this.writeProgressNum=100 //写报假进度
            // this.headerTabType='message'



            await this.fetchReportData({
                query: this.writtingTitle,
                desc: this.descText,
                topic: this.curTempTitle,
                result: this.resultWriteData
            });

        },
        // 停止写报
        writeGenerateState(){
            // this.bottomProgressNum=100
            this.headerTabType='translate'
            this.writeProgressNum=0
            this.processLogAlone=''
            this.tabList[2].active=false
            this.abortController.abort()
        },

        // ========== 路由参数处理 ==========
        async setRouteParams(query) {
            this.routeQuery = { ...query };
            this._isDisableTemplate = Object.keys(query).length > 0;

            if (Object.keys(query).length > 0) {
                const { topic, fileId } = query;
                if (topic) {
                    this.curTempTitle = topic;
                    this.tempActiveIndex = this.tempList.findIndex(item => item.title === topic);
                }

                // 如果携带 fileId：外部跳转仅回填/锁定参数，不自动生成
                if (fileId) {
                    this.curTempTitle = topic || '政令';
                    this.tempActiveIndex = this.tempList.findIndex(item => item.title === this.curTempTitle);

                    // 初始标题设为空，待点击生成后从接口获取并清洗
                    this.writtingTitle = '';
                }
            }
        },

        // ========== 内部工具函数 (抽取的公共逻辑) ==========
        _cleanTitle(title) {
            return (title || '').replace(/[^\u4e00-\u9fa5]/g, '');
        },

        async _fetchBusinessData({ url, payload, typeName }) {
            this.isGenerating = true;
            this.isShowProcess = true;
            this.processLog = `${this.formattedTime}:正在获取${typeName}数据...\r\n`;

            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });

                const data = await response.json();

                if (data.status === 'success' && data.result) {
                    this.processLog += `${this.formattedTime}:${typeName}数据获取成功，开始生成写报...\r\n`;
                    
                    // 清洗标题
                    this.writtingTitle = this._cleanTitle(data.result['报告标题']);
                    
                    // 触发 AI 生成
                    await this.fetchReportData({
                        query: this.writtingTitle,
                        desc: this.descText,
                        topic: this.curTempTitle,
                        result: data.result
                    });
                } else {
                    throw new Error(data.error_log?.join(', ') || `获取${typeName}数据失败`);
                }
            } catch (error) {
                console.error(`获取${typeName}数据异常:`, error);
                await this._handleGenerateError(`获取${typeName}数据失败: ${error.message}`);
            }
        },

        // ========== 获取政令基础信息 (翻译栏数据) ==========
        async fetchOrderBaseInfo(orderId) {
            try {
                const response = await fetch('/reportData/get-order-base-info', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ order_id: Number(orderId) })
                });
                const data = await response.json();
                if (data.status === 'success' && data.result) {
                    const res = data.result;
                    
                    // 1. 填充元数据 (用于翻译栏顶部的标题卡片)
                    this.pdfMetadata = {
                        name: res.order_name_zh,
                        order_title: res.order_name,
                        signing_date: res.post_date
                    };

                    // 2. 填充条款翻译内容
                    this.clauseTranslationMessages = (res.clauses || []).map(item => ({
                        event: 'clause_translation',
                        payload: {
                            clause_number: item.section_num,
                            clause_section: item.section_num, // 这里根据结构复用 section_num
                            clause_content: item.section_text,
                            clause_content_zh: item.section_text_zh
                        }
                    }));

                    // 3. 自动展示翻译栏
                    this.isShowClauseTranslation = true;
                    this.isShowSteps = true;

                    console.log('政令基础信息获取并回填成功:', res);
                }
            } catch (error) {
                console.error('获取政令基础信息失败:', error);
            }
        },

        // ========== 获取业务数据并触发生成 (业务封装) ==========
        async fetchOrderReportData(orderId) {
            await this._fetchBusinessData({
                url: '/reportData/get-order-report-data',
                payload: { order_id: Number(orderId) },
                typeName: '政令'
            });
        },

        async fetchBillReportData(billId) {
            await this._fetchBusinessData({
                url: '/reportData/get-bill-report-data',
                payload: { bill_id: billId },
                typeName: '法案'
            });
        },

        async fetchListReportData(sancDate) {
            await this._fetchBusinessData({
                url: '/reportData/get-sanc-list-report-data',
                payload: { sanc_date: sancDate },
                typeName: '实体清单'
            });
        },

        // ========== 文件上传相关 ==========
        handleExceed(files, uploadRef) {
            if (uploadRef) {
                uploadRef.clearFiles();
                const file = files[0];
                file.uid = Date.now();
                uploadRef.handleStart(file);
            }
        },

        handleFileChange(file, files) {
            this.uploadFileList = files.length > 1 ? [file] : files;
        },

        // ========== PDF 解析 SSE（仅更新执行步骤） ==========
        async fetchPdfData(selectedFile) {
            if (this.abortController) this.abortController.abort();
            this.abortController = new AbortController();
            this.processLog = '';

            // 进度初始化1
            this.bottomProgressNum=1
            try {
                const formData = new FormData();
                formData.append('pdf', selectedFile);

                const { fetchEventSource } = await import('@microsoft/fetch-event-source');
                await fetchEventSource('/pdfSse/api/v1/order/pdf/extract/report/sse', {
                    method: 'POST',
                    body: formData,
                    signal: this.abortController.signal,
                    headers: { Accept: 'text/event-stream', 'Cache-Control': 'no-cache' },
                    openWhenHidden: true,
                    retryDelay: 1000,
                    maxRetries: 3,
                    onopen: async (response) => {
                        if (response.ok && response.headers.get('content-type')?.includes('text/event-stream')) {
                        } else {
                            ElMessage.warning('SSE连接格式异常，即将断开');
                            this.abortController.abort();
                        }
                    },
                    onmessage: async (event) => {
                        console.log(event)
                        if (!event || !event.data || event.data.trim() === '') return;

                        let jsonData = null;
                        try {
                            jsonData = JSON.parse(event.data.trim());
                        } catch (parseError) {
                            console.warn('SSE消息JSON解析失败', parseError, event.data);
                            return;
                        }
                        
                        switch (event.event) {
                            case 'progress':
                                // 仅更新执行步骤
                                if (jsonData.message) {
                                    this.processLog += `${this.formattedTime}:${jsonData.message}\r\n`;
                                    this.processLogAlone=`${this.formattedTime}:${jsonData.message}\r\n`;
                                }
                                this.bottomProgressNum+=1
                                break;
                            case 'metadata':
                                if (jsonData && jsonData.payload) {
                                    this.pdfMetadata = jsonData.payload;
                                }
                                if(this.bottomProgressNum<90){
                                    this.bottomProgressNum+=5
                                }
                                break;
                            case 'clause_translation':
                                // 保存条款翻译消息并显示侧边栏
                                if (jsonData) {
                                    this.clauseTranslationMessages.push(jsonData);
                                    this.isShowClauseTranslation = true;
                                    this.isShowSteps = true; // 翻译出现时，步骤侧边栏也显示

                                    // 假进度
                                    if(this.bottomProgressNum<90){
                                        this.bottomProgressNum+=5
                                    }
                                }
                                break;
                            case 'result':
                                if (jsonData && Object.keys(jsonData).length) {
                                    this.bottomProgressNum=100 // 假进度完成
                                    this.resultWriteData=jsonData //给写报使用
                                    this.tabList[1].active=true //放开思维导图
                                    this.processLogAlone = `点击查看`; 
                                    // await this.fetchReportData({
                                        // query: this.writtingTitle,
                                        // desc: this.descText,
                                        // topic: this.curTempTitle,
                                        // result: jsonData
                                    // });
                                }
                                break;
                            case 'error':
                                await this._handleGenerateError(jsonData.message);
                                break;
                            default:
                                console.debug('未处理的SSE事件类型', event.event);
                                break;
                        }
                    },
                    onerror: async (error) => {
                        console.error('SSE连接错误', error);
                        if (error.name !== 'AbortError') {
                            await this._handleGenerateError('写报生成报错!');
                            return true;
                        }
                        this.resetGenerateState();
                    },
                    onclose: () => {
                        this.bottomProgressNum=100 // 假进度完成
                        console.log('SSE连接正常关闭');
                        this.isGenerating = false;
                    }
                });
            } catch (error) {
                if (error.name !== 'AbortError') {
                    console.error('PDF SSE请求异常', error);
                    await this._handleGenerateError(`PDF解析请求失败：${error.message}`);
                    throw error;
                }
                this.resetGenerateState();
                throw error;
            }
        },

        // ========== AI 生成报文 SSE（更新报文内容 + 执行步骤） ==========
        async fetchReportData(params) {
            console.log(">")
            if (this.abortController) this.abortController.abort();
            this.abortController = new AbortController();
            // this.processLog = '';
            // this.processLogAlone=''
            this.writeProgressNum=1


            // 用于把 SSE 的分片内容先聚合，再按“句子/段落边界”一次性提交到 reportContent
            // 这样可以还原老版“一句完整再显示”的渲染效果，避免分片逐条渲染
            let streamBuffer = '';
            let lastFlushedIndex = 0;

            const flushToReport = (force = false) => {
                // 强制 flush 时，把剩余 buffer 全部提交；否则只提交到 lastFlushedIndex
                const endIndex = force ? streamBuffer.length : lastFlushedIndex;
                if (endIndex <= 0) return;

                const chunk = streamBuffer.slice(0, endIndex);
                if (!chunk) return;

                this.reportContent += chunk;
                streamBuffer = streamBuffer.slice(endIndex);
                lastFlushedIndex = 0;

                if (this.reportContent.includes('./out/img')) {
                    this.reportContent = this.reportContent.replaceAll('./out/img', 'http://172.19.21.9:8003/out/img');
                }
            };

            // 尝试找到一个“合适的边界”再 flush：
            // 1) 中文/英文句末标点 + 可选换行
            // 2) 双换行（段落）
            // 3) markdown 列表/标题等常见行结束
            const updateFlushIndexByBoundary = () => {
                // 优先按段落（双换行）
                const paraIdx = streamBuffer.lastIndexOf('\n\n');
                if (paraIdx !== -1) {
                    lastFlushedIndex = Math.max(lastFlushedIndex, paraIdx + 2);
                }

                // 其次按句末标点
                // eslint-disable-next-line no-useless-escape
                const sentenceRe = /[。！？!?；;](?:\s|\n|$)/g;
                let m;
                while ((m = sentenceRe.exec(streamBuffer)) !== null) {
                    lastFlushedIndex = Math.max(lastFlushedIndex, m.index + m[0].length);
                }

                // 再次按单行结束（避免长时间不刷新）
                const lineIdx = streamBuffer.lastIndexOf('\n');
                if (lineIdx !== -1 && streamBuffer.length > 200) {
                    lastFlushedIndex = Math.max(lastFlushedIndex, lineIdx + 1);
                }
            };
            try {
                const { fetchEventSource } = await import('@microsoft/fetch-event-source');
                await fetchEventSource('/sseWrite/api/v1/workflow/invoke', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(params),
                    signal: this.abortController.signal,
                    openWhenHidden: true,
                    onopen: (res) => {
                        console.log('流式回答开始', res);
                        
                    },
                    onmessage: (res) => {
                        if (!res.data) return;

                        let msgData;
                        try {
                            msgData = JSON.parse(res.data);
                        } catch (e) {
                            return;
                        }

                        const str = msgData.data || '';
            
                        
                        if (msgData.event_type === 'stream_agent_out') {
                            if (str !== '[DONE]') {
                                // SSE 分片先进入 buffer（仅用于报文内容）
                                streamBuffer += str;
                                updateFlushIndexByBoundary();
                                flushToReport(false);
                                console.log(streamBuffer,456)
                                console.log(msgData,'data')
                            } else {
                                // 结束时把剩余内容强制 flush
                                flushToReport(true);
                                this.isGenerating = false;
                                this.isShowSteps = false; // 报文生成结束后关闭步骤侧边栏
                                ElMessage.success('报文生成结束');

                                
                                this.writeProgressNum=100 //写报假进度
                                this.processLogAlone= '点击查看';

                                // 这里不再调用 resetGenerateState，因为可能需要保留翻译内容
                            }
                        } else if (msgData.event_type === 'workflow_complete') {
                            // complete 也做一次强制 flush，避免尾巴丢失
                            flushToReport(true);
                            this.isGenerating = false;
                            this.isShowSteps = false; // 报文生成结束后关闭步骤侧边栏
                            ElMessage.success('报文生成结束');
                            
                            this.tabList[2].active=true //写报生成之后放开写报按钮
                            this.writeProgressNum=100 //写报假进度
                            this.processLogAlone= '点击查看';
                        } else if ((msgData.event_type || '').toLowerCase().includes('error')) {
                            // 优先从 data.error 获取详细错误描述
                            const errorMsg = msgData.data?.error || str || '生成失败';
                            this._handleGenerateError('生成失败：' + errorMsg);
                        } else {
                            // 老版 --index.vue 行为：步骤栏直接追加服务端发来的完整步骤内容，不加时间戳、不强行换行
                            // 这样可以避免 SSE 分片导致的“步骤破碎”（一条步骤被拆成多条显示）
                            if (str) {
                                this.processLog += str;
                                this.processLogAlone+= str;
                                if(this.writeProgressNum<=90){
                                    this.writeProgressNum+=0.05
                                }
                            }
                            this.curAgentTool = msgData.tool || '无';
                        }
                    },
                    onerror: async (error) => {
                        await this._handleGenerateError('写报生成报错!');
                        throw new Error(error);
                    }
                });
            } catch (error) {
                if (error.name !== 'AbortError') {
                    await this._handleGenerateError(error.message || '写报生成报错!');
                } else {
                    this.resetGenerateState();
                }
                throw error;
            }
        },

        // ========== 业务入口 ==========
        async generateReport() {
            this.bottomProgressNum=1
            if (Object.keys(this.routeQuery).length !== 0) {
                // 路由参数优先
                

                const { fileId } = this.routeQuery;

                // 外部跳转：根据 topic 决定调用哪种数据获取接口，再触发生成
                if (fileId) {
                    this.isGenerating = true;
                    this.isShowProcess = true;
                    if (this.curTempTitle === '法案') {
                        await this.fetchBillReportData(fileId);
                    } else if (this.curTempTitle === '清单') {
                        await this.fetchListReportData(fileId);
                    } else {
                        // 政令：先获取基础信息(用于翻译栏)，再获取写报数据并生成
                        await this.fetchOrderBaseInfo(fileId);
                        await this.fetchOrderReportData(fileId);
                    }
                    return;
                }

                // 兼容：若仅有 routeQuery 但无 fileId，则直接走原生成接口

                const params = {
                    query: this.writtingTitle,
                    desc: this.descText,
                    topic: this.curTempTitle,
                    report_id: fileId
                };
                await this.fetchReportData(params);
            } else {
                console.log(10101010101010)
                // 政令模板需要先解析PDF
                if (this.curTempTitle === '政令') {
                    if (this.uploadFileList.length === 0) {
                        throw new Error('请上传政令文件');
                    }
                    const rawFile = this.uploadFileList[0].raw;
                    if (!rawFile) {
                        throw new Error('文件解析失败，请重新选择');
                    }
                    await this.fetchPdfData(rawFile);
                } else {
                    // 路由参数优先
                    this.isGenerating = true;
                    this.isShowProcess = true;
                    const params = {
                        query: this.writtingTitle,
                        desc: this.descText,
                        topic: this.curTempTitle
                    };
                    await this.fetchReportData(params);
                }
            }
        },

        // ========== 导出Markdown ==========
        exportContent() {
            if (!this.reportContent) {
                ElMessage.warning('暂无可导出的报文内容');
                return;
            }
            const blob = new Blob([this.reportContent], { type: 'text/markdown' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `markdown-${new Date().getTime()}.md`;
            a.click();
            URL.revokeObjectURL(url);
        },

        // ========== 清理 ==========
        cleanup() {
            this.resetGenerateState();
        }
    }
});
