<template>
  <div class="new-doc-container">
    <TitlePage :items="list" @jump="jump"></TitlePage>
    <div class="content">
      <inputInformationVue
        v-if="activeIndex === 0"
        @info="info"
        @change="listChange"
        @promotion="promotion"
      ></inputInformationVue>
      <div class="acticle-panel" v-if="activeIndex === 1">
        <generate-outline
          :type="type"
          @arcticle="goArcticle"
          :params="params"
          :pfjb="chapter_level"
          @change="change"
          ref="gneRef"
          @refrash="refrash"
          @changeBt="changeBt"
          :flag="reEditor"
          :arr="chapterArr"
          :files="outlineFiles"
        ></generate-outline>
        <div class="arctile-box" v-if="type == 2">
          <articlePage
            @close="close"
            :section="section"
            :title="params.tm"
            :category="params.category"
            @next="next"
            @saveToDoc="saveToDoc"
            @save="save"
            @change="changeStatus"
            @stop="stopAI"
            :end="chapterEnd"
            ref="editRef"
            @deleteFinish="deleteFinish"
          ></articlePage>
        </div>
      </div>
      <div class="acticle-panel" v-if="activeIndex == 3">
        <div class="arctile-box">
          <articlePage
            @close="promoClose"
            :section="section"
            @saveToDoc="saveToDoc"
            @save="save"
            :title="params.tm"
            :category="params.category"
            :promo="promoFlag"
            @next="next"
            @stop="stopAI"
            @reload="queryPromotionArticle"
            :end="chapterEnd"
            ref="editRef"
            @deleteFinish="deleteFinish"
          ></articlePage>
        </div>
      </div>
    </div>
  </div>
</template>
<script  lang='ts' setup>
import {
  ref,
  nextTick,
  onMounted,
  onUnmounted,
  defineSSRCustomElement,
} from "vue";
import { fetchEventSource } from "@microsoft/fetch-event-source";
import TitlePage from "./components/title.vue";
import inputInformationVue from "./xjwd/inputInformation.vue";
import articlePage from "./xjwd/article.vue";
import generateOutline from "./xjwd/generateOutline.vue";
import { message } from "ant-design-vue";
import PubsubService from "@/utils/PubsubService";
import { uploaFile } from "./xjwd/http";
import { getDocumentDetail } from "./myDocument/http";
import { set } from "lodash";

const reEditor = ref(false);
const activeIndex = ref(0);
const gneRef = ref(null);
const index = ref(0);
const childrenIndex = ref(0);
//本章结束
const chapterEnd = ref(false);
const childrenTotal = ref(0);
const thirdIndex = ref(0);
const thirdTotal = ref(0);
const total = ref(0);
const sencondArr = ref([]);
const promoFlag = ref(false);
const arcticleRef = ref(null);
const docId = ref("");
//分段
const section = ref(true);
const params = ref({});
let ctr: AbortController | null = null;
const editRef = ref(null);
const type = ref(0);
const title = ref("");
const topic = ref("");
const contentDesc = ref("");
const insertContentDesc = ref("");
const outlneContent = ref("");
const keywords = ref("");
const outline = ref("");
const category = ref("");
const initPostion = ref(-1);
const chapterArr = ref([]);
const outlineFiles = ref([]);
const kb_file = ref("");
const compose_length = ref(5000);
const chapter_level = ref("2");
// const paragraph_length = ref(500);
const paragraph_length = ref(1000);
const user_prompt = ref("");
const neekRefreshData = ref({});
const query = ref("");
const checked = ref(false);
const checkedRefrash = ref(false);
import { useUserStore } from "@/stores";
const store = useUserStore();
const user = ref(store?.user?.user || {});
import LoginAPI from "@/api/login";
const dsChecked = ref(false);

