<script setup lang="ts">
import noticeIcon from "@/assets/ai/noticeIcon.svg";
// @ts-ignore
import RobotDialogueBox from "./components/RobotDialogueBox.vue";

import { nextTick, onMounted, reactive, ref, watch } from "vue";
import openAi, { OpenAI } from "openai";
import "./index.less";
import { ElLoading, ElMessage } from "element-plus";
import { marked } from "marked";
import axios from "axios";
import {
  getFieldEnumTree,
  handleGetANALYSISRULEList,
  handleGetPROMPTList,
  handleSynchroPROMPT,
} from "./service";
import moment from "moment";
import pageBg from '../../assets/pageBg.png'




const userInput = ref();
const loading = ref();
const error = ref();
const response = ref();
const responseText = ref("");
const descResponseText = ref("");
const aliyunresponseText = ref("");
const aliyundescResponseText = ref("");
const deepseekresponseText = ref("");
const deepseekdescResponseText = ref("");
// 对话框的实例
const RobotDialogueBoxRef = ref();
const boxContentBoxRef = ref();
// 存储所有请求的控制器
const controllers = ref<AbortController[]>([]);
// 显示终止按钮
const showController = ref<boolean>(false);
// 当前的滚动条list
const scrollList = reactive<any>([]);

const messageList = reactive<any>([]);
const aliyunMessageList = reactive<any>([]);
let deepseekMessageList = reactive<any>([]);

// 是否开启自由定义
const startFree = ref<boolean>(false);
// 自由定义的文本内容
const freeContent = ref<string>("");

const maxTokens = ref<number>(4096);
const Temperature = ref<number>(0.4);
const TopP = ref<number>(0.4);
const TopK = ref<number>(40);
const FrequencyPenalty = ref<number>(0);
// 是否加上问题的后缀
const RoleDescription = ref<boolean>(false);
// 是否显示阿里云对话框
const showAliYun = ref<boolean>(false);
// 是否显示deepseek的对话框
const showDeepseek = ref<boolean>(true);
// 是否引入地图的数据
const useMapData = ref<boolean>(true);
// 几个大模型种类的切换
const modalTypeSelect = ref<number[]>([2, 4]);
// 几个模型的具体数据
let modalTypeDataList = reactive<any>([
  {
    label: "Deepseek",
    value: 1,
    messageList: [],
    isShow: false,
    responseText: "",
    descResponseText: "",
    showCopy: false,
    showReload: false,
  },
  {
    label: "硅基流动",
    value: 2,
    messageList: [],
    isShow: true,
    responseText: "",
    descResponseText: "",
    showCopy: false,
    showReload: false,
  },
  {
    label: "阿里云",
    value: 3,
    messageList: [],
    isShow: false,
    responseText: "",
    descResponseText: "",
    showCopy: false,
    showReload: false,
  },
  {
    label: "通义千问",
    value: 4,
    messageList: [],
    isShow: true,
    responseText: "",
    descResponseText: "",
    showCopy: false,
    showReload: false,
  },
]);
// 是否显示左侧
const hideLeft = ref<boolean>(true);
// 省略过程
const omitProcess = ref<boolean>(false);
// 左侧的筛选条件的tab显示的内容
const leftTabShow = ref<string>("first");
// 页面类型 通过来自哪里 来存值    0 本身  1 云南大屏
const pageType = ref<number>(0)

// deepseek版本的更换
const options = [
  { label: "DeepSeek-V3", value: 1 },
  { label: "DeepSeek-R1", value: 2 },
];
// 当前选择的deepseek版本
const selectDeepseekVersion = ref<number>(1);
// 判断是否为手机
const isPhone = ref<boolean>(false);
// 显示手机端设置
const showPhoneOption = ref<boolean>(false);

// 驿商语义解析 角色
let YSRole = ref<any>({
  title: "",
  desc: "",
  content: "",
});

// 路由角色说明
let routerRole = ref<any>({
  title: "",
  desc: "",
  content: "",
});



onMounted(async () => {
  let param1: string = ""
  if (/Mobi|Android/i.test(navigator.userAgent)) {
    console.log("是手机");
    isPhone.value = true;
    // 只显示一个对话框
    modalTypeSelect.value = [4];
  }
  console.log('modalTypeDataListmodalTypeDataList', modalTypeDataList);

  if (modalTypeDataList && modalTypeDataList.length > 0) {
    modalTypeDataList.forEach((item: any) => {
      if (modalTypeSelect.value.indexOf(item.value) !== -1) {
        item.isShow = true;
      } else {
        item.isShow = false;
      }
    });
  } else {
    const urlParams = new URLSearchParams(window.location.search);
    param1 = urlParams.get('comeForm') || "";
    console.log("comeForm", param1);
    if (param1 === 'YNMap') {
      pageType.value = 1
      hideLeft.value = false
      modalTypeSelect.value = [2];
      if (modalTypeDataList && modalTypeDataList.length > 0) {
        modalTypeDataList.forEach((item: any) => {
          if (modalTypeSelect.value.indexOf(item.value) !== -1) {
            item.isShow = true;
          } else {
            item.isShow = false;
          }
        });
      }
    }
  }

  const PROMPT_TYPE = await getFieldEnumTree({
    FieldExplainField: "PROMPT_TYPE",
    sessionName: "PROMPT_TYPE",
  });
  let PROMPT_TYPEobj: any = {};
  if (PROMPT_TYPE && PROMPT_TYPE.length > 0) {
    PROMPT_TYPE.forEach((item: any) => {
      PROMPT_TYPEobj[item.value] = item.label;
    });
  }

  const list: any = await handleGetPrompt();

  if (list && list.length > 0) {
    list.forEach((item: any) => {
      if (item.PROMPT_TYPE === 1000) {
        let obj: any = {
          ...item,
          title: PROMPT_TYPEobj[item.PROMPT_TYPE],
          desc: item.PROMPT_DESC,
          content: item.PROMPT_CONTENT,
        };
        YSRole.value = obj;
      } else if (item.PROMPT_TYPE === 2000) {
        let obj: any = {
          ...item,
          title: PROMPT_TYPEobj[item.PROMPT_TYPE],
          desc: item.PROMPT_DESC,
          content: item.PROMPT_CONTENT,
        };
        routerRole.value = obj;
      }
    });
  }

  // 如果是云南大屏 就先清除路由解析中的文字
  // if (param1 === 'YNMap') {
  //   routerRole.value.content = ""
  // }

  console.log("YSRole", YSRole);
  console.log("routerRole", routerRole);
});

const showPhoneChange = ref<boolean>(false);

// 显示手机端设置的悬浮框 显示
const handleShowPhoneOption = () => {
  nextTick(() => {
    showPhoneOption.value = true;
  });
};

// 手机端切换模型的显示
const handleShowPhoneChangeBox = () => {
  nextTick(() => {
    showPhoneChange.value = true;
  });
};
// 关闭手机切换模型的显示
const handleClosePhoneMeng = () => {
  nextTick(() => {
    showPhoneChange.value = false;
    showPhoneOption.value = false;
  });
};
// 切换模型
const handlePhoneChangeModal = (bigObjValue: number) => {
  if (modalTypeDataList && modalTypeDataList.length > 0) {
    modalTypeDataList.forEach((item: any) => {
      if (item.value === bigObjValue) {
        item.isShow = true;
      } else {
        item.isShow = false;
      }
    });
  }

  showPhoneChange.value = false;
  modalTypeSelect.value = [bigObjValue];
};

// 提示词列表请求方法
const handleGetPrompt = async () => {
  let req: any = {
    PageIndex: 1,
    pagesize: 999999,
    searchParameter: {
      current: 1,
      pageSize: 10,
    },
    sortstr: "OPERATE_DATE desc",
  };
  const data = await handleGetPROMPTList(req);
  console.log("data", data);
  return data.List;
};

// 更新提示词
const handleUpdatePrompt = async (id: number) => {
  console.log("id", id);
  console.log("YSRole.value", YSRole.value);

  let req: any = {};
  if (id === 1000) {
    req = {
      ...YSRole.value,
      PROMPT_CONTENT: YSRole.value.content,
      OPERATE_DATE: moment().format("YYYY-MM-DD HH:mm:ss"),
    };
  } else if (id === 2000) {
    req = {
      ...routerRole.value,
      PROMPT_CONTENT: routerRole.value.content,
      OPERATE_DATE: moment().format("YYYY-MM-DD HH:mm:ss"),
    };
  }
  console.log("req", req);
  const data = await handleSynchroPROMPT(req);
  if (data.Result_Code === 100) {
    ElMessage({
      message: "更新成功",
      type: "success",
    });
  } else {
    ElMessage.error(data.Result_Desc);
  }
};

// 引入地图数据的角色说明的前缀
const mapDescPrefix = ref<string>(
  `你是服务区商业经营专家，请结合问题解析关键字和用户的提问，严谨分析JSON字段内容，给出经营数据分析总结，无需建议，注意段落区分，字数控制200以内。`
);
// 请分析以下 JSON 数据或字符，并生成一段简介精炼、具体直观的总结，适用于客户阅读：
// 1、提炼核心信息，避免冗余，保证逻辑清晰。
// 2、使用 Markdown 格式展示，以便直观呈现。
// 3、重点突出关键数据、结论或建议，让客户易于理解。
// 4、如果内容涉及多个方面，分点说明，条理清晰。
// 5、请使用正式、专业的语言，避免口语化表述。

// 37 接口地址: EShangApiMain/BusinessProject/GetAccountWarningList,
// 21 接口地址: CommercialApi/Revenue/GetMonthlyBusinessAnalysis,
// 29 接口地址: EShangApiMain/BusinessProject/GetPeriodWarningList,
// 2  接口地址: EShangApiMain/BusinessProject/GetAccountWarningList,
// 35 接口地址: EShangApiMain/Finance/GetContractExcuteAnalysis,
// 33 接口地址: CommercialApi/BigData/GetProvinceVehicleTreeList,
// 31 接口地址: EShangApiMain/Revenue/GetBusinessAnalysisReport,
// 27 接口地址: EShangApiMain/Analysis/GetRevenueEstimateList,
// 23 接口地址: EShangApiMain/Analysis/GetASSETSPROFITSTreeList,
// 25 接口地址: CommercialApi/Revenue/GetShopSABFIList,
// 4  接口地址: EShangApiMain/Revenue/GetRevenueReport,
// 3  接口地址: EShangApiMain/BusinessProject/GetPeriodWarningList,
// 11 接口地址: EShangApiMain/Revenue/GetRevenueYOYQOQ,
// 15 接口地址: CommercialApi/Revenue/GetServerpartINCAnalysis,
// 19 接口地址: CommercialApi/Revenue/GetMonthINCAnalysis,
// 1  接口地址: CommercialApi/Revenue/GetMonthINCAnalysis,
// 17 接口地址: CommercialApi/BaseInfo/GetServerpartInfo,

// 从云平台拿到最新的规则列表 变成 文字
let newRuleText = ref<string>("");

// 补充给问题的后缀
let suffixText = ref<string>(`你的任务是：
    根据用户的自然语言查询,识别用户想要调用的一个或多个API;
    并根据上述的触发关键字，查找最贴近用户语义的关键字，来修改用户提出的问题，用户提问所带的修饰性文字也优化保留，并输出结果；
    不需要返回思考过程, 最终只输出API接口ID数组, 无需其他文字说明,找不到匹配的id就输出空
    输出结果格式按照 {
      idList:[],
      question:""
    }, question 为修改后的问题, idList为用户可能想要调用的API的ID
        `);
// 尽量提取出“服务区ID、时间范围”等有用信息；
//   最终只输出一个JSON格式,包含：
//       intents: 数组类型，列出识别到的意图
//       apiCalls: 数组类型，每个元素包含 apiName 和 params
// 如果完全无法判断要调用哪个接口，则返回空数组或者给出无匹配说明。只需要输出json

// ServerpartId是服务区id是枚举值,
// ShowNormal是判断是否显示正常项目默认是true,
// calcType是计算方式1是当月 2是累计 默认是2,
// pushProvinceCode是省份编码默认是530000,
// curYear是当前年份,如2025,
// compareYear是去年年份,如2024,
// StatisticsMonth是结算的结束月份,格式为YYYYMM,
// StatisticsStartMonth是结算的开始月份,格式为YYYYMM,
// StatisticsDate是统计日期默认是当天时间格式为YYYY-MM-DD,
// PeriodState是经营周期 1为当前周期 0为历史周期 默认都为1,
// DataType是数据格式 1为业主 2为商家 3为经营业态默认都为2,
// Format 默认都为1
// ShowMulti为是显示多个预警类型 默认为true,
// BusinessTrade为经营业态
// BusinessBrand
// MerchantName
// ShopName