const origList = ref([
  {
    name: "01. 输入主要信息",
    checked: true,
  },
  {
    name: "02. AI生成大纲",
    checked: false,
  },
  {
    name: "03. AI生成文章",
    checked: false,
  },
]);
const promoList = ref([
  {
    name: "01. 输入主要信息",
    checked: true,
  },
  {
    name: "02. AI生成文章",
    checked: false,
  },
]);
const list = ref([
  {
    name: "01. 输入主要信息",
    checked: true,
  },
  {
    name: "02. AI生成大纲",
    checked: false,
  },
  {
    name: "03. AI生成文章",
    checked: false,
  },
]);
const jump = (i: number) => {
  if (ctr) {
    ctr.abort();
  }
  if (i == 0 && activeIndex.value != 0) {
    if (params.value.category == "宣传文案") {
      list.value[1].checked = false;
      activeIndex.value = 0;
    } else {
      list.value[1].checked = false;
      list.value[2].checked = false;
      activeIndex.value = 0;
    }
  }
};
const changeStatus = (check: boolean) => {
  checked.value = check;
};
const info = (p: {}) => {
  list.value[1].checked = true;
  params.value = p;
  type.value = 1;
  reEditor.value = false;
  activeIndex.value = 1;
};
const listChange = (name) => {
  if (name == "宣传文案") {
    list.value = promoList.value;
  } else {
    list.value = origList.value;
  }
};
const getFileDetail = (id) => {
  getDocumentDetail(id).then((res) => {
    console.log(res);
    var content = res.data.content;
    if (res.success) {
      if (editRef.value) {
        editRef.value.setInitData(res.data.content);
      }
      if (
        chapterArr.value[index.value] &&
        chapterArr.value[index.value].children
      ) {
        childrenTotal.value = chapterArr.value[index.value].children.length;
      }

      setTimeout(() => {
        if (
          childrenTotal.value != 0 &&
          childrenIndex.value < childrenTotal.value - 1
        ) {
          if (
            content.includes(
              chapterArr.value[index.value].children[childrenIndex.value]
            )
          ) {
            childrenIndex.value = childrenIndex.value + 1;
          }
          editRef.value.changeData("", 1);
          if (chapter_level.value == "2") {
            queryArticle(
              chapterArr.value[index.value],
              chapterArr.value[index.value].children[childrenIndex.value]
            );
          } else {
            queryThirdArticle(
              chapterArr.value[index.value],
              chapterArr.value[index.value].children[childrenIndex.value],
              chapterArr.value[index.value].children[childrenIndex.value]
                ? chapterArr.value[index.value].children[childrenIndex.value]
                    .children[thirdIndex.value]
                : null
            );
          }
        } else {
          // if (chapter_level.value == "2") {
          //   nextChapter();
          // } else {
          //   thirdLevelNextChapter();
          // }
          //继续下一章自己点
          chapterEnd.value = true;
          section.value = true;
        }
      }, 100);
    }
  });
};
const saveToDoc = (data) => {
  var p = data;
  p.bz1 = category.value;
  if (docId.value) {
    p.id = docId.value;
  }
  p.bz = JSON.stringify({
    arr: chapterArr.value,
    topic: topic.value,
    keywords: keywords.value,
    pfyq: compose_length.value,
    pfjb: chapter_level.value,
    outlineFiles: outlineFiles.value,
    index: index.value,
    childrenIndex: childrenIndex.value,
    tIndex: thirdIndex.value,
  });
  uploaFile(p).then((res) => {
    if (res.code == 200) {
      message.success(res.data);
      if (store && store.isLogin && store.user.user.userInfo.phone) {
        //发送短信验证
        var pamara = {
          phone: store.user.user.userInfo.phone,
          title: p.fileName,
        };
        LoginAPI.phoneMessage(pamara).then((res) => {
          if (res.success) {
            console.log("短信发送成功！");
          }
        });
      }
    }
  });
};
//保存我的文档
const save = (data) => {
  var p = data;
  p.bz1 = category.value;
  if (docId.value) {
    p.id = docId.value;
  }
  p.bz = JSON.stringify({
    arr: chapterArr.value,
    topic: topic.value,
    keywords: keywords.value,
    pfyq: compose_length.value,
    pfjb: chapter_level.value,
    outlineFiles: outlineFiles.value,
    index: index.value,
    childrenIndex: childrenIndex.value,
    tIndex: thirdIndex.value,
  });
  uploaFile(p).then((res) => {
    if (res.code == 200) {
      message.success(res.data);
    }
  });
};
//宣传文案
const promotion = (p: {}) => {
  list.value[1].checked = true;
  params.value = p;
  reEditor.value = false;
  activeIndex.value = 3;
  title.value = p.tm;
  promoFlag.value = true;
  category.value = "宣传文案";
  setTimeout(() => {
    editRef.value.changeData("", 1);
    queryPromotionArticle();
  }, 1000);
};
const promoClose = () => {
  activeIndex.value = 0;
  list.value[2].checked = false;
};
onMounted(() => {
  PubsubService.subscribe("edit", (data) => {
    func(data);
  });
});
onUnmounted(() => {
  // 防止重复订阅
  PubsubService.clearSubsByTopic("edit");
});
const func = (data) => {
  if (!reEditor.value) {
    reEditor.value = true;
    if (reEditor.value) {
      list.value[1].checked = true;
      list.value[2].checked = true;
      activeIndex.value = 1;
      type.value = 2;
      var result = JSON.parse(data.bz);
      docId.value = data.id;
      title.value = data.filename;
      category.value = data.bz1;
      section.value = true;
      checked.value = false;
      chapterArr.value = result.arr;
      topic.value = result.topic;
      outlineFiles.value = result.outlineFiles;
      keywords.value = result.keywords;
      index.value = result.index;
      params.value.tm = data.filename;
      total.value = chapterArr.value.length;
      compose_length.value = result.pfyq;
      chapter_level.value = result.pfjb;
      childrenIndex.value = result.childrenIndex;
      thirdIndex.value = result.tIndex;
    }
    getFileDetail(data.id);
  }
};
//目录数组，目录大纲字符串，题目，主题，关键字，篇幅要求，大纲级别，参考文件名称
const goArcticle = (
  arr: string | any[],
  ml: string,
  t: string,
  zt: string,
  key: string,
  pfyq: number,
  pfjb: string,
  file: string,
  queryArr: never[],
  cate: string,
  check: boolean,
  outlineFile: any[],
  ds: boolean
) => {
  list.value[2].checked = true;
  chapterEnd.value = false;
  reEditor.value = false;
  type.value = 2;
  user_prompt.value = "";
  chapterArr.value = arr;
  outline.value = ml;
  kb_file.value = file ? file : "";
  outlneContent.value = ml;
  title.value = t;
  topic.value = zt;
  keywords.value = key;
  compose_length.value = pfyq;
  chapter_level.value = pfjb;
  sencondArr.value = queryArr;
  category.value = cate;
  promoFlag.value = false;
  section.value = check;
  if (!check) {
    checked.value = true;
  } else {
    checked.value = false;
  }
  outlineFiles.value = outlineFile;
  dsChecked.value = ds;
  if (category.value.includes("论文")) {
    initPostion.value = 4;
  } else if (
    category.value.includes("工作方案") ||
    category.value.includes("建设方案")
  ) {
    initPostion.value = -1;
  } else {
    initPostion.value = -1;
  }
  //章节输出
  index.value = 0;
  total.value = arr.length;
  childrenTotal.value = arr[index.value].children.length;
  childrenIndex.value = 0;
  if (chapter_level.value == 3) {
    if (arr[index.value].children && arr[index.value].children.length > 0) {
      if (arr[index.value].children[0].children) {
        thirdTotal.value = arr[index.value].children[0].children.length;
        thirdIndex.value = 0;
      }
    }
  }
  setTimeout(() => {
    if (chapter_level.value == 2) {
      if (editRef.value) {
        var header =
          "<h2 style='text-align: center;'>" +
          title.value +
          "</h2> " +
          "<h3 style='text-align: left;'>" +
          arr[index.value].title +
          "</h3> ";

        if (chapterArr.value[index.value].title == "摘要") {
          header =
            "<h2 style='text-align: center;'>" +
            title.value +
            "</h2>" +
            `<p<span>${arr[index.value].title}</span>:<p>`;
          editRef.value.changeData(header, 1);
        } else if (chapterArr.value[index.value].title == "引言") {
          header = "<h2 style='text-align: center;'>" + title.value + "</h2>";
          editRef.value.changeData(header, 1);
        } else {
          editRef.value.changeData(header, 1);
        }
      }
      if (chapterArr.value[index.value].title != "引言") {
        queryArticle(arr[index.value], arr[index.value].children[0]);
      } else {
        justArcticle(
          chapterArr.value[index.value],
          chapter_level.value == "2" ? 0 : 1
        );
      }
    } else {
      if (editRef.value) {
        var header =
          "<h2 style='text-align: center;'>" +
          title.value +
          "</h2> " +
          "<h3 style='text-align: left;'>" +
          arr[index.value].title +
          "</h3> ";
        if (arr[index.value].children && arr[index.value].children.length > 0) {
          header +=
            "<h4 style='text-align: left;'>" +
            arr[index.value].children[0].title +
            "</h4> ";
        }
        if (chapterArr.value[index.value].title == "摘要") {
          header =
            "<h2 style='text-align: center;'>" +
            title.value +
            "</h2>" +
            `<p<span>${arr[index.value].title}</span>:<p>`;
          editRef.value.changeData(header, 1);
        } else if (chapterArr.value[index.value].title == "引言") {
          header = "<h2 style='text-align: center;'>" + title.value + "</h2>";
          editRef.value.changeData(header, 1);
        } else {
          editRef.value.changeData(header, 1);
        }
      }
      queryThirdArticle(
        arr[index.value],
        arr[index.value].children[0],
        arr[index.value].children[0]
          ? arr[index.value].children[0].children[0]
          : null
      );
    }
  }, 10);
};
const stopAI = () => {
  // index.value = 0;
  // childrenTotal.value = 0;
  // childrenIndex.value = 0;
  if (ctr) {
    ctr.abort();
  }
};
const close = () => {
  type.value = 1;
  list.value[2].checked = false;
  reEditor.value = false;
  stopAI();
  if (docId.value) {
    PubsubService.publish("jump", "myAiDocument");
  }
};
const next = (value: string) => {
  user_prompt.value = value;
  if (chapter_level.value == 2) {
    nextChapter();
  } else if (chapter_level.value == 3) {
    thirdLevelNextChapter();
  }
  chapterEnd.value = false;
};
const deleteFinish = (
  need: any,
  above_text: any,
  follow_text: any,
  org_text: any
) => {
  contentDesc.value = "";
  checkedRefrash.value = false;
  insertContentDesc.value = "";
  chapterRefrash(need, above_text, follow_text, org_text);
  console.log("deleteFinish==");
};
const change = (check: boolean) => {
  section.value = check;
  reEditor.value = false;
};
const queryArticle = async (
  fitem: never,
  item: {
    desc: string;
    title: string;
  }
) => {
  if (editRef.value) {
    editRef.value.showEndLoadingView();
  }
  var outsideArr = ["摘要"];
  if (!item) {
    if (outsideArr.includes(fitem.title)) {
      query.value = "###" + fitem.title + "\\n" + fitem.desc;
    } else if (fitem.title == "参考文献") {
      return;
    } else if (fitem.title == "关键词") {
      return;
    } else {
      query.value = "###" + title.value + "###" + fitem.title;
    }
  } else {
    query.value =
      "###" +
      title.value +
      "###" +
      fitem.title +
      "**" +
      item.title +
      "**" +
      (item.desc ? item.desc : "");
  }
  contentDesc.value = "";
  ctr = new AbortController();
  var params = new FormData();
  params.append("query", query.value);
  params.append("stream", true);
  params.append("topic", topic.value ? topic.value : "null");
  params.append("keywords", keywords.value);
  if (fitem.files) {
    var arr: any[] = [];
    var urlArr: any[] = [];
    var fileParams = "";
    var url = "";
    fitem.files.forEach((item: { checked: any; wylj: any }, index: any) => {
      if (item.checked) {
        if (item.wylj) {
          urlArr.push(item);
        } else {
          arr.push(item);
        }
      }
    });
    arr.forEach((item, index) => {
      if (index != arr.length - 1) {
        fileParams += item.name + ",";
      } else {
        fileParams += item.name;
      }
    });
    urlArr.forEach((item, index) => {
      if (index != urlArr.length - 1) {
        url += item.link + ",";
      } else {
        url += item.link;
      }
    });
    if (arr && arr.length > 0) {
      params.append("kb_file_source_name", fileParams);
    } else {
      params.append("kb_file_source_name", "");
    }
    if (urlArr && urlArr.length > 0) {
      params.append("compose_url", url);
    } else {
      params.append("compose_url", "");
    }
  } else {
    params.append("kb_file_source_name", kb_file.value ? kb_file.value : "");
  }
  params.append("outline", outlneContent.value);
  params.append("compose_length", compose_length.value);
  params.append("chapter_level", chapter_level.value);
  params.append("user_prompt", user_prompt.value);
  params.append("compose_type", category.value);
  // var zs = parseInt(compose_length.value) / sencondArr.value.length;
  // params.append(
  //   "paragraph_length",
  //   item.zsyq ? parseInt(item.zsyq) : zs.toFixed(0)
  // );
  // var zs = parseInt(compose_length.value / sencondArr.value.length);
  if (fitem.paragraph_length) {
    params.append("paragraph_length", fitem.paragraph_length);
  } else {
    params.append("paragraph_length", paragraph_length.value);
  }
  // params.append("paragraph_length", 10);

  await fetchEventSource(window.AppGlobalConfig.chatDetailUrl, {
    method: "POST",
    openWhenHidden: true,
    // mode: 'no-cors',
    body: params,
    signal: ctr.signal,
    async onmessage(msg) {
      try {
        const rData = JSON.parse(msg.data);
        console.log(msg.data);
        if (rData.status != 3) {
          contentDesc.value += rData.choices[0].delta.content
            ? rData.choices[0].delta.content
            : "";
          var bt = item ? item.title : fitem.title;
          var trimBt = bt.replace(/\s+/g, "");
          var title1 = `*${bt}**`;
          var title2 = `**${bt}**`;
          var title11 = `**${trimBt}**`;
          var title3 = `**${bt}*`;
          var title5 = `###${bt}`;
          var title6 = `#${bt}`;
          var title7 = `##${bt}`;
          var title8 = `### ${bt}`;
          var title9 = `# ${bt}`;
          var title10 = `## ${bt}`;
          if (contentDesc.value.length > title2.length) {
            if (
              !contentDesc.value.includes(title2) &&
              contentDesc.value.includes(title1)
            ) {
              contentDesc.value = contentDesc.value.replaceAll(title1, title2);
            } else if (
              !contentDesc.value.includes(title2) &&
              contentDesc.value.includes(title3)
            ) {
              contentDesc.value = contentDesc.value.replaceAll(title3, title2);
            }
          }
          
          if (contentDesc.value.indexOf("</think>") !== -1) {
            contentDesc.value = contentDesc.value.slice(contentDesc.value.indexOf("</think>")+8)
          }
          if (!item) {
            contentDesc.value = contentDesc.value.replaceAll(title2, "");
            contentDesc.value = contentDesc.value.replaceAll(title5, "");
            contentDesc.value = contentDesc.value.replaceAll(title6, "");
            contentDesc.value = contentDesc.value.replaceAll(title7, "");
            contentDesc.value = contentDesc.value.replaceAll(title8, "");
            contentDesc.value = contentDesc.value.replaceAll(title9, "");
            contentDesc.value = contentDesc.value.replaceAll(title10, "");
            contentDesc.value = contentDesc.value.replaceAll(title11, "");
          }
          if (editRef.value) {
            editRef.value.changeData(contentDesc.value, 2);
          }
        } else if (rData.status == 3) {
          if (editRef.value) {
            setTimeout(() => {
              if (fitem.title == "摘要") {
                editRef.value.handleSearch("摘要:");
              }
              setTimeout(() => {
                editRef.value.changeData("", 3);
              }, 500);
            }, 1000);
          }
        }
      } catch (e) {
        console.log("--出错");
      }
    },
    onclose() {
      setTimeout(() => {
        if (childrenIndex.value < childrenTotal.value - 1) {
          childrenIndex.value = childrenIndex.value + 1;
          queryArticle(
            chapterArr.value[index.value],
            chapterArr.value[index.value].children[childrenIndex.value]
          );
        } else {
          if (!section.value) {
            nextChapter();
          } else {
            chapterEnd.value = true;
            if (
              initPostion.value != -1 &&
              index.value < initPostion.value - 1
            ) {
              nextChapter();
            } else {
              if (initPostion.value == -1) {
                if (index.value == chapterArr.value.length - 1) {
                  chapterEnd.value = false;
                  message.success("文章已生成！");
                  if (editRef.value) {
                    editRef.value.loadFinshed();
                  }
                  if (checked.value && editRef.value) {
                    editRef.value.save();
                  }
                }
              } else {
                //自动补全参考文献
                if (index.value == chapterArr.value.length - 2) {
                  nextChapter();
                }
              }
            }
          }
        }
      }, 3000);
    },
    onerror(err) {
      message.error("请求异常！");

      throw err;
    },
    onopen() {},
  });
};
//宣传文案
const queryPromotionArticle = async () => {
  if (ctr) {
    ctr.abort();
    ctr = null;
  }
  if (editRef.value) {
    editRef.value.showEndLoadingView();
  }
  contentDesc.value = "";
  ctr = new AbortController();
  var p = { query: params.value.tm, stream: true };
  if (params.value.zt) {
    p['"topic"'] = params.value.zt ? params.value.zt : "";
  }
  var keyword = "";
  var keywordArr = [];
  if (params.value.gjz) {
    keywordArr = params.value.gjz.split("、");
  }
  if (keywordArr) {
    keywordArr.forEach((item, index) => {
      if (index != keywordArr.length - 1) {
        keyword += item + ",";
      } else {
        keyword += item;
      }
    });
  }
  if (keyword) {
    p["keywords"] = keyword;
  }
  var raw = JSON.stringify(p);
  await fetchEventSource(window.AppGlobalConfig.chatPublicitylUrl, {
    method: "POST",
    openWhenHidden: true,
    // mode: 'no-cors',
    body: raw,
    headers: {
      "Content-Type": "application/json",
    },
    signal: ctr.signal,
    async onmessage(msg) {
      try {
        const rData = JSON.parse(msg.data);
        console.log(msg.data);
        if (rData.status != 3) {
          contentDesc.value += rData.choices[0].delta.content
            ? rData.choices[0].delta.content
            : "";

          if (editRef.value) {
            editRef.value.changeData(contentDesc.value, 2);
          }
        } else if (rData.status == 3) {
          if (editRef.value) {
            setTimeout(() => {
              editRef.value.changeData("", 3);
              chapterEnd.value = false;
              message.success("文章已生成！");
              if (editRef.value) {
                editRef.value.loadFinshed();
              }
              setTimeout(() => {
                if (checked.value && editRef.value) {
                  editRef.value.save();
                }
              }, 1);
            }, 1000);
          }
        }
      } catch (e) {
        console.log("--出错");
      }
    },
    onclose() {},
    onerror(err) {
      message.error("请求异常！");

      throw err;
    },
    onopen() {},
  });
};
const changeBt = (obj) => {
  var index = obj.i;
  var oldData = obj.oldTxt;
  var newData = obj.newTxt;
  if (editRef.value) {
    editRef.value.changeTxt(oldData, newData);
    setTimeout(() => {
      if (gneRef.value) {
        gneRef.value.changeOrigenTitle(index);
      }
    }, 1);
  }
};
const refrash = (data: {
  item?: any;
  second?: any;
  next?: any;
  thirdItem?: any;
  level?: any;
  nextFirstItem?: any;
}) => {
  neekRefreshData.value = data;
  var fitem = data.item;
  var sitem = data.second;
  var next = data.next;
  var titem = data.thirdItem;
  var level = data.level;
  var nextFirstItem = data.nextFirstItem;
  var nextlevel = data.next ? (data.next.key.includes("-") ? -1 : 1) : 1;
  if (fitem.title != fitem.orgbt) {
    if (editRef.value) {
      editRef.value.changeTxt(fitem.orgbt, fitem.title);
    }
  }
  nextTick(() => {
    setTimeout(() => {
      if (editRef.value) {
        if (level == 2) {
          if (sitem.title != sitem.orgbt) {
            editRef.value.changeTxt(sitem.orgbt, sitem.title);
            setTimeout(() => {
              editRef.value.refrashData(
                sitem.title,
                next ? next.title : "null",
                nextlevel,
                nextFirstItem ? nextFirstItem.title : "",
                fitem ? fitem.title : ""
              );
            }, 500);
          } else {
            editRef.value.refrashData(
              sitem.title,
              next ? next.title : "null",
              nextlevel,
              nextFirstItem ? nextFirstItem.title : "",
              fitem ? fitem.title : ""
            );
          }
        } else {
          nextlevel =
            countSubstrings(next.key, "-") != countSubstrings(titem.key, "-")
              ? 1
              : -1;
          if (sitem.title != sitem.orgbt || titem.title != titem.orgbt) {
            if (titem.title != titem.orgbt) {
              editRef.value.changeTxt(titem.orgbt, titem.title);
            }
            setTimeout(() => {
              if (sitem.title != sitem.orgbt) {
                editRef.value.changeTxt(sitem.orgbt, sitem.title);
              }
            }, 10);
            setTimeout(() => {
              editRef.value.refrashData(
                titem.title,
                next ? next.title : "null",
                nextlevel,
                nextFirstItem ? nextFirstItem.title : "",
                fitem ? fitem.title : ""
              );
            }, 500);
          } else {
            editRef.value.refrashData(
              titem.title,
              next ? next.title : "null",
              nextlevel,
              nextFirstItem ? nextFirstItem.title : "",
              fitem ? fitem.title : ""
            );
          }
        }
      }
    }, 10);
  });
};
const countSubstrings = (str, subStr) => {
  // 将subStr中的特殊字符转义
  subStr = subStr.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  // 使用正则表达式进行全局匹配，并计算匹配的数量
  return (str.match(new RegExp(subStr, "g")) || []).length;
};
const chapterRefrash = async (
  need: any,
  above_text: any,
  follow_text: any,
  org_text: any
) => {
  var data = neekRefreshData.value;
  var fitem = data.item;
  var sitem = data.second;
  var titem = data.thirdItem;
  var currentTitle = "";
  if (data.level == 2) {
    currentTitle = sitem.title;
    if (sitem) {
      query.value =
        "###" +
        title.value +
        "###" +
        fitem.title +
        "**" +
        sitem.title +
        "**" +
        (sitem.desc ? sitem.desc : "");
    } else {
      query.value = "###" + title.value + "###" + fitem.title;
    }
  } else {
    currentTitle = titem.title;
    var desc = titem.desc ? titem.desc : "";
    query.value =
      "###" +
      title.value +
      "###" +
      fitem.title +
      "**" +
      sitem.title +
      "**" +
      `---${titem.title}---` +
      desc;
  }

  // query.value = "###第一章 绪论 **1.1 研究背景**";
  contentDesc.value = "";
  ctr = new AbortController();
  var params = new FormData();
  params.append("query", query.value);
  params.append("stream", true);
  params.append("topic", topic.value ? topic.value : "null");
  params.append("keywords", keywords.value);
  if (above_text) {
    params.append("above_text", above_text);
  }
  if (follow_text) {
    params.append("follow_text", follow_text);
  }
  if (fitem.files) {
    var arr: any[] = [];
    var urlArr: any[] = [];
    var fileParams = "";
    var url = "";
    fitem.files.forEach((item: { checked: any; wylj: any }, index: any) => {
      if (item.checked) {
        if (item.wylj) {
          urlArr.push(item);
        } else {
          arr.push(item);
        }
      }
    });
    arr.forEach((item, index) => {
      if (index != arr.length - 1) {
        fileParams += item.name + ",";
      } else {
        fileParams += item.name;
      }
    });
    urlArr.forEach((item, index) => {
      if (index != urlArr.length - 1) {
        url += item.link + ",";
      } else {
        url += item.link;
      }
    });
    if (arr && arr.length > 0) {
      params.append("kb_file_source_name", fileParams);
    } else {
      params.append("kb_file_source_name", "");
    }
    if (urlArr && urlArr.length > 0) {
      params.append("compose_url", url);
    } else {
      params.append("compose_url", "");
    }
  } else {
    params.append("kb_file_source_name", kb_file.value ? kb_file.value : "");
  }
  params.append("compose_length", compose_length.value);
  params.append("chapter_level", chapter_level.value);
  params.append("user_prompt", user_prompt.value);
  if (fitem.paragraph_length) {
    params.append("paragraph_length", fitem.paragraph_length);
  } else {
    params.append("paragraph_length", paragraph_length.value);
  }
  // params.append("paragraph_length", 10);

  await fetchEventSource(window.AppGlobalConfig.chatDetailUrl, {
    method: "POST",
    openWhenHidden: true,
    // mode: 'no-cors',
    body: params,
    signal: ctr.signal,
    async onmessage(msg) {
      try {
        const rData = JSON.parse(msg.data);
        console.log(msg.data);
        // if (rData.status != 3) {
        //   var title = neekRefreshData.value.second;
        //   if (contentDesc.value == `**${item.title}**`) {
        //     var desc = rData.choices[0].delta.content;
        //     insertContentDesc.value += desc;
        //   } else {
        //     contentDesc.value += rData.choices[0].delta.content;
        //   }
        // } else if (rData.status == 3) {
        //   contentDesc.value = rData.choices[0].delta.content;
        //  contentDesc.value= contentDesc.value.replaceAll(`**${item.title}**`, "");
        //   editRef.value.toInsertData(item.title, contentDesc.value, 3);
        // }
        var ctitle = currentTitle.replaceAll("*", "");
        if (rData.status != 3) {
          contentDesc.value += rData.choices[0].delta.content
            ? rData.choices[0].delta.content
            : "";
          contentDesc.value = contentDesc.value.replaceAll(
            `---${ctitle}---`,
            `**${ctitle}**`
          );
          console.log("1111111---------------------")
          if (!need) {
            if (
              contentDesc.value.length > ctitle.length + 4 &&
              contentDesc.value.includes(ctitle)
            ) {
              checkedRefrash.value = true;
            }
            contentDesc.value = contentDesc.value.replaceAll(
              `**${ctitle}**`,
              ""
            );
          }
          if (checkedRefrash.value) {
            editRef.value.toInsertData(contentDesc.value, 2);
          }
        } else if (rData.status == 3) {
          setTimeout(() => {
            if (checkedRefrash.value) {
              editRef.value.toInsertData("", 3);
            } else {
              editRef.value.toInsertData(org_text, 2);
              setTimeout(() => {
                editRef.value.toInsertData("", 3);
              }, 10);
            }
          }, 1000);
        }
      } catch (e) {
        console.log("--出错");
      }
    },
    onclose() {},
    onerror(err) {
      throw err;
    },
    onopen() {},
  });
};
const queryThirdArticle = async (
  fitem: never,
  item: { title: string },
  citem: { title: any }
) => {
  var outsideArr = ["摘要"];
  if (outsideArr.includes(fitem.title)) {
    query.value = "###" + fitem.title + "\\n" + fitem.desc;
  } else if (fitem.title == "参考文献") {
    return;
  } else if (fitem.title == "关键词") {
    return;
  } else {
    if (citem) {
      var desc = citem.desc ? citem.desc : "";
      query.value =
        "###" +
        title.value +
        "###" +
        fitem.title +
        "**" +
        item.title +
        "**" +
        `---${citem.title}---` +
        desc;
    } else if (item) {
      query.value =
        "###" + title.value + "###" + fitem.title + "**" + item.title + "**";
    } else {
      query.value = "###" + title.value + "###" + fitem.title;
    }
  }
  if (editRef.value) {
    editRef.value.showEndLoadingView();
  }
  ctr = new AbortController();
  contentDesc.value = "";
  var params = new FormData();
  params.append("query", query.value);
  params.append("stream", true);
  params.append("topic", topic.value ? topic.value : "null");
  params.append("keywords", keywords.value);
  //大纲选的文件或者段落文件 优先段落
  if (fitem.files) {
    var arr: any[] = [];
    var urlArr: any[] = [];
    var fileParams = "";
    var url = "";
    fitem.files.forEach((item: { checked: any; wylj: any }, index: any) => {
      if (item.checked) {
        if (item.wylj) {
          urlArr.push(item);
        } else {
          arr.push(item);
        }
      }
    });
    arr.forEach((item, index) => {
      if (index != arr.length - 1) {
        fileParams += item.name + ",";
      } else {
        fileParams += item.name;
      }
    });
    urlArr.forEach((item, index) => {
      if (index != urlArr.length - 1) {
        url += item.link + ",";
      } else {
        url += item.link;
      }
    });
    if (arr && arr.length > 0) {
      params.append("kb_file_source_name", fileParams);
    } else {
      params.append("kb_file_source_name", "");
    }
    if (urlArr && urlArr.length > 0) {
      params.append("compose_url", url);
    } else {
      params.append("compose_url", "");
    }
  } else {
    params.append("kb_file_source_name", kb_file.value ? kb_file.value : "");
  }
  params.append("user_prompt", user_prompt.value);
  params.append("compose_length", compose_length.value);
  params.append("chapter_level", chapter_level.value);
  if (fitem.paragraph_length) {
    params.append("paragraph_length", fitem.paragraph_length);
  } else {
    params.append("paragraph_length", paragraph_length.value);
  }
  await fetchEventSource(window.AppGlobalConfig.chatDetailUrl, {
    method: "POST",
    openWhenHidden: true,
    // mode: 'no-cors',
    body: params,
    signal: ctr.signal,
    async onmessage(msg) {
      try {
        const rData = JSON.parse(msg.data);
        console.log(msg.data);

        if (rData.status != 3) {
          contentDesc.value += rData.choices[0].delta.content
            ? rData.choices[0].delta.content
            : "";
            console.log("2222222222222")
          if (contentDesc.value.indexOf("</think>") !== -1) {
            contentDesc.value = contentDesc.value.slice(contentDesc.value.indexOf("</think>")+8)
          }
          if (citem) {
            contentDesc.value = contentDesc.value.replaceAll(
              `---${citem.title}---`,
              `**${citem.title}**`
            );
            if (contentDesc.value.includes("---")) {
              contentDesc.value = contentDesc.value.replaceAll("---", "**");
            }
          }
          //只有一级标题
          if (!item) {
            var title1 = `**${fitem.title}**`;
            contentDesc.value = contentDesc.value.replaceAll(title1, "");
          }
          if (editRef.value) {
            editRef.value.changeData(contentDesc.value, 2);
          }
        } else if (rData.status == 3) {
          if (editRef.value) {
            setTimeout(() => {
              if (fitem.title == "摘要") {
                editRef.value.handleSearch("摘要:");
              }
              setTimeout(() => {
                editRef.value.changeData("", 3);
              }, 500);
            }, 1000);
          }
        }
      } catch (e) {
        console.log("--出错");
      }
    },
    onclose() {
      setTimeout(() => {
        if (thirdIndex.value < thirdTotal.value - 1) {
          thirdIndex.value = thirdIndex.value + 1;
          queryThirdArticle(
            chapterArr.value[index.value],
            chapterArr.value[index.value].children[childrenIndex.value],
            chapterArr.value[index.value].children[childrenIndex.value]
              .children[thirdIndex.value]
          );
        } else {
          if (childrenIndex.value < childrenTotal.value - 1) {
            childrenIndex.value = childrenIndex.value + 1;
            thirdIndex.value = 0;
            thirdTotal.value =
              chapterArr.value[index.value].children[
                childrenIndex.value
              ].children.length;
            if (editRef.value) {
              var header =
                "<h4 style='text-align: left;'>" +
                chapterArr.value[index.value].children[childrenIndex.value]
                  .title +
                "</h4> ";
              editRef.value.changeData(header, 1);
            }
            queryThirdArticle(
              chapterArr.value[index.value],
              chapterArr.value[index.value].children[childrenIndex.value],
              chapterArr.value[index.value].children[childrenIndex.value]
                .children[thirdIndex.value]
            );
          } else {
            if (!section.value) {
              thirdLevelNextChapter();
            } else {
              setTimeout(() => {
                chapterEnd.value = true;
                if (
                  initPostion.value != -1 &&
                  index.value < initPostion.value - 1
                ) {
                  thirdLevelNextChapter();
                } else {
                  if (initPostion.value == -1) {
                    if (index.value == chapterArr.value.length - 1) {
                      chapterEnd.value = false;
                      message.success("文章已生成！");
                      if (editRef.value) {
                        editRef.value.loadFinshed();
                      }
                      if (checked.value && editRef.value) {
                        editRef.value.save();
                      }
                    }
                  } else {
                    //自动补全参考文献
                    if (index.value == chapterArr.value.length - 2) {
                      thirdLevelNextChapter();
                    }
                  }
                }
              }, 1000);
            }
          }
        }
      }, 3000);
    },
    onerror(err) {
      message.error("请求异常！");

      throw err;
    },
    onopen() {},
  });
};
const nextChapter = () => {
  if (index.value < total.value - 1) {
    chapterEnd.value = false;
    index.value = index.value + 1;
    childrenTotal.value = chapterArr.value[index.value].children.length;
    childrenIndex.value = 0;
    if (editRef.value) {
      var header =
        "<h3 style='text-align: left;'>" +
        chapterArr.value[index.value].title +
        "</h3> ";

      if (chapterArr.value[index.value].title == "参考文献") {
        header =
          "<h4 style='text-align: left;color:#000'>" +
          chapterArr.value[index.value].title +
          " </h4> " +
          "<p>" +
          chapterArr.value[index.value].desc +
          "</p>";
      }
      if (chapterArr.value[index.value].title == "引言") {
        header = "";
      }
      if (chapterArr.value[index.value].title == "关键词") {
        var desc = chapterArr.value[index.value].desc
          .replaceAll(":", "")
          .replaceAll("；", "、")
          .replaceAll(": ", "");
        header = `<p>${
          chapterArr.value[index.value].title
        }:<span>${desc}</span> </p>`;
      }

      editRef.value.changeData(header, 1);
      setTimeout(() => {
        if (chapterArr.value[index.value].title == "关键词") {
          editRef.value.handleSearch("关键词:");
        }
      }, 50);
      setTimeout(() => {
        if (
          chapterArr.value[index.value].title != "关键词" &&
          chapterArr.value[index.value].title != "参考文献" &&
          chapterArr.value[index.value].title != "引言"
        ) {
          queryArticle(
            chapterArr.value[index.value],
            chapterArr.value[index.value].children[0]
          );
        } else {
          if (
            chapterArr.value[index.value].title == "关键词" ||
            chapterArr.value[index.value].title == "参考文献"
          ) {
            setTimeout(() => {
              chapterEnd.value = true;
              if (
                initPostion.value != -1 &&
                index.value < initPostion.value - 1
              ) {
                nextChapter();
              }
              if (index.value == chapterArr.value.length - 1) {
                chapterEnd.value = false;
                message.success("文章已生成！");
                if (editRef.value) {
                  editRef.value.loadFinshed();
                }
                if (checked.value && editRef.value) {
                  editRef.value.save();
                }
              }
            }, 1000);
          } else {
            if (chapterArr.value[index.value].title == "引言") {
              justArcticle(chapterArr.value[index.value], 0);
            }
          }
        }
      }, 500);
    }
  } else {
    setTimeout(() => {
      chapterEnd.value = true;
      if (index.value == chapterArr.value.length - 1) {
        message.success("文章已生成！");
        chapterEnd.value = false;
        if (editRef.value) {
          editRef.value.loadFinshed();
        }
        if (checked.value && editRef.value) {
          editRef.value.save();
        }
      }
    }, 1000);
  }
};
const thirdLevelNextChapter = () => {
  if (index.value < total.value - 1) {
    chapterEnd.value = false;
    index.value = index.value + 1;
    childrenTotal.value = chapterArr.value[index.value].children.length;
    childrenIndex.value = 0;
    thirdTotal.value = chapterArr.value[index.value].children[
      childrenIndex.value
    ]
      ? chapterArr.value[index.value].children[childrenIndex.value].children
          .length
      : 0;
    thirdIndex.value = 0;
    if (editRef.value) {
      var header =
        "<h3 style='text-align: left;'>" +
        chapterArr.value[index.value].title +
        "</h3> ";
      if (chapterArr.value[index.value].children[childrenIndex.value]) {
        header =
          header +
          "<h4 style='text-align: left;'>" +
          chapterArr.value[index.value].children[childrenIndex.value].title +
          "</h4>";
      }

      if (chapterArr.value[index.value].title == "参考文献") {
        header =
          "<h3 style='text-align: left;color:#000'>" +
          chapterArr.value[index.value].title +
          " </h3> " +
          "<p>" +
          chapterArr.value[index.value].desc +
          "</p>";
      }
      if (chapterArr.value[index.value].title == "引言") {
        header = "";
      }
      if (chapterArr.value[index.value].title == "关键词") {
        var desc = chapterArr.value[index.value].desc
          .replaceAll(":", "")
          .replaceAll("；", "、")
          .replaceAll(": ", "");
        header = `<p><strong>${
          chapterArr.value[index.value].title
        }:</strong><span>${desc}</span> </p>`;
      }
      editRef.value.changeData(header, 1);
      setTimeout(() => {
        if (
          chapterArr.value[index.value].title != "关键词" &&
          chapterArr.value[index.value].title != "参考文献" &&
          chapterArr.value[index.value].title != "引言"
        ) {
          queryThirdArticle(
            chapterArr.value[index.value],
            chapterArr.value[index.value].children[childrenIndex.value],
            chapterArr.value[index.value].children[childrenIndex.value]
              ? chapterArr.value[index.value].children[childrenIndex.value]
                  .children[thirdIndex.value]
              : null
          );
        } else {
          if (
            chapterArr.value[index.value].title == "关键词" ||
            chapterArr.value[index.value].title == "参考文献"
          ) {
            setTimeout(() => {
              chapterEnd.value = true;
              if (
                initPostion.value != -1 &&
                index.value < initPostion.value - 1
              ) {
                thirdLevelNextChapter();
              }
              if (index.value == chapterArr.value.length - 1) {
                message.success("文章已生成！");
                chapterEnd.value = false;
                if (editRef.value) {
                  editRef.value.loadFinshed();
                }
                if (checked.value && editRef.value) {
                  editRef.value.save();
                }
              }
            }, 1000);
          } else {
            if (chapterArr.value[index.value].title == "引言") {
              justArcticle(chapterArr.value[index.value], 1);
            }
          }
        }
      }, 500);
    }
  } else {
    setTimeout(() => {
      chapterEnd.value = true;
      if (index.value == chapterArr.value.length - 1) {
        message.success("文章已生成！");
        chapterEnd.value = false;
        if (editRef.value) {
          editRef.value.loadFinshed();
        }
        if (checked.value && editRef.value) {
          editRef.value.save();
        }
      }
    }, 1000);
  }
};
const thirdLevelNextChapter1 = () => {
  if (index.value < total.value - 1) {
    chapterEnd.value = false;
    index.value = index.value + 1;
    childrenTotal.value = chapterArr.value[index.value].children.length;
    childrenIndex.value = 0;
    thirdTotal.value =
      chapterArr.value[index.value].children[
        childrenIndex.value
      ].children.length;
    thirdIndex.value = 0;
    if (editRef.value) {
      var header =
        "<h3 style='text-align: left;'>" +
        chapterArr.value[index.value].title +
        "</h3> " +
        "<h4 style='text-align: left;'>" +
        chapterArr.value[index.value].children[childrenIndex.value].title +
        "</h4>";
      editRef.value.changeData(header, 1);
    }
    queryThirdArticle(
      chapterArr.value[index.value],
      chapterArr.value[index.value].children[childrenIndex.value],
      chapterArr.value[index.value].children[childrenIndex.value].children[
        thirdIndex.value
      ]
    );
  } else {
    setTimeout(() => {
      chapterEnd.value = true;
      if (index.value == chapterArr.value.length - 1) {
        message.success("文章已生成！");
        chapterEnd.value = false;
        if (editRef.value) {
          editRef.value.loadFinshed();
        }
        if (checked.value && editRef.value) {
          editRef.value.save();
        }
      }
    }, 1000);
  }
};
//扩写引言 type 0二级目录 1三级目录