// 文字问题的回答结果
const textData = ref();
// 图片答案
const imgData = ref();
// 阿里云调用deepseek
const aLiYunGetDeepSeek = async (question: string) => {
  aliyunMessageList.push({
    role: "assistant",
    content: "",
    descResponseText: "",
    loading: true,
  });
  const openai = new openAi({
    apiKey: "sk-1aa2c1c672034c6d826ce62d3aebcb47",
    baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
    dangerouslyAllowBrowser: true,
  });
  // // 判断数据流是否继续
  let isStreaming: boolean = true;
  // const data: any = await openai.chat.completions.create({
  //   model: "deepseek-r1-distill-qwen-1.5b",
  //   messages: [{ role: "user", content: question }],
  //   stream: true,
  // });
  // console.log("data", data);

  let oldMessage: any = [];
  if (aliyunMessageList && aliyunMessageList.length > 0) {
    aliyunMessageList.forEach((item: any, index: number) => {
      if (index + 1 === aliyunMessageList.length) {
        oldMessage.push({
          role: item.role,
          content:
            item.content +
            (RoleDescription.value ? routerRole.value.content : ""),
        });
      } else {
        oldMessage.push({
          role: item.role,
          content: item.content,
        });
      }
    });
  }
  try {
    let modal = {
      model: "deepseek-r1-distill-qwen-1.5b",
      messages: [...oldMessage],
      stream: true,
      max_tokens: 1500,
      stop: ["null"],
      temperature: 0.7,
      top_p: 0.7,
      top_k: 50,
      frequency_penalty: 0.5,
      n: 1,
      response_format: {
        type: "text",
      },
    };
    const options = {
      method: "POST",
      headers: {
        Authorization: "Bearer sk-1aa2c1c672034c6d826ce62d3aebcb47",
        "Content-Type": "application/json",
      },
      body: JSON.stringify(modal),
    };
    const response: any = await fetch(
      "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
      options
    );
    // 创建流式读取器
    const reader = response.body.getReader();
    const decoder = new TextDecoder("utf-8");
    while (isStreaming) {
      const { done, value } = await reader.read();
      if (done) break;
      // 解码并处理数据
      const chunk = decoder.decode(value);
      aliyunStreamChunk(chunk);
      handleAliyunScrollToBottom();
    }

    aliyunresponseText.value = "";
    aliyundescResponseText.value = "";

    showController.value = false;
  } catch (error: any) {
    if (error.name !== "AbortError") {
      console.error("流式请求失败:", error);
    }
  } finally {
    isStreaming = false;
  }
};

// 阿里云处理数据流
const aliyunStreamChunk = async (chunk: any) => {
  const lines = chunk.split("\n").filter((line: any) => line.trim() !== "");

  lines.forEach((line: any) => {
    const message = line.replace(/^data: /, "");
    if (message === "[DONE]") return;
    try {
      const parsed = JSON.parse(message);
      let text = "";
      let descText = "";
      if (parsed.choices[0].delta.content) {
        text = parsed.choices[0].delta.content || "";
        aliyunresponseText.value += text; // 实时更新响应文本
      } else if (parsed.choices[0].delta.reasoning_content) {
        descText = parsed.choices[0].delta.reasoning_content || "";
        aliyundescResponseText.value += descText;
      }

      aliyunMessageList[aliyunMessageList.length - 1] = {
        ...aliyunMessageList[aliyunMessageList.length - 1],
        content: aliyunresponseText.value,
        descResponseText: aliyundescResponseText.value,
        loading: false,
      };
    } catch (err) {
      console.warn("解析 JSON 失败:", err);
    }
  });
};

// 直接提问deepseek 没有格式 不走语义
const handleAskDirectlyDeepseek = async () => {
  console.log("modalTypeDataList", modalTypeDataList);
  if (modalTypeDataList && modalTypeDataList.length > 0) {
    modalTypeDataList.forEach((item: any) => {
      if (item.isShow) {
        handleGetAnswerID(item);
      }
    });
  }
};

// 判断是否有大屏两个字
const containsDaping = (input: string) => {
  return /大屏/.test(input);
}

// 发送问题
const handleSendRequest = async (bigObj?: any) => {
  // 点击刷新 还是会来问问题 bigObj 控制只有一个进行刷新

  if (!userInput.value) {
    return;
  }

  // 把提问输入框里面的内容 给存起来 然后清空 输入框的内容
  let thisQuestion: string = "";
  let mapQuestion: string = "";
  thisQuestion = JSON.parse(JSON.stringify(userInput.value));
  userInput.value = "";


  console.log('modalTypeDataList', modalTypeDataList);
  // 找到当前选择的模型 添加问题的数据
  modalTypeDataList.forEach((item: any) => {
    if (item.isShow) {
      let list: any = item.messageList;
      list.push({
        role: "user",
        content: (startFree.value ? freeContent.value : "") + thisQuestion,
        index: list && list.length > 0 ? list.length : 0,
      });
      item.messageList = list;
      console.log('listlistlistlist', JSON.parse(JSON.stringify(list)))

      handleScrollToBottomID("gjldBox" + item.value);
    }
  });

  // 判断是否开启了自由定义 开启了就换个方法
  if (startFree.value || thisQuestion.length > 50) {
    await handleAskDirectlyDeepseek();
    return;
  }
  console.log('pageType.valuepageType.value', pageType.value);

  // 判断一下 是不是被内嵌到别人那边的 内嵌的话 就走这儿 不走下面的了
  if (containsDaping(thisQuestion)) {
    // 内嵌云南大屏的内嵌规则 是内嵌 且要有大屏 两个字
    // 这样就进来 不去调用后面的内容

    modalTypeDataList.forEach((item: any) => {
      if (bigObj.value) {
        if (item.value !== bigObj.value) {
          return;
        }
      }
      if (item.isShow) {
        let list: any = item.messageList;
        console.log("list", list);
        list.push({
          role: "default",
          content: "",
          index: list && list.length > 0 ? list.length : 0,
          noHiden: omitProcess.value ? 0 : 1,
        });
        item.messageList = list;
      }
    });

    console.log('newRuleTextnewRuleTextnewRuleText', newRuleText.value);
    console.log('routerRolerouterRolerouterRolerouterRole', routerRole.value);
    console.log('thisQuestionthisQuestionthisQuestionthisQuestion', thisQuestion);


    let YNMapData: any = await handleGetYNMapData()



    // 配置问题内容  
    mapQuestion = `#云南大屏直接进行路由角色说明解析#<Br/>
          #路由角色解析#<Br/>
          ${routerRole.value.content}<Br/>
          #用户提问#<Br/>
          ${thisQuestion || ""}<Br/>
          #接口数据说明#<Br/>
          ${YNMapData}
          `;

    console.log('mapQuestionmapQuestionmapQuestion', mapQuestion);


    for (let i = 0; i < modalTypeDataList.length; i++) {
      if (modalTypeDataList[i].isShow) {
        let list: any = modalTypeDataList[i].messageList;

        console.log('listlistlistlist', JSON.parse(JSON.stringify(list)));

        list[list.length - 1] = {
          ...list[list.length - 1],
          content: mapQuestion,
          loading: false,
        };
        modalTypeDataList[i].messageList = list;
      }
    }
    console.log('modalTypeDataListmodalTypeDataListmodalTypeDataList', JSON.parse(JSON.stringify(modalTypeDataList)));

    // let nowShowIdList: any = [];
    // for (let i = 0; i < modalTypeDataList.length; i++) {
    //   if (modalTypeDataList[i].isShow) {
    //     nowShowIdList.push(modalTypeDataList[i].value)
    //   }
    // }
    // handleOnceMoreModal(nowShowIdList);
    return
  }



  if (useMapData) {
    modalTypeDataList.forEach((item: any) => {
      if (bigObj.value) {
        if (item.value !== bigObj.value) {
          return;
        }
      }
      if (item.isShow) {
        let list: any = item.messageList;
        console.log("list", list);
        list.push({
          role: "default",
          content: "",
          loading: true,
          index: list && list.length > 0 ? list.length : 0,
          noHiden: omitProcess.value ? 0 : 1,
        });
        item.messageList = list;
      }
    });

    // 拿最新的语义规则
    // 确保每次问问题都可以拿到最新的规则文本
    await handleNewRuleList();

    // 拿到这一次问问题的哪个模型 不一样的模型 他们的自己语义对话框的id不同
    // let nowValueList: any = []
    // if(bigObj.value){
    //   nowValueList= [bigObj.value]
    // }else{
    //   modalTypeDataList.forEach((item: any) => {
    //     nowValueList.push(item.value)
    //   })
    // }

    for (let i = 0; i < modalTypeDataList.length; i++) {
      console.log("modalTypeDataList[i].isShow", modalTypeDataList[i].isShow);

      if (modalTypeDataList[i].isShow) {
        // 调用自己的语义 
        const mapData: any = await RobotDialogueBoxRef.value.handleSubmit(
          thisQuestion,
          modalTypeDataList[i].value
        );
        console.log('atatatat', mapData);

        // 判断自己的语义是否成功
        let userSemanticsIsSuccess: boolean = true;

        if (mapData && mapData.length > 0) {
          userSemanticsIsSuccess = true;
          let allStr: string = "";
          // 关键字 如果多个的话 关键字是一样的
          let RevenueAnalysis: string = "";
          // JSON字段注解
          let JSONDESC: string = "";

          mapData.forEach((item: any) => {
            RevenueAnalysis = item.RevenueAnalysis;
            let columnsObj: any = {};
            let columnsTypeList: any = [];

            let dataList: any = [];
            // 将表格数据变成一个字符串 写起来的表格
            let dataStr: string = "";
            // 需要显示的字段
            let showColumnsList: any = [];
            let showColumnsObj: any = {};

            if (item.RESPONSE_FIELD) {
              let obj: any = item.RESPONSE_FIELD
                ? JSON.parse(item.RESPONSE_FIELD)
                : "";

              let tabHeader: string = "";
              if (obj) {
                for (let key in obj) {
                  if (tabHeader) {
                    tabHeader += ` ${obj[key]}`;
                  } else {
                    tabHeader = `${obj[key]}`;
                  }
                  showColumnsList.push(key);
                }
                tabHeader += `<Br/>`;
                dataStr += `${tabHeader}`;
              }
            } else if (item.columns && item.columns.length > 0) {
              item.columns.forEach((subItem: any) => {
                if (subItem.prop) {
                  columnsObj[subItem.prop] = subItem.label;
                }
                columnsTypeList.push(subItem.prop);
              });
              showColumnsList = columnsTypeList;

              if (columnsObj) {
                let str: string = "";
                for (let key in columnsObj) {
                  if (str) {
                    str += ` ${columnsObj[key]}`;
                  } else {
                    str = `${columnsObj[key]}`;
                  }
                }
                dataStr += str;
              }
              dataStr += `<Br/>`;
            }

            if (item.tableData && item.tableData.length > 0) {
              item.tableData.forEach((subItem: any) => {
                let str: string = "";
                let obj: any = JSON.parse(JSON.stringify(subItem));
                obj = handleChangObjType(obj);

                if (obj) {
                  let text: string = handleTableDataToStr(
                    obj,
                    showColumnsList,
                    item.ruleDetail.CHILD_NODENAME,
                    1
                  );
                  str = `${text}`;
                }
                if (str) {
                  dataStr += `
                  ${str}`;
                }
              });
            }
            if (item.VHtml && item.VHtml !== "暂无数据") {
              allStr += `#id【${item.ruleDetail.ANALYSISRULE_ID}】接口数据如下#：<Br/>${item.VHtml}<Br/>`;
            } else {
              console.log("dataStrdataStrdataStr", dataStr);
              allStr += `#id【${item.ruleDetail.ANALYSISRULE_ID}】接口数据如下#：<Br/>${dataStr}<Br/>`;
            }
            let desc: string = `接口意图：${item.ruleDetail.USER_INTENT}；接口备注：${item.ruleDetail.ANALYSISRULE_DESC}。`;
            JSONDESC += `#id【${item.ruleDetail.ANALYSISRULE_ID}】的注释#：<Br/>
            ${desc}<Br/>`;
          });
          // 驿商语义解析 的替换 如果规则id只有一个  且这个的id配置了大模型输出规范字段 那么就替换
          let newContent: string = "";

          if (
            mapData &&
            mapData.length === 1 &&
            mapData[0].ruleDetail.OUTPUT_STANDARD
          ) {
            newContent = mapData[0].ruleDetail.OUTPUT_STANDARD;
          }

          mapQuestion = `#驿商语义解析#<Br/>
          ${newContent ? newContent : YSRole.value.content}<Br/>
          #用户提问#<Br/>
          ${thisQuestion || ""}<Br/>
          #问题解析关键字#<Br/>
          ${RevenueAnalysis}<Br/>
          #以下是API接口注释#<Br/>
          ${JSONDESC}
          #接口数据说明(-代表为空数据,*代表层级)#<Br/>
          ${allStr}`;
        } else {
          mapQuestion = `#驿商语义解析失败切换至路由角色说明解析#<Br/>
          #路由角色解析#<Br/>
          ${newRuleText.value}
          ${routerRole.value.content}<Br/>
          #用户提问#<Br/>
          ${thisQuestion || ""}<Br/>
          `;
          userSemanticsIsSuccess = false;
        }

        console.log('mapQuestionmapQuestionmapQuestion', mapQuestion);


        if (
          bigObj.value
            ? modalTypeDataList[i].value === bigObj.value
            : modalTypeDataList[i].isShow
        ) {
          let list: any = modalTypeDataList[i].messageList;
          list[list.length - 1] = {
            ...list[list.length - 1],
            content: mapQuestion,
            loading: false,
            userSemanticsIsSuccess: userSemanticsIsSuccess,
          };
          modalTypeDataList[i].messageList = list;
        }

        // modalTypeDataList.forEach((item: any) => {
        //   if (bigObj.value) {
        //     if (item.value !== bigObj.value) {
        //       return;
        //     }
        //   }
        //   if (item.isShow) {
        //     let list: any = item.messageList;
        //     list[list.length - 1] = {
        //       ...list[list.length - 1],
        //       content: mapQuestion,
        //       loading: false,
        //       userSemanticsIsSuccess: userSemanticsIsSuccess,
        //     };
        //     item.messageList = list;
        //   }
        // });
      }
    }
  }

  let nowShowIdList: any = [];

  // modalTypeDataList 的isShow为true的 就是需要添加内容的
  if (modalTypeDataList && modalTypeDataList.length > 0) {
    modalTypeDataList.forEach((item: any) => {
      if (item.isShow) {
        // 如果是点击的刷新 那么就往list传一个value
        // 如果是正常的问问题 那就是走else 传入全部value
        if (bigObj?.value) {
          if (bigObj.value === item.value) {
            nowShowIdList.push(item.value);
          }
        } else {
          nowShowIdList.push(item.value);
        }
        // 找最后一个用户问的对象
        let list: any = item.messageList;
        let userList: any = [];
        if (list && list.length > 0) {
          list.forEach((subItem: any) => {
            if (subItem.role === "user") {
              userList.push(subItem);
            }
          });
        }
        let lastObj: any =
          userList && userList.length > 0 ? userList[userList.length - 1] : "";
        lastObj.mapContent = mapQuestion;

        if (lastObj && item.messageList && item.messageList.length > 0) {
          item.messageList.forEach((subItem: any) => {
            if (subItem.index === lastObj.index) {
              subItem = lastObj;
            }
          });
        }
        handleScrollToBottomID("gjldBox" + item.value);
        // handleOnceMoreModal([item.value]);
      }
    });
  }

  console.log('nowShowIdListnowShowIdListnowShowIdList', nowShowIdList);

  // 判断一下 是不是开启了 省略过程 那就是直接去调用ai深度分析
  if (omitProcess.value) {
    handleOnceMoreModal(nowShowIdList);
  }
};

// 封装一个方法 把一个对象里面 包裹一个对象的内容 拆成同一级对象
const handleChangObjType = (obj: any) => {
  let newObj: any = {
    ...obj,
  };
  for (let key in obj) {
    if (
      typeof obj[key] === "object" &&
      obj[key] !== null &&
      !Array.isArray(obj[key])
    ) {
      let smallObj: any = obj[key];
      for (let smallKey in smallObj) {
        newObj[`${key}${smallKey}`] = smallObj[smallKey];
      }
    }
  }
  return newObj;
};

// 封装一个方法 作用是把table数据的每一层变成文字 且子级递归 且 子级字段名字可配
const handleTableDataToStr = (
  obj: any,
  showColumnsList: any,
  childrenName: string,
  level: number
) => {
  if (!obj || !(showColumnsList && showColumnsList.length > 0)) {
    return "";
  }
  // list为表格数据 showColumnsList 为需要显示的字段 string的数组  childrenName为子级的名称 默认是children
  // level 表示层级
  let childrenField: string = childrenName || "children";
  // 输出的文本结果
  let res: string = "";
  // 这一次的文本输出
  let thisText: string = "";
  if (level) {
    for (let i = 0; i < level; i++) {
      res += `*`;
    }
  }

  showColumnsList.forEach((item: any) => {
    if (res) {
      res += ` ${obj[item] || "-"}`;
    } else {
      res = `${obj[item] || "-"}`;
    }
  });

  // let textList: any = thisText.split(" ");
  // if (textList && textList.length > 0) {
  //   // 判断是不是都是 -
  //   let isAllNone: boolean = true;

  //   textList.forEach((item: any) => {
  //     if (item !== "-") {
  //       isAllNone = false;
  //     }
  //   });

  //   if (!isAllNone) {
  //     res += thisText;
  //   }
  //   res += `<Br/>`;
  // }
  res += `<Br/>`;

  if (obj[childrenField] && obj[childrenField].length > 0) {
    let list: any = obj[childrenField];

    list.forEach((subItem: any) => {
      let subObj = handleChangObjType(subItem);
      let str: string = handleTableDataToStr(
        subObj,
        showColumnsList,
        childrenName,
        level + 1
      );
      res += `${str}`;
    });
  }

  return res;
};

// 角色说明分析
const handleUseRoleQuestion = async (bigObj: any, obj: any) => {
  if (pageType.value === 1) {
    handleOnceMoreModal(modalTypeSelect.value);
    return
  }


  console.log('bigObj3232', bigObj);



  // 最后显示的文字
  let mapQuestion: string = "";
  let thisQuestion: string = "";

  let userList: any = [];

  if (bigObj.messageList && bigObj.messageList.length > 0) {
    bigObj.messageList.forEach((item: any) => {
      if (item.role === "user") {
        userList.push(item);
      }
    });
    let list = bigObj.messageList;
    list[list.length - 1].loading = true;
    list[list.length - 1].loadingContent = "路由角色分析中...";
    bigObj.messageList = list;
  }

  let lastUserObj: any = userList[userList.length - 1];

  console.log("lastUserObj", lastUserObj);
  let showBtn: string = "";

  // 判断这一次deepseek是否成功分析出来了
  let userSemanticsIsSuccess: boolean = true;
  const data = await handleGetInterfaceID(lastUserObj.content, bigObj);
  console.log("dsadasdasdasdsgas", data);
  if (bigObj.messageList && bigObj.messageList.length > 0) {
    bigObj.messageList.forEach((item: any) => {
      if (item.role === "user") {
        userList.push(item);
      }
    });
    let list = bigObj.messageList;
    list[list.length - 1].loading = true;
    list[list.length - 1].loadingContent = "思考中...";
    bigObj.messageList = list;
  }

  if (data.idList === "请求超时，请稍后重试！") {
    mapQuestion = "请求超时，请稍后重试！";
  } else if (data.idList && data.idList.length > 0) {
    const newData: any = await RobotDialogueBoxRef.value.handleGetAnswerID(
      data.idList,
      data.question,
      bigObj.value
    );
    console.log("newData3232", newData);
    if (newData && newData.length > 0) {
      userSemanticsIsSuccess = true;
      let allStr: string = "";
      // 关键字 如果多个的话 关键字是一样的
      let RevenueAnalysis: string = "";
      // JSON字段注解
      let JSONDESC: string = "";

      newData.forEach((item: any) => {
        RevenueAnalysis = item.RevenueAnalysis;
        let columnsObj: any = {};
        let columnsTypeList: any = [];
        let dataList: any = [];
        // 将表格数据变成一个字符串 写起来的表格
        let dataStr: string = "";
        // 需要显示的字段
        let showColumnsList: any = [];
        let showColumnsObj: any = {};

        if (item.RESPONSE_FIELD) {
          let obj: any = item.RESPONSE_FIELD
            ? JSON.parse(item.RESPONSE_FIELD)
            : "";

          let tabHeader: string = "";
          if (obj) {
            for (let key in obj) {
              if (tabHeader) {
                tabHeader += ` ${obj[key]}`;
              } else {
                tabHeader = `${obj[key]}`;
              }
              showColumnsList.push(key);
            }
            tabHeader += `<Br/>`;
            dataStr += `${tabHeader}`;
          }
          console.log("tabHeader", tabHeader);
          console.log("item.RESPONSE_FIELD", obj);
        } else if (item.columns && item.columns.length > 0) {
          item.columns.forEach((subItem: any) => {
            if (subItem.prop) {
              columnsObj[subItem.prop] = subItem.label;
            }
            columnsTypeList.push(subItem.prop);
          });
          showColumnsList = columnsTypeList;

          if (columnsObj) {
            let str: string = "";
            for (let key in columnsObj) {
              if (str) {
                str += ` ${columnsObj[key]}`;
              } else {
                str = `${columnsObj[key]}`;
              }
            }
            dataStr += str;
          }
          console.log("showColumnsList", showColumnsList);
          dataStr += `<Br/>`;
        }

        if (item.tableData && item.tableData.length > 0) {
          item.tableData.forEach((subItem: any) => {
            let str: string = "";
            let obj: any = JSON.parse(JSON.stringify(subItem));
            obj = handleChangObjType(obj);
            console.log("handleChangObjType", obj);

            if (obj) {
              let text: string = handleTableDataToStr(
                obj,
                showColumnsList,
                item.ruleDetail.CHILD_NODENAME,
                1
              );
              str = `${text}`;
            }
            if (str) {
              dataStr += `
                  ${str}`;
            }
          });
        }
        if (item.VHtml && item.VHtml !== "暂无数据") {
          allStr += `#id【${item.ruleDetail.ANALYSISRULE_ID}】接口数据如下#：<Br/>${item.VHtml}<Br/>`;
        } else {
          console.log("dataStrdataStrdataStr", dataStr);
          allStr += `#id【${item.ruleDetail.ANALYSISRULE_ID}】接口数据如下#：<Br/>${dataStr}<Br/>`;
        }
        let desc: string = `接口意图：${item.ruleDetail.USER_INTENT}；接口备注：${item.ruleDetail.ANALYSISRULE_DESC}。`;
        JSONDESC += `#id【${item.ruleDetail.ANALYSISRULE_ID}】的注释#：<Br/>
            ${desc}<Br/>`;
      });
      // 驿商语义解析 的替换 如果规则id只有一个  且这个的id配置了大模型输出规范字段 那么就替换
      let newContent: string = "";
      console.log("allStr", allStr);
      if (
        newData &&
        newData.length === 1 &&
        newData[0].ruleDetail.OUTPUT_STANDARD
      ) {
        newContent = newData[0].ruleDetail.OUTPUT_STANDARD;
      }

      mapQuestion = `#驿商语义解析#<Br/>
          ${newContent ? newContent : YSRole.value.content}<Br/>
          #用户提问#<Br/>
          ${thisQuestion || ""}<Br/>
          #问题解析关键字#<Br/>
          ${RevenueAnalysis}<Br/>
          #以下是API接口注释#<Br/>
          ${JSONDESC}
          #接口数据说明(-代表为空数据,*代表层级)#<Br/>
          ${allStr}`;
    } else {
      mapQuestion = `#驿商语义解析失败切换至路由角色说明解析#<Br/>
          #路由角色解析#<Br/>
          ${newRuleText.value}
          ${routerRole.value.content}<Br/>
          #用户提问#<Br/>
          ${thisQuestion || ""}<Br/>
          `;
      userSemanticsIsSuccess = false;
    }

    // if (newData) {
    //   if (newData.tableData && newData.tableData.length > 0) {
    //     let columnsList: any = [];
    //     let columnsTypeList: any = [];
    //     let columnsObj: any = {};
    //     if (newData.PARAM_FIELD) {
    //       columnsList = JSON.parse(newData.PARAM_FIELD);
    //       columnsObj = JSON.parse(newData.PARAM_FIELD);
    //       if (columnsList) {
    //         for (let key in columnsList) {
    //           columnsTypeList.push(key);
    //         }
    //       }
    //     } else if (newData.columns && newData.columns.length > 0) {
    //       newData.columns.forEach((item: any) => {
    //         // columnsList.push({ label: item.label, value: item.prop });
    //         if (item.prop) {
    //           columnsList.push(`${item.prop}:${item.label}`);
    //           columnsObj[item.prop] = item.label;
    //         }
    //         columnsTypeList.push(item.prop);
    //       });
    //     }

    //     let dataList: any = [];
    //     // 将表格数据变成一个字符串 写起来的表格
    //     let dataStr: string = "";

    //     // 需要显示的字段
    //     let showColumnsList: any = [];
    //     let showColumnsObj: any = {};
    //     if (newData.RESPONSE_FIELD) {
    //       let responseObj: any = JSON.parse(newData.RESPONSE_FIELD);
    //       showColumnsObj = JSON.parse(newData.RESPONSE_FIELD);
    //       for (let key in responseObj) {
    //         showColumnsList.push(key);
    //       }
    //     } else {
    //       showColumnsList = columnsTypeList;
    //     }

    //     if (columnsObj) {
    //       let str: string = "";
    //       for (let key in columnsObj) {
    //         if (str) {
    //           str += ` ${columnsObj[key]}`;
    //         } else {
    //           str = `${columnsObj[key]}`;
    //         }
    //       }
    //       dataStr += str;
    //     }

    //     if (newData.tableData && newData.tableData.length > 0) {
    //       newData.tableData.forEach((item: any) => {
    //         let str: string = "";
    //         let obj: any = JSON.parse(JSON.stringify(item));

    //         if (obj) {
    //           showColumnsList.forEach((showColumnsItem: any) => {
    //             if (obj[showColumnsItem]) {
    //               if (str) {
    //                 str += ` ${obj[showColumnsItem]}`;
    //               } else {
    //                 str = `${obj[showColumnsItem]}`;
    //               }
    //             } else {
    //               if (str) {
    //                 str += ` ${obj[showColumnsItem]}`;
    //               } else {
    //                 str = `${obj[showColumnsItem]}`;
    //               }
    //             }
    //           });
    //         }

    //         dataStr += `
    //       ${str}`;

    //         if (item.children && item.children.length > 0) {
    //           item.children.forEach((subItem: any) => {
    //             let str: string = "";
    //             let obj: any = JSON.parse(JSON.stringify(subItem));

    //             if (obj) {
    //               showColumnsList.forEach((thirdItem: any) => {
    //                 if (obj[thirdItem]) {
    //                   if (str) {
    //                     str += ` ${obj[thirdItem]}`;
    //                   } else {
    //                     str = `${obj[thirdItem]}`;
    //                   }
    //                 } else {
    //                   if (str) {
    //                     str += ` ${obj[thirdItem]}`;
    //                   } else {
    //                     str = `${obj[thirdItem]}`;
    //                   }
    //                 }
    //               });
    //             }
    //             dataStr += `
    //             ${str}`;
    //           });
    //         }
    //       });
    //     }

    //     let tableDataJSON: string = JSON.stringify(dataList);
    //     let columnsJSON: string = JSON.stringify(columnsList);
    //     mapQuestion = `#驿商语义解析#<Br/>
    //         ${YSRole.value.content}<Br/>
    //         #用户提问#<Br/>
    //         ${data.question || ""}<Br/>
    //         #问题解析关键字#<Br/>
    //         ${newData.RevenueAnalysis || ""}<Br/>
    //         #JSON字段注解#<Br/>
    //         ${columnsJSON}<Br/>
    //         #JSON数据#<Br/>
    //         ${tableDataJSON}`;
    //     // 表格数据的JSON格式内容为${tableDataJSON},表格数据对应的字段JSON为${columnsJSON},label为字段的含义,value就是数组字段,关键字${mapData.text}
    //     // mapQuestion = `表格数据的JSON格式内容为${tableDataJSON},表格重点显示的字段JSON为${columnsJSON},根据重点显示的字段分析表格数据，并给出总结性的语言给客户展示讲解`;
    //   } else if (newData.VHtml) {
    //     // mapQuestion = `${newData.VHtml}理解该段自然语言,将这段话进行总结，并给出总结性的语言给客户展示讲解`;
    //     mapQuestion = `#驿商语义解析#<Br/>
    //   ${YSRole.value.content}<Br/>
    //   #用户提问#<Br/>
    //   ${data.question || ""}<Br/>
    //   #问题解析关键字#<Br/>
    //   ${newData.RevenueAnalysis || ""}<Br/>
    //   #文本字符#<Br/>
    //   ${newData.VHtml}`;
    //   }
    // } else {
    //   // userSemanticsIsSuccess = false;
    //   mapQuestion = "无法理解，请换个说法";
    // }
  } else {
    // mapQuestion = "无法理解，请换个说法";
    // mapQuestion = `您好！目前暂时无法找到与您的问题相关的数据。为了更好地帮助您，可以尝试这样提问：新桥服务区营收情况如何`;
    mapQuestion =
      data.question ||
      "您好！目前暂时无法找到与您的问题相关的数据。为了更好地帮助您，可以尝试这样提问：新桥服务区营收情况如何";
    userSemanticsIsSuccess = true;
    showBtn = "1";
  }

  if (bigObj.messageList && bigObj.messageList.length > 0) {
    let list: any = bigObj.messageList;
    list[list.length - 1] = {
      ...list[list.length - 1],
      content: mapQuestion,
      loading: false,
      loadingContent: null,
      userSemanticsIsSuccess: userSemanticsIsSuccess,
      showBtn: showBtn,
    };
    bigObj.messageList = list;
  }

  // modalTypeDataList.forEach((item: any) => {
  //   if (item.isShow) {
  //     let list: any = item.messageList;
  //     list[list.length - 1] = {
  //       ...list[list.length - 1],
  //       content: mapQuestion,
  //       loading: false,
  //       loadingContent: null,
  //       userSemanticsIsSuccess: userSemanticsIsSuccess,
  //     };
  //     item.messageList = list;
  //   }
  // });

  console.log("mapQuestionmapQuestionmapQuestionmapQuestion", mapQuestion);
  console.log(
    "mapQuestionmapQuestionmapQuestionmapQuestion",
    bigObj.messageList
  );
};