const justArcticle = async (item, type) => {
  if (editRef.value) {
    editRef.value.showEndLoadingView();
  }
  contentDesc.value = "";
  if (ctr) {
    ctr.abort();
    ctr = null;
  }
  var paragraph_length = "500";
  if (item.paragraph_length) {
    paragraph_length = item.paragraph_length;
  }
  ctr = new AbortController();
  var raw = JSON.stringify({
    query: item.desc,
    adjust_type: `扩充成一段${paragraph_length}字的段落`,
    // adjust_type: "扩充成一段10字的段落",
    stream: true,
    compose_type: category.value,
  });
  await fetchEventSource(window.AppGlobalConfig.adjustUrl, {
    method: "POST",
    openWhenHidden: true,
    headers: {
      "Content-Type": "application/json",
    },
    body: raw,
    signal: ctr.signal,
    async onmessage(msg) {
      try {
        const rData = JSON.parse(msg.data);
        console.log(msg.data);
        if (rData.status != 3) {
          contentDesc.value += rData.choices[0].delta.content
            ? rData.choices[0].delta.content
            : "";
          var bt = item.title;
          var title1 = `*${bt}**`;
          var title2 = `**${bt}**`;
          var title3 = `**${bt}*`;
          if (contentDesc.value.length > title2.length) {
            if (
              !contentDesc.value.includes(title2) &&
              contentDesc.value.includes(title1)
            ) {
              contentDesc.value = contentDesc.value.replaceAll(title1, title2);
            } else if (
              !contentDesc.value.includes(title2) &&
              contentDesc.value.includes(title3)
            ) {
              contentDesc.value = contentDesc.value.replaceAll(title3, title2);
            }
          }
          contentDesc.value = contentDesc.value.replaceAll(title2, "");
          contentDesc.value = contentDesc.value.replace("扩写", "");
          if (editRef.value) {
            editRef.value.changeData(contentDesc.value, 2);
          }
        } else if (rData.status == 3) {
          if (editRef.value) {
            setTimeout(() => {
              editRef.value.changeData("", 3);
            }, 1000);
          }
        }
      } catch (e) {
        console.log("--出错");
      }
    },
    onclose() {
      setTimeout(() => {
        if (!section.value) {
          nextChapter();
        } else {
          chapterEnd.value = true;
          if (initPostion.value != -1 && index.value < initPostion.value - 1) {
            if (type == 0) {
              nextChapter();
            } else {
              thirdLevelNextChapter();
            }
          } else {
            if (initPostion.value == -1) {
              if (index.value == chapterArr.value.length - 1) {
                message.success("文章已生成！");
                chapterEnd.value = false;
                if (editRef.value) {
                  editRef.value.loadFinshed();
                }
                if (checked.value && editRef.value) {
                  editRef.value.save();
                }
              }
            } else {
              //自动补全参考文献
              if (index.value == chapterArr.value.length - 2) {
                if (type == 0) {
                  nextChapter();
                } else {
                  thirdLevelNextChapter();
                }
              }
            }
          }
        }
      }, 3000);
    },
    onerror(err) {
      throw err;
    },
    onopen() {},
  });
};
</script>
<style lang="scss" scoped>
.new-doc-container {
  width: 100%;
  height: 100%;
  .content {
    width: 100%;
    height: calc(100% - 60px);
    .acticle-panel {
      display: flex;
      height: 100%;
      .arctile-box {
        flex: 1;
        height: 100%;
        border-left: 1px solid #e4e7ea;
      }
    }
  }
}
</style>