// 一次性执行多个模型的问问题方法
const handleOnceMoreModal = async (typeList: number[]) => {
  if (typeList && typeList.length > 0) {
    modalTypeDataList.forEach((item: any) => {
      if (typeList.indexOf(item.value) !== -1) {
        item = handleGetAnswerID(item);
      }
      // if (item.isShow) {
      //   item = handleGetAnswerID(item);
      // }
    });
  }
};

// 根据传入的id去调用对应的 发起问题的方法
const handleGetAnswerID = async (obj: any) => {
  // 最新的相应文本
  // let responseText: string = "";
  console.log("obj2222", obj);

  let oldMessage: any = [];
  // 当对话列表小于3时 说明是第一次问问题 那么就直接找user就好了
  if (
    obj.messageList &&
    obj.messageList.length < 2 &&
    obj.messageList.length > 0
  ) {
    obj.messageList.forEach((item: any, index: number) => {
      // if (startFree.value ? item.role === "user" : item.role === "default") {
      if (item.role === "default") {
        oldMessage.push({
          role: "user",
          content: item.content,
          // (RoleDescription.value ? suffixText.value : "") +
          // (useMapData
          //   ? item.mapContent === "查询失败"
          //     ? ""
          //     : item.mapContent
          //   : item.content),
        });
      } else if (item.role === "user") {
        oldMessage.push({
          role: "user",
          content: item.content,
        });
      }
    });
  } else if (obj.messageList && obj.messageList.length >= 2) {
    // 区分之前的问题记录 和 最新的问题记录
    console.log("obj.messageList", obj.messageList);

    obj.messageList.forEach((item: any, index: number) => {
      // if (startFree.value ? item.role === "user" : item.role === "default") {
      if (item.role === "default" || item.role === "user") {
        oldMessage.push({
          role: "user",
          content: item.content,
          // (RoleDescription.value ? suffixText.value : "") +
          // (useMapData
          //   ? item.mapContent === "查询失败"
          //     ? ""
          //     : item.mapContent
          //   : item.content),
        });
      } else if (item.role === "assistant") {
        // 历史回答记录
        oldMessage.push({
          role: item.role,
          content: item.realContent || "",
        });
      }
    });
  }

  // if (obj.messageList && obj.messageList.length > 0) {
  //   obj.messageList.forEach((item: any, index: number) => {
  //     if (item.role !== "default") {
  //       if (index + 1 === obj.messageList.length) {
  //         oldMessage.push({
  //           role: item.role,
  //           content:
  //             (RoleDescription.value ? suffixText.value : "") + item.content,
  //         });
  //       } else {
  //         oldMessage.push({
  //           role: item.role,
  //           content: useMapData ? item.mapContent : item.content,
  //         });
  //       }
  //     }
  //   });
  // }
  console.log("oldMessage", oldMessage);

  obj.messageList.push({
    role: "assistant",
    content: "",
    descResponseText: "",
    loading: true,
    loadingContent: "深度分析中...",
  });
  handleScrollToBottomID("gjldBox" + obj.value);
  console.log("modalTypeDataList", modalTypeDataList);

  // 记录是否有数据流
  let hasStreamData: boolean = false;
  // 终止器
  const controller = new AbortController();
  controllers.value.push(controller); // 存入全局数组
  showController.value = true;
  console.log("controller", controller);
  let timeoutId: any = null; // 记录超时 ID

  try {
    const timeoutPromise = new Promise((resolve) => {
      timeoutId = setTimeout(() => {
        if (!hasStreamData) {
          // 仅当没有数据流时才执行超时逻辑
          let list: any = obj.messageList;
          list[list.length - 1] = {
            ...list[list.length - 1],
            content: "请求超时，请稍后重试！",
            loading: false,
            loadingContent: null,
          };
          obj.messageList = list;
          resolve({});
        }
      }, 60000);
    });
    let resText: any = await Promise.race([
      new Promise(async (resolve) => {
        try {
          // 判断数据流是否继续
          let isStreaming: boolean = true;
          let modal = {
            model:
              obj.value === 1
                ? selectDeepseekVersion.value === 1
                  ? "deepseek-chat"
                  : selectDeepseekVersion.value === 2
                    ? "deepseek-reasoner"
                    : ""
                : obj.value === 2
                  ? selectDeepseekVersion.value === 1
                    ? "deepseek-ai/DeepSeek-V3"
                    : selectDeepseekVersion.value === 2
                      ? "deepseek-ai/DeepSeek-R1-Distill-Llama-70B"
                      : ""
                  : obj.value === 3
                    ? selectDeepseekVersion.value === 1
                      ? "deepseek-v3"
                      : selectDeepseekVersion.value === 2
                        ? "deepseek-r1"
                        : ""
                    : obj.value === 4
                      ? "qwen-plus"
                      : "",
            messages: [...oldMessage],
            stream: true,
            max_tokens: maxTokens.value,
            stop: ["null"],
            temperature: Temperature.value,
            top_p: TopP.value,
            top_k: TopK.value,
            frequency_penalty: FrequencyPenalty.value,
            n: 1,
            response_format: {
              type: "text",
            },
          };
          const options = {
            method: "POST",
            headers: {
              Authorization:
                obj.value === 1
                  ? "Bearer sk-d47e0bdc7fd249f29d2f0dba807d46f0"
                  : obj.value === 2
                    ? "Bearer sk-nynbgbtnmsffijgkttoimqkptetivviwuqrdhbuclgbmvnsq"
                    : obj.value === 3
                      ? "Bearer sk-1aa2c1c672034c6d826ce62d3aebcb47"
                      : obj.value === 4
                        ? "Bearer sk-1aa2c1c672034c6d826ce62d3aebcb47"
                        : "",
              "Content-Type": "application/json",
            },
            body: JSON.stringify(modal),
            signal: controller.signal, // 关键：绑定控制器信号
          };
          // 判断是否成功
          let isSuccess: boolean = false;
          const response: any = await fetch(
            obj.value === 1
              ? "https://api.deepseek.com/v1/chat/completions"
              : obj.value === 2
                ? "https://api.siliconflow.cn/v1/chat/completions"
                : obj.value === 3
                  ? "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
                  : obj.value === 4
                    ? "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
                    : "",
            options
          );
          console.log("response", response);
          if (response.status === 200) {
            isSuccess = true;
          }
          // 创建流式读取器
          const reader = response.body.getReader();
          const decoder = new TextDecoder("utf-8");
          while (isStreaming) {
            const { done, value } = await reader.read();
            if (done) break;
            // 解码并处理数据
            const chunk = decoder.decode(value);
            handleStreamChunkID(chunk, obj);

            // 判断当前的这个框 是滚动数组里面的第几个 对他进行判断是不是在底部
            let nowShowList: any = [];
            if (modalTypeDataList && modalTypeDataList.length > 0) {
              modalTypeDataList.forEach((item: any) => {
                if (item.isShow) {
                  nowShowList.push(item);
                }
              });
            }
            let index: number = 99999;
            let isBottom: any = "default";
            if (nowShowList && nowShowList.length > 0) {
              nowShowList.forEach((item: any, itemIndex: number) => {
                if (item.value === obj.value) {
                  index = itemIndex;
                  if (scrollList.value && scrollList.value.length > 0) {
                    isBottom = scrollList.value[itemIndex].isBottom;
                  }
                }
              });
            }

            if (
              index === 99999 ||
              isBottom === "default" ||
              isBottom === true
            ) {
              handleScrollToBottomID("gjldBox" + obj.value);
            }

            resolve(true); // 完成流处理后resolve
          }
          // messageList.push({
          //   role: "assistant",
          //   content: responseText.value,
          //   descResponseText: descResponseText.value,
          // });
          obj.responseText = "";
          obj.descResponseText = "";
          showController.value = false;
          // handleStop();
          return isSuccess;
        } catch (error: any) {
          if (error.name !== "AbortError") {
            console.error("流式请求失败:", error);
          }
        } finally {
        }
      }).then((res) => {
        console.log("res", res);
        hasStreamData = true; // 这里标记数据流出现了
        clearTimeout(timeoutId); // 取消超时逻辑
      }),
      // handleAiDeepThinking(obj, oldMessage, controller).then((res) => {
      //   if (res) {
      //     console.log("标记数据流", res);

      //     hasStreamData = true; // 这里标记数据流出现了
      //     clearTimeout(timeoutId); // 取消超时逻辑
      //   }
      // }),
      timeoutPromise,
    ]);
    return resText;
  } catch (error) {
    // modalTypeDataList.forEach((item: any) => {
    //   if (item.isShow) {
    //     let list: any = item.messageList;
    //     list[list.length - 1] = {
    //       ...list[list.length - 1],
    //       content: "请求超时，请稍后重试！",
    //       loading: false,
    //       loadingContent: null,
    //     };
    //     item.messageList = list;
    //   }
    // });
    let list: any = obj.messageList;
    list[list.length - 1] = {
      ...list[list.length - 1],
      content: "请求超时，请稍后重试！",
      loading: false,
      loadingContent: null,
    };
    obj.messageList = list;
  }
};

// 最后的ai深度思考 超时终止  这个方法是他的请求内容
const handleAiDeepThinking = async (
  obj: any,
  oldMessage: any,
  controller: any
) => {
  // 判断数据流是否继续
  let isStreaming: boolean = true;

  let modal = {
    model:
      obj.value === 1
        ? selectDeepseekVersion.value === 1
          ? "deepseek-chat"
          : selectDeepseekVersion.value === 2
            ? "deepseek-reasoner"
            : ""
        : obj.value === 2
          ? selectDeepseekVersion.value === 1
            ? "deepseek-ai/DeepSeek-V3"
            : selectDeepseekVersion.value === 2
              ? "deepseek-ai/DeepSeek-R1-Distill-Llama-70B"
              : ""
          : obj.value === 3
            ? selectDeepseekVersion.value === 1
              ? "deepseek-v3"
              : selectDeepseekVersion.value === 2
                ? "deepseek-r1"
                : ""
            : obj.value === 4
              ? "qwen-plus"
              : "",
    messages: [...oldMessage],
    stream: true,
    max_tokens: maxTokens.value,
    stop: ["null"],
    temperature: Temperature.value,
    top_p: TopP.value,
    top_k: TopK.value,
    frequency_penalty: FrequencyPenalty.value,
    n: 1,
    response_format: {
      type: "text",
    },
  };
  const options = {
    method: "POST",
    headers: {
      Authorization:
        obj.value === 1
          ? "Bearer sk-d47e0bdc7fd249f29d2f0dba807d46f0"
          : obj.value === 2
            ? "Bearer sk-nynbgbtnmsffijgkttoimqkptetivviwuqrdhbuclgbmvnsq"
            : obj.value === 3
              ? "Bearer sk-1aa2c1c672034c6d826ce62d3aebcb47"
              : obj.value === 4
                ? "Bearer sk-1aa2c1c672034c6d826ce62d3aebcb47"
                : "",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(modal),
    signal: controller.signal, // 关键：绑定控制器信号
  };

  // 判断是否成功
  let isSuccess: boolean = false;

  try {
    const response: any = await fetch(
      obj.value === 1
        ? "https://api.deepseek.com/v1/chat/completions"
        : obj.value === 2
          ? "https://api.siliconflow.cn/v1/chat/completions"
          : obj.value === 3
            ? "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
            : obj.value === 4
              ? "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
              : "",
      options
    );

    console.log("response", response);
    if (response.status === 200) {
      isSuccess = true;
    }

    // 创建流式读取器
    const reader = response.body.getReader();
    const decoder = new TextDecoder("utf-8");

    while (isStreaming) {
      const { done, value } = await reader.read();
      if (done) break;
      // 解码并处理数据
      const chunk = decoder.decode(value);
      handleStreamChunkID(chunk, obj);

      // 判断当前的这个框 是滚动数组里面的第几个 对他进行判断是不是在底部
      let nowShowList: any = [];
      if (modalTypeDataList && modalTypeDataList.length > 0) {
        modalTypeDataList.forEach((item: any) => {
          if (item.isShow) {
            nowShowList.push(item);
          }
        });
      }
      let index: number = 99999;
      let isBottom: any = "default";
      if (nowShowList && nowShowList.length > 0) {
        nowShowList.forEach((item: any, itemIndex: number) => {
          if (item.value === obj.value) {
            index = itemIndex;
            if (scrollList.value && scrollList.value.length > 0) {
              isBottom = scrollList.value[itemIndex].isBottom;
            }
          }
        });
      }

      if (index === 99999 || isBottom === "default" || isBottom === true) {
        handleScrollToBottomID("gjldBox" + obj.value);
      }
    }
    // messageList.push({
    //   role: "assistant",
    //   content: responseText.value,
    //   descResponseText: descResponseText.value,
    // });

    obj.responseText = "";
    obj.descResponseText = "";
    showController.value = false;
    // handleStop();
    return isSuccess;
  } catch (error: any) {
    if (error.name !== "AbortError") {
      console.error("流式请求失败:", error);
    }
  } finally {
    isStreaming = false;
  }
};

// 根据传入的id 去找对应的div元素 让他滚动到最底部
const handleScrollToBottomID = (id: string) => {
  const gjldBox: any = document.getElementById(id);
  setTimeout(() => {
    nextTick(() => {
      if (gjldBox) {
        gjldBox.scrollTop = gjldBox.scrollHeight; // 将 scrollTop 设置为 scrollHeight，滚动到最底部
      }
    });
  }, 100);
};

// 文字问问题
const handleAnswerText = async (question: string) => {
  messageList.push({
    role: "assistant",
    content: "",
    descResponseText: "",
    loading: true,
  });
  // 判断数据流是否继续
  let isStreaming: boolean = true;
  // 最新的相应文本
  // let responseText: string = "";
  // 终止器
  let controller = new AbortController();

  let oldMessage: any = [];
  if (messageList && messageList.length > 0) {
    messageList.forEach((item: any, index: number) => {
      if (index + 1 === messageList.length) {
        oldMessage.push({
          role: item.role,
          content:
            (RoleDescription.value ? routerRole.value.content : "") +
            item.content,
        });
      } else {
        oldMessage.push({
          role: item.role,
          content: item.content,
        });
      }
    });
  }

  let modal = {
    model: "deepseek-ai/DeepSeek-R1-Distill-Llama-70B",
    messages: [
      ...oldMessage,
      // {
      //   role: "user",
      //   content: question,
      // },
    ],
    stream: true,
    max_tokens: 1500,
    stop: ["null"],
    temperature: 0.7,
    top_p: 0.7,
    top_k: 50,
    frequency_penalty: 0.5,
    n: 1,
    response_format: {
      type: "text",
    },
    // tools: [
    //   {
    //     type: "function",
    //     function: {
    //       description: "<string>",
    //       name: "<string>",
    //       parameters: {},
    //       strict: false,
    //     },
    //   },
    // ],
  };
  const options = {
    method: "POST",
    headers: {
      Authorization:
        "Bearer sk-nynbgbtnmsffijgkttoimqkptetivviwuqrdhbuclgbmvnsq",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(modal),
  };

  try {
    const response: any = await fetch(
      "https://api.siliconflow.cn/v1/chat/completions",
      options
    );

    // 创建流式读取器
    const reader = response.body.getReader();
    const decoder = new TextDecoder("utf-8");

    while (isStreaming) {
      const { done, value } = await reader.read();
      if (done) break;
      // 解码并处理数据
      const chunk = decoder.decode(value);
      handleStreamChunk(chunk);
      handleScrollToBottom();
    }
    // messageList.push({
    //   role: "assistant",
    //   content: responseText.value,
    //   descResponseText: descResponseText.value,
    // });

    responseText.value = "";
    descResponseText.value = "";
    showController.value = false;
    console.log("messageList", messageList);
  } catch (error: any) {
    if (error.name !== "AbortError") {
      console.error("流式请求失败:", error);
    }
  } finally {
    isStreaming = false;
  }

  // .then((response) => response.json())
  // .then((response) => {
  //   console.log("response", response);
  //   let textAnswer = response.choices[0].message.content || "";
  //   textData.value = textAnswer;
  // })
  // .catch((err) => console.error(err));
};

// 根据传入的id 去处理数据流
const handleStreamChunkID = async (chunk: any, obj: any) => {
  const lines = chunk.split("\n").filter((line: any) => line.trim() !== "");

  lines.forEach((line: any) => {
    const message = line.replace(/^data: /, "");
    if (message === "[DONE]") return;

    try {
      const parsed = JSON.parse(message);

      let text = "";
      let descText = "";
      if (parsed.choices[0].delta.content) {
        text = parsed.choices[0].delta.content || "";
        obj.responseText += text; // 实时更新响应文本
      } else if (parsed.choices[0].delta.reasoning_content) {
        descText = parsed.choices[0].delta.reasoning_content || "";
        obj.descResponseText += descText;
      }

      obj.messageList[obj.messageList.length - 1] = {
        ...obj.messageList[obj.messageList.length - 1],
        content: marked(obj.responseText),
        realContent: obj.responseText,
        descResponseText: marked(obj.descResponseText),
        loading: false,
        loadingContent: null,
        index:
          obj.messageList && obj.messageList.length > 0
            ? obj.messageList.length
            : 0,
      };
    } catch (err) {
      console.warn("解析 JSON 失败:", err);
    }
  });
};

// 拿到云南大屏的数据
const handleGetYNMapData = async () => {
  let obj: any = {
    "服务区况述": sessionStorage.getItem("OverviewOfServiceAreaAI") || "",
    "服务区承载": sessionStorage.getItem("OverviewOfServiceAreaBusinessAI") || "",
    "特情事件": sessionStorage.getItem("TradingAlertAI") || "",
    "实时营收": sessionStorage.getItem("CoreBusinessDataAI") || "",
    "月度实时数据": sessionStorage.getItem("CoreBusinessDataMonthAI") || "",
    "断面流量": sessionStorage.getItem("TrendOfTrafficFlowYesAI") || "",
    "入区车流": sessionStorage.getItem("VehiclesEnteringAI") || "",
    "对客营收": sessionStorage.getItem("VehiclesEnteringAI2") || "",
    "经营效益": sessionStorage.getItem("VehicleModelStayAI") || "",
    "年龄": sessionStorage.getItem("CustomerAgeGroupAI") || "",
    "性别": sessionStorage.getItem("GenderCustomerGroupAI") || "",
    "偏好类型": sessionStorage.getItem("PreferenceTypeAI") || "",
    "客群特征分析": sessionStorage.getItem("CustomerGroupAI") || "",
    "客群消费偏好": sessionStorage.getItem("CustomerConsumptionPreferencesAI") || "",
    "消费转化对比图": sessionStorage.getItem("ConsumptionConversionAI") || "",
    "消费水平": sessionStorage.getItem("ConsumptionLevelAI") || "",
    "消费时段分析": sessionStorage.getItem("ConsumptionPeriodAI") || "",
    "品牌消费水平": sessionStorage.getItem("BrandConsumptionLevelAI") || "",
    "营收特征分析": sessionStorage.getItem("BusinessCaseAI") || "",
    "区域营收占比": sessionStorage.getItem("RegionalRevenueAI") || "",
    "业态结构占比": sessionStorage.getItem("BusinessStructureAI") || "",
    "节假日营收分析": sessionStorage.getItem("FestivalRevenueSumInfoAI") || "",
  }
  return JSON.stringify(obj)
}

// 处理数据流
const handleStreamChunk = async (chunk: any) => {
  const lines = chunk.split("\n").filter((line: any) => line.trim() !== "");

  lines.forEach((line: any) => {
    const message = line.replace(/^data: /, "");
    if (message === "[DONE]") return;

    try {
      const parsed = JSON.parse(message);

      let text = "";
      let descText = "";
      if (parsed.choices[0].delta.content) {
        text = parsed.choices[0].delta.content || "";
        responseText.value += text; // 实时更新响应文本
      } else if (parsed.choices[0].delta.reasoning_content) {
        descText = parsed.choices[0].delta.reasoning_content || "";
        descResponseText.value += descText;
      }

      messageList[messageList.length - 1] = {
        ...messageList[messageList.length - 1],
        content: responseText.value,
        descResponseText: descResponseText.value,
        loading: false,
      };
    } catch (err) {
      console.warn("解析 JSON 失败:", err);
    }
  });
};

// 将滚动条滚动到底部  一般触发时间为打字机效果 和 提问的时候
const handleScrollToBottom = () => {
  const gjldBox: any = document.getElementById("gjldBox");
  setTimeout(() => {
    nextTick(() => {
      if (gjldBox) {
        gjldBox.scrollTop = gjldBox.scrollHeight; // 将 scrollTop 设置为 scrollHeight，滚动到最底部
      }
    });
  }, 100);
};

// deepseek的官网的请求
const handleGetDeepseek = async (question: string) => {
  deepseekMessageList.push({
    role: "assistant",
    content: "",
    descResponseText: "",
    loading: true,
  });
  // 判断数据流是否继续
  let isStreaming: boolean = true;

  let oldMessage: any = [];
  if (deepseekMessageList && deepseekMessageList.length > 0) {
    deepseekMessageList.forEach((item: any, index: number) => {
      if (index + 1 < deepseekMessageList.length) {
        if (index + 2 === deepseekMessageList.length) {
          oldMessage.push({
            role: item.role,
            content:
              (RoleDescription.value ? routerRole.value.content : "") +
              item.content,
          });
        } else {
          oldMessage.push({
            role: item.role,
            content: item.content,
          });
        }
      }
    });
  }
  console.log("oldMessage", oldMessage);

  try {
    let modal = {
      model:
        selectDeepseekVersion.value === 1
          ? "deepseek-chat"
          : selectDeepseekVersion.value === 2
            ? "deepseek-reasoner"
            : "",
      // model: "deepseek-reasoner",
      messages: [...oldMessage],
      stream: true,
      // max_tokens: 1500,
      // stop: ["null"],
      // temperature: 1.3,
      // top_p: 0.7,
      // top_k: 50,
      // frequency_penalty: 0.5,
      // n: 1,
      // response_format: {
      //   type: "text",
      // },
    };
    const options = {
      method: "POST",
      headers: {
        Authorization: "Bearer sk-d47e0bdc7fd249f29d2f0dba807d46f0",
        "Content-Type": "application/json",
      },
      body: JSON.stringify(modal),
    };
    const response: any = await fetch(
      "https://api.deepseek.com/v1/chat/completions",
      options
    );

    // 创建流式读取器
    const reader = response.body.getReader();
    const decoder = new TextDecoder("utf-8");

    // const openai = new OpenAI({
    //   baseURL: "https://api.deepseek.com/v1",
    //   apiKey: "sk-d47e0bdc7fd249f29d2f0dba807d46f0",
    //   dangerouslyAllowBrowser: true,
    // });
    // const completion = await openai.chat.completions.create({
    //   messages: [...oldMessage],
    //   model: "deepseek-reasoner",
    // });
    // console.log("completion", completion);
    while (isStreaming) {
      const { done, value } = await reader.read();
      if (done) break;
      // 解码并处理数据
      const chunk = decoder.decode(value);
      deepseekStreamChunk(chunk);
      handleDeepseekScrollToBottom();
    }

    deepseekresponseText.value = "";
    deepseekdescResponseText.value = "";
    showController.value = false;
  } catch (error: any) {
    if (error.name !== "AbortError") {
      console.error("流式请求失败:", error);
    }
  } finally {
    isStreaming = false;
  }
};

const deepseekStreamChunk = async (chunk: any) => {
  const lines = chunk.split("\n").filter((line: any) => line.trim() !== "");

  lines.forEach((line: any) => {
    const message = line.replace(/^data: /, "");
    if (message === "[DONE]") return;
    try {
      const parsed = JSON.parse(message);
      let text = "";
      let descText = "";
      if (parsed.choices[0].delta.content) {
        text = parsed.choices[0].delta.content || "";
        deepseekresponseText.value += text; // 实时更新响应文本
      } else if (parsed.choices[0].delta.reasoning_content) {
        descText = parsed.choices[0].delta.reasoning_content || "";
        deepseekdescResponseText.value += descText;
      }

      deepseekMessageList[deepseekMessageList.length - 1] = {
        ...deepseekMessageList[deepseekMessageList.length - 1],
        content: deepseekresponseText.value,
        descResponseText: deepseekdescResponseText.value,
        loading: false,
      };
    } catch (err) {
      console.warn("解析 JSON 失败:", err);
    }
  });
};

const handleAliyunScrollToBottom = () => {
  const aliyunBox: any = document.getElementById("aliyunBox");
  setTimeout(() => {
    nextTick(() => {
      if (aliyunBox) {
        aliyunBox.scrollTop = aliyunBox.scrollHeight; // 将 scrollTop 设置为 scrollHeight，滚动到最底部
      }
    });
  }, 100);
};

const handleDeepseekScrollToBottom = () => {
  const deepseekBox: any = document.getElementById("deepseekBox");
  setTimeout(() => {
    nextTick(() => {
      if (deepseekBox) {
        deepseekBox.scrollTop = deepseekBox.scrollHeight; // 将 scrollTop 设置为 scrollHeight，滚动到最底部
      }
    });
  }, 100);
};

// 切换deepseek版本
// const handleChangeVersion = (e: any) => {
//   deepseekresponseText.value = "";
//   deepseekdescResponseText.value = "";
//   deepseekMessageList = [];
// };

// 模型种类切换
const handleChangeModalType = (e: any) => {
  console.log("e1", e);
  console.log("pageType", pageType.value);
  console.log("isPhone", isPhone);
  let newList: number[] = [];
  if (pageType.value === 1 || isPhone.value) {
    console.log('1');

    if (e && e.length > 1) {
      newList = [e[e.length - 1]]
    }
    // 当pageType为1  或者 是在手机里面时  就只能选则一个
    modalTypeSelect.value = newList;
    modalTypeDataList.forEach((item: any) => {
      if (newList.indexOf(item.value) !== -1) {
        item.isShow = true;
      } else {
        item.isShow = false;
      }
    });
  } else {
    console.log('2');
    if (e && e.length > 2) {
      e.forEach((item: number, index: number) => {
        if (index === 0) {
        } else {
          newList.push(item);
        }
      });
      modalTypeSelect.value = newList;
    }
    if (!(newList && newList.length > 1)) {
      newList = e;
    }
    console.log('newList', newList);

    modalTypeDataList.forEach((item: any) => {
      if (newList.indexOf(item.value) !== -1) {
        item.isShow = true;
      } else {
        item.isShow = false;
      }
    });
    console.log("modalTypeDataList", modalTypeDataList);
  }
};

// 终止生成
const handleStop = () => {
  controllers.value.forEach((controller) => controller.abort()); // 终止所有请求
  controllers.value = []; // 清空控制器数组

  modalTypeDataList.forEach((item: any) => {
    if (item.isShow) {
      if (item.messageList && item.messageList.length > 0) {
        item.messageList.forEach((subItem: any) => {
          if (subItem.loading) {
            subItem.loading = false;
            subItem.content = "分析终止";
          }
        });
      }
      item.responseText = "";
      item.descResponseText = "";
    }
  });
  console.log("modalTypeDataList", modalTypeDataList);

  showController.value = false;
};

// 改变他们使用的是v3 还是 r1
const handleChangeVersion = () => {
  if (selectDeepseekVersion.value === 1) {
    selectDeepseekVersion.value = 2;
    maxTokens.value = 8192;
  } else {
    selectDeepseekVersion.value = 1;
    maxTokens.value = 4096;
  }
};

watch(
  () => controllers,
  (newVal, oldVal) => {
    console.log("newVal", newVal);
    console.log("oldVal", oldVal);
  },
  { deep: true }
);

watch(
  () => startFree.value,
  (newVal, oldVal) => {
    if (newVal) {
      useMapData.value = false;
      RoleDescription.value = false;
    } else {
      useMapData.value = true;
    }
  },
  { deep: true }
);

watch(
  () => modalTypeDataList,
  (newVal, oldVal) => {
    if (newVal && newVal.length > 0) {
      newVal.forEach((item: any) => {
        if (item.messageList && item.messageList.length > 0) {
          item.messageList.forEach((subItem: any) => {
            if (subItem.role === "user") {
              item.showReload = true;
            }
            if (subItem.role === "assistant" && subItem.realContent) {
              item.showCopy = true;
            }
          });
        } else {
          item.showReload = false;
          item.showCopy = false;
        }
      });
    }
  },
  { deep: true }
);

// 点击深度分析
const handleDepthAnalysis = async (bigObj: any, obj: any) => {
  console.log("bigObj", bigObj);
  console.log("obj", obj);
  handleOnceMoreModal([bigObj.value]);
};

// 当自己的语义查询失败时 用deepseek 帮我们分析 要去调用哪个或几个的方法 返回的是id
// 返回id之后 去调用地图那边复制来的方法 按照正常的结果输出
const handleGetInterfaceID = async (questionText: string, bigObj: any) => {
  // modalTypeDataList.forEach(async (item: any) => {});
  let timeoutId: any;
  let lastQuestion: string =
    newRuleText.value + routerRole.value.content + questionText;
  try {
    const timeoutPromise = new Promise((resolve) => {
      timeoutId = setTimeout(
        () =>
          resolve({
            idList: "请求超时，请稍后重试！",
            question: "",
          }),
        60000
      );
    });
    let resText: any = await Promise.race([
      handleGetDeepseekAnswer(lastQuestion, bigObj),
      timeoutPromise,
    ]);
    clearTimeout(timeoutId);
    return resText;
  } catch (error) {
    console.error("请求出错:", error);
    return {
      idList: "请求超时，请稍后重试！",
      question: "",
    };
  }

  // for (let i = 0; i < modalTypeDataList.length; i++) {
  //   let item: any = modalTypeDataList[i];
  //   if (item.isShow) {
  //     console.log("handleGetDeepseekAnswer", item);
  //     // 取最新一条的用户提问
  //     let userQuestion: any = [];
  //     if (item.messageList && item.messageList.length > 0) {
  //       item.messageList.forEach((item: any) => {
  //         if (item.role === "user") {
  //           userQuestion.push(item);
  //         }
  //       });
  //     }

  //     // 最新的问题对象
  //     let lastObj: any = userQuestion[userQuestion.length - 1];
  //     console.log("lastObj", lastObj);

  //   }
  // }
};

// 仅调用deepseek返回答案 不对页面进行任何处理
const handleGetDeepseekAnswer = async (questionText: string, obj: any) => {
  let modal = {
    model:
      obj.value === 1
        ? selectDeepseekVersion.value === 1
          ? "deepseek-chat"
          : selectDeepseekVersion.value === 2
            ? "deepseek-reasoner"
            : ""
        : obj.value === 2
          ? selectDeepseekVersion.value === 1
            ? "deepseek-ai/DeepSeek-V3"
            : selectDeepseekVersion.value === 2
              ? "deepseek-ai/DeepSeek-R1-Distill-Llama-70B"
              : ""
          : obj.value === 3
            ? selectDeepseekVersion.value === 1
              ? "deepseek-v3"
              : selectDeepseekVersion.value === 2
                ? "deepseek-r1"
                : ""
            : obj.value === 4
              ? "qwen-plus"
              : "",
    messages: [{ role: "user", content: questionText }],
    // stream: true,
    max_tokens: maxTokens.value,
    stop: ["null"],
    temperature: Temperature.value,
    top_p: TopP.value,
    top_k: TopK.value,
    frequency_penalty: FrequencyPenalty.value,
    n: 1,
    response_format: {
      type: "text",
    },
  };
  const config = {
    method: "post",
    maxBodyLength: Infinity,
    url:
      obj.value === 1
        ? "https://api.deepseek.com/v1/chat/completions"
        : obj.value === 2
          ? "https://api.siliconflow.cn/v1/chat/completions"
          : obj.value === 3
            ? "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
            : obj.value === 4
              ? "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
              : "",
    headers: {
      "Content-Type": "application/json",
      Authorization:
        obj.value === 1
          ? "Bearer sk-d47e0bdc7fd249f29d2f0dba807d46f0"
          : obj.value === 2
            ? "Bearer sk-nynbgbtnmsffijgkttoimqkptetivviwuqrdhbuclgbmvnsq"
            : obj.value === 3
              ? "Bearer sk-1aa2c1c672034c6d826ce62d3aebcb47"
              : obj.value === 4
                ? "Bearer sk-1aa2c1c672034c6d826ce62d3aebcb47"
                : "",
    },
    data: modal,
  };
  const data = await axios(config);
  let id = data.data.choices[0].message.content;
  id = fixToJson(id);
  console.log("id", id);

  let idObj: any = handleChangeJSON(id);
  console.log("idObj", idObj);
  idObj.idList = idObj.idList.toString();
  idObj.idList = handleParseToArray(idObj.idList);
  // const arr = handleParseToArray(id);
  // console.log("handleGetDeepseekAnswer", arr);

  return idObj;
};
// 判断是不是JSON的方法 不是也变成JSON
const fixToJson = (input: any): string | null => {
  try {
    // 如果已经是 JSON，直接返回
    if (typeof input === "object") {
      return JSON.stringify(input);
    }

    if (typeof input !== "string") {
      throw new Error("输入必须是字符串或对象");
    }

    // 移除 Markdown 代码块标记（如果存在）
    input = input.replace(/```json[\s\S]*?```/g, (match) =>
      match.replace(/```json|```/g, "").trim()
    );

    // 先尝试解析，如果能解析说明是合法 JSON
    JSON.parse(input);
    return input;
  } catch (error) {
    try {
      input = input.replace(/'/g, '"');
      input = input.replace(/([{,])(\s*)([a-zA-Z0-9_]+)(\s*):/g, '$1"$3":');
      input = input.replace(/:\s*\[/g, ":[").replace(/:\s*{/g, ":{");

      // 再次尝试解析修正后的字符串
      JSON.parse(input);
      return input;
    } catch (fixError) {
      console.error("无法修正 JSON:", fixError);
      return null;
    }
  }
};

// 转JSON的判断
const handleChangeJSON = (jsonStr: any) => {
  try {
    jsonStr = jsonStr.replace(/\s+/g, "");
    console.log("jsonStr", jsonStr);

    let openBraces = (jsonStr.match(/{/g) || []).length;
    let closeBraces = (jsonStr.match(/}/g) || []).length;
    if (openBraces > closeBraces) {
      jsonStr = jsonStr.replace(/^{+/, "{");
    } else if (closeBraces > openBraces) {
      jsonStr = jsonStr.replace(/}+$/, "}");
    }
    jsonStr = jsonStr.replace(/{\{/, "{").replace(/}\}/, "}");
    let parsedData = JSON.parse(jsonStr);
    return {
      idList: Array.isArray(parsedData.idList)
        ? parsedData.idList
        : parsedData.idList,
      question:
        typeof parsedData.question === "string" ? parsedData.question : "",
    };
  } catch (error) {
    console.error("JSON 解析失败:", error);
    return { idList: [], question: "" }; // 解析失败时返回默认值
  }
};

// 字符转为数组  且 可以兼容[[]  []] deepseek返回的这些格式
const handleParseToArray = (str: string) => {
  let cleanedStr = str.replace(/[^0-9,\-]/g, "");
  let arr = cleanedStr
    .split(",")
    .filter((item) => item !== "")
    .map(Number);
  return arr;
};

// 重新提问
const handleQuestionReload = (obj: any, bigObj: any) => {
  // 判断当前最后一个 是不是在loading中
  let isLoading: boolean = false;
  if (bigObj.messageList && bigObj.messageList.length > 0) {
    let lastObj: any = bigObj.messageList[bigObj.messageList.length - 1];
    if (lastObj.loading) {
      isLoading = lastObj.loading;
    }
  }

  if (showController.value || isLoading) {
    return;
  }
  console.log("obj", obj);
  userInput.value = obj.content;
  handleSendRequest(bigObj);
};

// 滚动
const handleScroll = (e: any) => {
  let el = boxContentBoxRef.value;
  let elList: any = [];
  if (el && el.length === 2) {
    elList = [
      { id: el[0].id.split("gjldBox")[1], content: el[0] },
      { id: el[1].id.split("gjldBox")[1], content: el[1] },
    ];
    let newEl: any = [];
    // 给滚动框按照id顺序排个序 不然会乱掉
    if (elList[0].id > elList[1].id) {
      newEl.push(elList[1].content);
      newEl.push(elList[0].content);
    } else {
      newEl.push(elList[0].content);
      newEl.push(elList[1].content);
    }
    el = newEl;
  } else if (el && el.length === 1) {
    elList = [{ id: el[0].id.split("gjldBox")[1], content: el[0] }];
  }

  // if (el && el.length > 0) {
  //   for (let i = 0; i < el.length - 1; i++) {
  //     for (let j = 0; i < el.length - i; j++) {
  //       let thisDomID: number = Number(el[i].id.split("gjldBox")[1]);
  //       let nextDomId: number = Number(el[i].id.split("gjldBox")[1]);
  //       if (thisDomID < nextDomId) {
  //         let temp;
  //         temp = el[j - 1];
  //         el[j - 1] = el[j];
  //         el[j] = temp;
  //       }
  //     }
  //   }
  //   // el.forEach((item: any) => {
  //   //   console.log("item", item);
  //   // });
  // }

  // el.forEach((item: any) => {
  //   item.isBottom = true;
  // });

  if (!el) return;

  let nowShowList: any = [];

  if (modalTypeDataList && modalTypeDataList.length > 0) {
    modalTypeDataList.forEach((item: any) => {
      if (item.isShow) {
        let obj: any = JSON.parse(JSON.stringify(item));
        nowShowList.push(obj);
      }
    });
  }
  let index: number = 9999;
  if (nowShowList && nowShowList.length > 0) {
    nowShowList.forEach((item: any, itemIndex: number) => {
      if (item.value === e) {
        index = itemIndex;
      }
    });
  }

  if (index !== 9999) {
    const distanceToBottom =
      el[index].scrollHeight - el[index].scrollTop - el[index].clientHeight;
    let isBottom: boolean = distanceToBottom < 10;

    nowShowList[index].isBottom = isBottom;
  }

  scrollList.value = nowShowList;
};

// 删除该项的聊天记录
const handleDeleteMessageList = (obj: any) => {
  obj.messageList = [];

  RobotDialogueBoxRef.value.handleDelteModalCode(obj.value);
};

// 拿最新的规则列表 转成文字
const handleNewRuleList = async () => {
  const data = await handleGetANALYSISRULEList({
    searchParameter: {
      ANALYSISRULE_IDS: "",
      current: 1,
      pageSize: 10,
    },
    pagesize: 999999,
    PageIndex: 1,
  });
  console.log("handleNewRuleList", data);
  let str: string = "";

  if (data && data.length > 0) {
    // 基础信息的备注说明 有点特殊 不要改它
    data.forEach((item: any) => {
      str += `
      接口ID:${item.ANALYSISRULE_ID},
      触发关键词:${item.TRIGGER_WORDS},
      备注说明:${item.ANALYSISRULE_ID === 17 ? "" : item.ANALYSISRULE_DESC}`;
    });
  }
  // 这是已经调好的文本格式 也不要动
  let res: string = `你是一个负责将用户查询路由到后台API的智能助手。系统中有以下接口可以调用：${str || ""
    }
在触发关键词中的|字符，表示或者的意思，
  `;

  newRuleText.value = res;

  console.log("res", res);
};

// 隐藏左侧
const handleHideLeft = async () => {
  if (hideLeft.value) {
    hideLeft.value = false;
  } else {
    hideLeft.value = true;
  }
};

// 底下的刷新
const handleBottomReload = async (bigObj: any) => {
  // 找最后一个问题
  let lastQuestionObj: any;
  if (bigObj.messageList && bigObj.messageList.length > 0) {
    bigObj.messageList.forEach((item: any) => {
      if (item.role === "user") {
        lastQuestionObj = item;
      }
    });
  }

  userInput.value = lastQuestionObj.content;
  handleSendRequest(bigObj);
};

// 复制答案
const handleCopyContent = (bigObj: any) => {
  // 找最后一个的回答
  let lastAnswerObj: any;
  if (bigObj.messageList && bigObj.messageList.length > 0) {
    bigObj.messageList.forEach((item: any) => {
      if (item.role === "assistant") {
        lastAnswerObj = item;
      }
    });
  }
  if (navigator.clipboard) {
    navigator.clipboard
      .writeText(lastAnswerObj.realContent) // 复制到剪贴板
      .then(() => {
        ElMessage({
          message: "复制成功",
          type: "success",
        });
      });
  } else {
    ElMessage.error("您的浏览器不支持复制功能，请检查是否在 HTTPS 环境下运行");
  }
};

// 改变工作模式的方法
const handleChangeProcess = (e: any) => {
  console.log("e", e);
  modalTypeDataList.forEach((item: any) => {
    let nowLength = item.messageList.length;
    if (item.messageList && item.messageList.length > 0) {
      item.messageList.forEach((subItem: any) => {
        if (subItem.role === "default") {
          if (
            subItem.index < nowLength &&
            subItem.noHiden !== 0 &&
            subItem.noHiden !== 1
          ) {
            subItem.noHiden = 1;
          }
        }
      });
    }
    // item.messageList = [];
  });
  // 隐藏时的 对话框长度
  // nextTick(() => {
  //   modalTypeDataList.forEach((item: any) => {
  //     item.messageLength = item.messageList.length;
  //     // item.messageList = [];
  //   });
  // });
};
</script>

<template>
  <div class="main" :style="{ backgroundImage: pageType === 1 ? `url(${pageBg})` : '' }">
    <div class="meng" v-if="showPhoneChange || showPhoneOption" @click="handleClosePhoneMeng"></div>

    <div class="leftFilterBox" v-if="hideLeft" :style="{ width: pageType === 1 ? '350px' : '' }">
      <el-tabs class="leftFilterTabBox" v-model="leftTabShow" style="margin-bottom: 12px">
        <el-tab-pane label="自由问答" name="first">
          <div class="filterItem roleBox">
            <!-- style="height: calc(100vh - 450px - 20px - 30px)" -->
            <div class="topItem">
              <div class="titleBox">
                <span class="itemTitle">自由问答</span>
                <el-tooltip class="box-item" effect="dark" :content="YSRole?.desc" placement="top">
                  <!-- content="引入地图的语义，对返回过来的表格或文字进行优化" -->
                  <img class="noticeIcon" :src="noticeIcon" />
                </el-tooltip>
              </div>
              <el-switch v-model="startFree" size="default" />
            </div>
            <div class="bottomItem">
              <!-- <el-input v-model="mapDescPrefix" type="textarea" /> -->
              <el-input v-model="freeContent" type="textarea" />
            </div>
            <!-- <div class="updatebox">
              <img
                class="updateIcon"
                src="@/assets/ai/updateIcon.svg"
                @click="handleUpdatePrompt(1000)"
              />
              <span class="updateText" @click="handleUpdatePrompt(1000)"
                >更新</span
              >
            </div> -->
          </div>
        </el-tab-pane>

        <el-tab-pane :label="YSRole?.title" name="second">
          <div class="filterItem roleBox">
            <!-- style="height: calc(100vh - 450px - 20px - 30px)" -->
            <div class="topItem">
              <div class="titleBox">
                <!-- <span class="itemTitle">驿商语义解析</span> -->
                <span class="itemTitle">{{ YSRole?.title || "" }}</span>
                <el-tooltip class="box-item" effect="dark" :content="YSRole?.desc" placement="top">
                  <!-- content="引入地图的语义，对返回过来的表格或文字进行优化" -->
                  <img class="noticeIcon" :src="noticeIcon" />
                </el-tooltip>
              </div>
              <el-switch v-model="useMapData" size="default" />
            </div>
            <div class="bottomItem">
              <!-- <el-input v-model="mapDescPrefix" type="textarea" /> -->
              <el-input v-model="YSRole.content" type="textarea" />
            </div>
            <div class="updatebox">
              <img class="updateIcon" src="@/assets/ai/updateIcon.svg" @click="handleUpdatePrompt(1000)" />
              <span class="updateText" @click="handleUpdatePrompt(1000)">更新</span>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane :label="routerRole.title" name="third">
          <div class="filterItem roleBox">
            <!-- style="height: calc(100vh - 450px - 20px - 30px)" -->
            <div class="topItem">
              <div class="titleBox">
                <!-- <span class="itemTitle">路由角色说明</span> -->
                <span class="itemTitle">{{ routerRole.title || "" }}</span>
                <el-tooltip class="box-item" effect="dark" :content="routerRole.desc" placement="top">
                  <!-- content="为true时会默认补充上接口配置说明,即后缀文字" -->
                  <img class="noticeIcon" :src="noticeIcon" />
                </el-tooltip>
              </div>
              <el-switch v-model="RoleDescription" size="default" />
            </div>
            <div class="bottomItem">
              <!-- <el-input v-model="suffixText" type="textarea" /> -->
              <el-input v-model="routerRole.content" type="textarea" />
            </div>
            <div class="updatebox">
              <img class="updateIcon" src="@/assets/ai/updateIcon.svg" @click="handleUpdatePrompt(2000)" />
              <span class="updateText" @click="handleUpdatePrompt(2000)">更新</span>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div class="filterItem" style="height: 40px">
        <div class="topItem">
          <div class="titleBox">
            <span class="itemTitle">{{
              omitProcess ? "工作模式" : "测试模式"
            }}</span>
          </div>
          <el-switch v-model="omitProcess" size="default" @change="handleChangeProcess" />
        </div>
      </div>

      <div class="filterItem">
        <div class="topItem">
          <div class="titleBox">
            <span class="itemTitle">Max Tokens</span>
            <el-tooltip class="box-item" effect="dark" content="最大字数" placement="top">
              <img class="noticeIcon" :src="noticeIcon" />
            </el-tooltip>
          </div>
          <el-input-number v-model="maxTokens" :min="1" :max="selectDeepseekVersion === 2 ? 8192 : 4096"
            controls-position="right" size="small" />
        </div>
        <div class="bottomItem">
          <el-slider v-model="maxTokens" :min="1" :max="selectDeepseekVersion === 2 ? 8192 : 4096" />
        </div>
      </div>

      <div class="filterItem">
        <div class="topItem">
          <div class="titleBox">
            <span class="itemTitle">Temperature</span>
            <el-tooltip class="box-item" effect="dark" content="答案的随机程度" placement="top">
              <img class="noticeIcon" :src="noticeIcon" />
            </el-tooltip>
          </div>
          <el-input-number v-model="Temperature" :min="0" :max="2" :step="0.1" controls-position="right" size="small" />
        </div>
        <div class="bottomItem">
          <el-slider v-model="Temperature" :min="0" :max="2" :step="0.1" />
        </div>
      </div>

      <div class="filterItem">
        <div class="topItem">
          <div class="titleBox">
            <span class="itemTitle">Top-P</span>
            <el-tooltip class="box-item" effect="dark" content="模型只会考虑概率最高的前top-p%的词汇" placement="top">
              <img class="noticeIcon" :src="noticeIcon" />
            </el-tooltip>
          </div>
          <el-input-number v-model="TopP" :min="0.1" :max="1" :step="0.1" controls-position="right" size="small" />
        </div>
        <div class="bottomItem">
          <el-slider v-model="TopP" :min="0.1" :max="1" :step="0.1" />
        </div>
      </div>

      <div class="filterItem">
        <div class="topItem">
          <div class="titleBox">
            <span class="itemTitle">Top-K</span>
            <el-tooltip class="box-item" effect="dark" content="" placement="top">
              <img class="noticeIcon" :src="noticeIcon" />
            </el-tooltip>
          </div>
          <el-input-number v-model="TopK" :min="0" :max="100" :step="1" controls-position="right" size="small" />
        </div>
        <div class="bottomItem">
          <el-slider v-model="TopK" :min="0" :max="100" :step="1" />
        </div>
      </div>

      <div class="filterItem">
        <div class="topItem">
          <div class="titleBox">
            <span class="itemTitle">Frequency Penalty</span>
            <el-tooltip class="box-item" effect="dark" content="" placement="top">
              <img class="noticeIcon" :src="noticeIcon" />
            </el-tooltip>
          </div>
          <el-input-number v-model="FrequencyPenalty" :min="-2" :max="2" :step="0.1" controls-position="right"
            size="small" />
        </div>
        <div class="bottomItem">
          <el-slider v-model="FrequencyPenalty" :min="-2" :max="2" :step="0.1" />
        </div>
      </div>
    </div>

    <div class="modalSelectBox"
      :style="{ width: pageType === 1 ? hideLeft ? '250px' : '57px' : hideLeft ? '10vw' : '57px' }">
      <div class="showBox">
        <el-checkbox-group v-if="hideLeft" v-model="modalTypeSelect" @change="handleChangeModalType">
          <el-checkbox class="selectBox" v-for="(item, index) in modalTypeDataList" :key="index" :label="item.label"
            :value="item.value" style="display: block" />
          <!-- <el-checkbox class="selectBox" label="Deepseek" :value="1" />
          <el-checkbox class="selectBox" label="硅基流动" :value="2" />
          <el-checkbox class="selectBox" label="阿里云" :value="3" /> -->
        </el-checkbox-group>

        <!-- <el-checkbox
          class="selectBox"
          v-model="showDeepseek"
          label="Deepseek"
          size="default"
        /> -->

        <div class="indentationBox" @click="handleHideLeft">
          <img class="indentationIcon" v-if="hideLeft" src="@/assets/ai/indentation.svg" />
          <img class="indentationIcon" v-else src="@/assets/ai/indentationRight.svg" />
        </div>
      </div>
    </div>

    <div class="dialogBox" :style="{
      width: isPhone ? '100vw' : hideLeft ? '' : 'calc((100vw - 57px))',
    }">
      <div class="bigContent" :style="{
        height: pageType === 1 ? 'calc(100% - 100px)' : '',
      }">
        <div class="contentBox" v-for="(item, index) in modalTypeDataList" :key="index" :style="{
          width: item.isShow
            ? isPhone
              ? '100%'
              : modalTypeSelect && modalTypeSelect.length === 1
                ? '100%'
                : ''
            : '0px',
          padding: item.isShow ? '' : '0px',
        }">
          <div class="contentTitleBox" v-if="!isPhone">
            <div>
              <div class="contentTitle" v-if="item.value === 2 && item.isShow" @click="handleShowPhoneChangeBox">
                硅基流动
              </div>
              <div class="contentTitle" v-if="item.value === 1 && item.isShow" @click="handleShowPhoneChangeBox">
                Deepseek
              </div>
              <div class="contentTitle" v-if="item.value === 3 && item.isShow" @click="handleShowPhoneChangeBox">
                阿里云
              </div>
              <div class="contentTitle" v-if="item.value === 4 && item.isShow" @click="handleShowPhoneChangeBox">
                通义千问
              </div>
              <div class="phoneModalSelectBox" v-if="item.isShow && showPhoneChange">
                <div class="phoneModal" v-for="(item, index) in modalTypeDataList" :key="index"
                  @click="handlePhoneChangeModal(item.value)">
                  {{ item.label }}
                </div>
              </div>
            </div>

            <div class="rightBox" v-if="item.isShow && isPhone">
              <img class="optionIcon" v-if="showPhoneOption" src="@/assets/ai/activeOption.svg"
                @click="handleShowPhoneOption" />
              <img v-else class="optionIcon" src="@/assets/ai/option.svg" @click="handleShowPhoneOption" />

              <div class="phoneRightOptionBox" v-if="item.isShow && showPhoneOption">
                <div class="OptionItem" style="height: 40px">
                  <div class="topItem">
                    <div class="titleBox">
                      <span class="itemTitle">{{
                        omitProcess ? "工作模式" : "测试模式"
                      }}</span>
                    </div>
                    <el-switch v-model="omitProcess" size="default" @change="handleChangeProcess" />
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="boxContentBox" v-if="item.isShow" @scroll="handleScroll(item.value)" ref="boxContentBoxRef"
            :id="'gjldBox' + item.value">
            <div class="contentItem" v-for="(subItem, subIndex) in item.messageList" :key="subIndex" :style="{
              justifyContent:
                subItem.role === 'assistant' || subItem.role === 'default'
                  ? 'flex-start'
                  : 'flex-end',
            }">
              <!-- @scroll="handleScroll" -->
              <div v-if="subItem.role === 'user'" style="width: 100%" class="defaultItem userItem">
                <div class="reloadBox" @click="handleQuestionReload(subItem, item)">
                  <img class="img" src="@/assets/ai/reloadIcon.svg" />
                </div>
                <div class="userText">
                  {{ subItem.content }}
                </div>
              </div>

              <div v-if="subItem.loading" class="loading">
                <div class="loadingTextBox">
                  {{
                    subItem.loadingContent
                      ? subItem.loadingContent
                      : "思考中..."
                  }}
                </div>
                <div class="loadingBox" v-loading="subItem.loading"></div>
              </div>

              <div v-if="subItem.role === 'assistant'" class="defaultItem assistantItem"
                :style="{ maxWidth: isPhone ? '100%' : '' }">
                <div class="descText" v-if="subItem.descResponseText" v-html="subItem.descResponseText"></div>
                <div class="contentText" v-if="subItem.content" v-html="subItem.content"></div>
              </div>
              <!-- v-if="
                  subItem.role === 'default' && !subItem.loading && !omitProcess
                " -->
              <!-- noHiden  1 代表保留  0代表不保留 -->
              <div v-if="
                omitProcess
                  ? subItem.noHiden === 1 && subItem.role === 'default'
                  : subItem.role === 'default' &&
                  !subItem.loading &&
                  subItem.noHiden === 1
              " class="defaultItem roleDefaultItem" :style="{ maxWidth: isPhone ? '100%' : '' }">
                <div class="descText" v-if="subItem.descResponseText" v-html="subItem.descResponseText"></div>
                <div class="contentText" v-if="subItem.content" v-html="subItem.content"></div>

                <div class="depthAnalysis" @click="handleDepthAnalysis(item, subItem)" v-if="
                  subIndex + 1 === item.messageList.length &&
                  subItem.content !== '无法理解，请换个说法' &&
                  subItem.content !== '请求超时，请稍后重试！' &&
                  subItem.showBtn !== '1' &&
                  subItem.userSemanticsIsSuccess
                ">
                  ai深度分析
                </div>

                <div class="depthAnalysis" @click="handleUseRoleQuestion(item, subItem)" v-if="
                  subIndex + 1 === item.messageList.length &&
                  !subItem.userSemanticsIsSuccess
                ">
                  角色说明分析
                </div>
              </div>
            </div>

            <div class="toolBox">
              <div class="deleteBox" v-if="item.showReload && !showController" style="margin-right: 16px">
                <img class="deleteIcon" src="@/assets/ai/reloadSmallIcon.svg" @click="handleBottomReload(item)" />
                <span class="deleteText" @click="handleBottomReload(item)">刷新</span>
              </div>

              <div class="deleteBox" v-if="item.showCopy && !showController" style="margin-right: 16px">
                <img class="deleteIcon" src="@/assets/ai/copyIcon.svg" @click="handleCopyContent(item)" />
                <span class="deleteText" @click="handleCopyContent(item)">复制</span>
              </div>

              <div class="deleteBox" v-if="
                item.messageList &&
                item.messageList.length >= 3 &&
                !showController
              ">
                <img class="deleteIcon" src="@/assets/ai/deleteIcon.svg" @click="handleDeleteMessageList(item)" />
                <span class="deleteText" @click="handleDeleteMessageList(item)">删除</span>
              </div>
            </div>
          </div>
        </div>

        <div class="contentBox" id="gjldBox" :style="{ marginLeft: showAliYun ? 0 : '10vw' }" v-if="false">
          <div class="contentTitle">硅基流动</div>
          <div class="contentItem" v-for="(item, index) in messageList" :key="index" :style="{
            justifyContent:
              item.role === 'assistant' ? 'flex-start' : 'flex-end',
          }">
            <div v-if="item.role === 'user'" class="defaultItem userItem" :style="{ maxWidth: isPhone ? '100%' : '' }">
              {{ item.content }}
            </div>

            <div v-if="item.loading" class="loading">
              <div class="loadingTextBox">思考中...</div>
              <div class="loadingBox" v-loading="item.loading"></div>
            </div>

            <div v-if="item.role === 'assistant'" class="defaultItem assistantItem"
              :style="{ maxWidth: isPhone ? '100%' : '' }">
              <div class="descText" v-if="item.descResponseText">
                {{ item.descResponseText }}
              </div>
              <div class="contentText" v-if="item.content">
                {{ item.content }}
              </div>
            </div>
          </div>
        </div>
        <!-- v-if="showDeepseek" -->
        <div class="contentBox" id="aliyunBox" style="margin-left: 16px" v-if="false">
          <div class="contentTitle">
            <!-- <el-select
              v-model="selectDeepseekVersion"
              class="m-2"
              placeholder="Select"
              style="width: 200px"
              @change="handleChangeVersion"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> -->
          </div>
          <div class="contentItem" v-for="(item, index) in deepseekMessageList" :key="index" :style="{
            justifyContent:
              item.role === 'assistant' ? 'flex-start' : 'flex-end',
          }">
            <div v-if="item.role === 'user'" class="defaultItem userItem" :style="{ maxWidth: isPhone ? '100%' : '' }">
              {{ item.content }}
            </div>

            <div v-if="item.loading" class="loading">
              <div class="loadingTextBox">思考中...</div>
              <div class="loadingBox" v-loading="item.loading"></div>
            </div>

            <div v-if="item.role === 'assistant'" class="defaultItem assistantItem"
              :style="{ maxWidth: isPhone ? '100%' : '' }">
              <div class="descText" v-if="item.descResponseText">
                {{ item.descResponseText }}
              </div>
              <div class="contentText" v-if="item.content" v-html="item.content"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="inputBox" :style="{
        width: pageType === 1 ? 'calc(100% - 32px)' : isPhone ? '100vw' : hideLeft ? '' : '80vw',
        marginLeft: pageType === 1 ? 0 : hideLeft ? '' : 'calc((20vw - 57px) / 2)',
      }">
        <!-- <div class="showBox">
        <el-checkbox
          class="selectBox"
          v-model="showDeepseek"
          label="Deepseek"
          size="default"
        />
      </div> -->

        <el-input class="input" v-model="userInput" placeholder="给数智助手发消息" @keyup.enter="handleSendRequest"
          type="textarea" :autosize="{ minRows: 1, maxRows: 4 }" />

        <div class="bottomInput">
          <div class="leftBox">
            <div :class="selectDeepseekVersion === 2
              ? 'handleV3 handleV3Select'
              : 'handleV3'
              " @click="handleChangeVersion">
              深度思考 (R1)
            </div>

            <!-- <div v-if="isPhone">
              <div
                class="changeBigBox"
                v-for="(item, index) in modalTypeDataList"
                :key="index"
              >
                <div
                  class="phoneChangeBox"
                  v-if="item.isShow"
                  @click="handleShowPhoneChangeBox"
                >
                  {{ item.label }}
                </div>
                <div
                  class="phoneModalSelectBox"
                  v-if="item.isShow && showPhoneChange"
                >
                  <div
                    class="phoneModal"
                    v-for="(item, index) in modalTypeDataList"
                    :key="index"
                    @click="handlePhoneChangeModal(item.value)"
                  >
                    {{ item.label }}
                  </div>
                </div>
              </div>
            </div> -->
          </div>

          <div class="sendBox" @click="handleSendRequest" v-if="!showController">
            <img class="iconImg" src="@/assets/ai/searchIconBlue.png" />
          </div>
          <div class="sendBox" @click="handleStop" v-if="showController">
            <img class="iconImg" src="@/assets/ai/stopIcon.png" />
          </div>
        </div>
        <!-- <button class="btn" @click="handleSendRequest" v-if="!showController">
        发送
      </button>

      <div class="stopBox" @click="handleStop" v-if="showController">
        <img class="stopIcon" src="@/assets/ai/stopIcon.png" />
        <text class="stopText">终止生成</text>
      </div> -->
      </div>
    </div>

    <!-- <div class="stopBox" @click="handleStop" v-if="showController">
      <img class="stopIcon" src="@/assets/ai/stopIcon.png" />
      <text class="stopText">终止生成</text>
    </div> -->

    <div style="display: none">
      <RobotDialogueBox ref="RobotDialogueBoxRef" currentServerPartDetail="null" allServerPartIdList="[]" />
    </div>
  </div>
</template>