<template>
  <div class="com-formual">
    <el-button @click="searchEx">检索</el-button>

    <!-- 显示匹配到的结果 -->
    <div v-if="matchResults.length" class="match-results">
      <div
        v-for="(item, index) in matchResults"
        :key="index"
        class="match-item"
      >
        <div class="match-content">
          <span>原始值: {{ item }}</span>
          <!-- <span>替换后: {{ item  }}</span> -->
        </div>
        <div class="actions">
          <el-button size="small" @click="replaceItem(item)">替换</el-button>
        </div>
      </div>
      <div style="display: flex; justify-content: flex-end; margin-top: 20px">
        <el-button type="primary" @click="replaceAll">批量替换</el-button>
      </div>
    </div>
  </div>
</template>
    
    <script>
import {
  searchSourceData,
  deleteSourceData,
  batch_content,
} from "@/api/sourceData";
/* import { search } from "core-js/fn/symbol"; */
import LuckyExcel from "luckyexcel"; //引入LuckyExcel
import axios from "axios";
export default {
  name: "SourceEs",
  emits: ["onPicked", "close"],
  props: {
    TemList: {
      type: Array,
      default: [],
    },
  },
  components: {},
  data() {
    return {
      tableCode: "",
      tableList: [],
      showConfirm: false,
      fileLoadStatus: false,
      showSearch: false,
      position: {
        tb: "",
        c: 0,
        r: 0,
        sheet: "",
        value: "",
      },
      dataIntro: "",
      textInfo: "",
      loading: false, // 增加 loading 状态
      searchResult: {},
      matchResults: [], // 存储匹配到的结果
    };
  },
  mounted() {
    this.initTableList();
  },
  methods: {
    /* searchEx() {
      let allMatches = [];

      this.TemList.forEach((el) => {
        const matches = el.content.match(
          /\[[A-Z0-9]+-[A-Z0-9]+-[0-9]+-[0-9]+\]/g
        );
        if (matches) {
          allMatches = [...allMatches, ...matches];
        }
      });
      // 去重
      this.matchResults = [...new Set(allMatches)];
    }, */
    /*  searchEx() {
      let allMatches = [];

      this.TemList.forEach((el) => {
        // 匹配特定格式的编号
        const pattern = /[【\[][A-Z0-9]+-[A-Z0-9]+-[0-9]+-[0-9]+[】\]]/g;
        const matches = el.content.match(pattern);

        if (matches) {
          matches.forEach((match) => {
            // 检查是否符合 FT8-RP-00-XXX 格式
            if (match.includes("FT8-RP-00-")) {
              allMatches.push(match);
            }
          });
        }
      });

      this.matchResults = [...new Set(allMatches)];
      console.log("匹配结果：", this.matchResults);
    }, */
    searchEx() {
      let allMatches = [];

      this.TemList.forEach((el) => {
        // 创建临时 div 来解析 HTML 内容
        const tempDiv = document.createElement("div");
        tempDiv.innerHTML = el.content;
        const plainText = tempDiv.textContent || tempDiv.innerText;

        // 分别匹配中文括号和英文括号
        const patterns = [
          /【([A-Z]{1,4}[0-9]{0,2})-([A-Z]{1,4}[0-9]{0,2})-([0-9]{2})-([0-9]{2,3})】/g,
          /\[([A-Z]{1,4}[0-9]{0,2})-([A-Z]{1,4}[0-9]{0,2})-([0-9]{2})-([0-9]{2,3})\]/g,
        ];

        patterns.forEach((pattern) => {
          let match;
          while ((match = pattern.exec(plainText)) !== null) {
            const fullMatch = match[0];
            const segments = [match[1], match[2], match[3], match[4]];

            // 验证每个段落的格式
            const isValid = segments.every((segment) => segment.length > 0);

            if (isValid) {
              allMatches.push(fullMatch);
            }
          }
        });
      });

      this.matchResults = [...new Set(allMatches)];
      console.log("匹配结果：", this.matchResults);

      // 调试用：打印每个匹配的详细信息
      this.matchResults.forEach((match) => {
        console.log("找到匹配:", match);
        // 根据括号类型选择不同的切片方式
        const content = match.startsWith("【")
          ? match.slice(1, -1)
          : match.slice(1, -1);
        const parts = content.split("-");
        console.log("分段:", parts);
      });
    },

    // 更新 escapeRegExp 方法以支持两种括号类型
    escapeRegExp(string) {
      const isChinese = string.startsWith("【");
      const content = isChinese
        ? string.replace(/^【|】$/g, "")
        : string.replace(/^\[|\]$/g, "");
      const escaped = content.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
      return isChinese ? `\\【${escaped}\\】` : `\\[${escaped}\\]`;
    },

    // 新增分类方法
    categorizeByType(matches) {
      const result = {
        RP: [], // 模板位置
        IR: [], // 中间层位置
        WE: [], // 技术报告位置
        other: [], // 其他
      };

      matches.forEach((match) => {
        const cleanMatch = match.replace(/[\[\]]/g, "");
        if (cleanMatch.includes("-RP-")) {
          result.RP.push(match);
        } else if (cleanMatch.includes("-IR-")) {
          result.IR.push(match);
        } else if (cleanMatch.includes("-WE-")) {
          result.WE.push(match);
        } else {
          result.other.push(match);
        }
      });

      return result;
    },

    // 添加新的辅助方法来判断文档类型
    getDocumentType(code) {
      if (code.includes("-RP-")) return "template_location";
      if (code.includes("-IR-")) return "middle_layer_location";
      if (code.includes("-WE-")) return "tech_report_location";
      return "other_location";
    },

    // 修改格式化请求参数的方法
    formatRequestParams(locations) {
      const locationArray = Array.isArray(locations) ? locations : [locations];

      // 初始化请求参数对象
      const params = {
        template_location: [],
        middle_layer_location: [],
        tech_report_location: [],
        other_location: [],
      };

      // 根据不同类型分类存储
      locationArray.forEach((location) => {
        const cleanLocation = location.replace(/[\[\]]/g, "");
        const type = this.getDocumentType(cleanLocation);
        console.log("params", type);
        // 为每种类型创建对应长度的空数组
        Object.keys(params).forEach((key) => {
          if (type === key) {
            params[key].push(cleanLocation);
          } else {
            params[key].push("");
          }
        });
      });

      return params;
    },

    // 单个替换
    replaceItem(item) {
      // 去掉方括号
      const cleanItem = item.replace(/[\[\]]/g, "");
      this.$confirm(`确认替换 ${item}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const params = this.formatRequestParams(cleanItem);
            const response = await axios.post(
              `${process.env.VUE_APP_BASE_API}/project-raw-data/batch-content`,
              params,
              {
                headers: {
                  "Content-Type": "application/json",
                },
              }
            );

            if (response.status === 200 && response.data) {
              // 修改获取替换值的逻辑
              const replacementValue =
                response.data.data.input_item_contents[0].content;

              if (replacementValue) {
                this.TemList.forEach((el, index) => {
                  this.$set(
                    this.TemList[index],
                    "content",
                    el.content.replace(
                      new RegExp(this.escapeRegExp(item), "g"),
                      replacementValue
                    )
                  );
                });

                this.matchResults = this.matchResults.filter(
                  (match) => match !== item
                );
                this.$message.success("替换成功");
                this.$emit("close"); // 成功后触发关闭事件
              } else {
                this.$message.warning("未获取到替换内容");
              }
            } else {
              this.$message.error("获取替换内容失败");
            }
          } catch (error) {
            console.error("替换失败:", error);
            this.$message.error(error.response?.data?.message || "替换失败");
          }
        })
        .catch(() => {
          // 取消操作
        });
    },
    /*批量替换 */
    replaceAll() {
      this.loadingAll = true;

      this.$confirm(
        `确认批量替换 ${this.matchResults.length} 项内容?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          try {
            // 清理所有项的方括号
            const cleanItems = this.matchResults.map((item) =>
              item.replace(/[\[\]]/g, "")
            );
            const params = this.formatRequestParams(cleanItems);
            const response = await axios.post(
              `${process.env.VUE_APP_BASE_API}/project-raw-data/batch-content`,
              params,
              {
                headers: {
                  "Content-Type": "application/json",
                },
              }
            );

            if (response.status === 200 && response.data) {
              // 修改这里，使用与单个替换相同的数据结构
              const replacementValues =
                response.data.data.input_item_contents.map(
                  (item) => item.content
                );
              // 添加验证：检查是否所有值都为 null
              if (replacementValues.every((value) => value === null)) {
                this.$message.warning("所有替换内容均无效，请检查数据");
                return;
              }

              // 添加验证：检查是否存在 null 值
              const nullCount = replacementValues.filter(
                (value) => value === null
              ).length;
              if (nullCount > 0) {
                this.$message.warning(
                  `${nullCount} 项内容无法替换，请检查数据`
                );
                return;
              }
              if (replacementValues.length > 0) {
                this.TemList.forEach((el, index) => {
                  let updatedContent = el.content;
                  this.matchResults.forEach((item, idx) => {
                    const replacementValue = replacementValues[idx];
                    if (replacementValue) {
                      updatedContent = updatedContent.replace(
                        new RegExp(this.escapeRegExp(item), "g"),
                        replacementValue
                      );
                    }
                  });
                  this.$set(this.TemList[index], "content", updatedContent);
                });

                this.matchResults = [];
                this.$message.success("批量替换成功");
                this.$emit("close"); // 成功后触发关闭事件
              } else {
                this.$message.warning("未获取到替换内容");
              }
            } else {
              this.$message.error("获取替换内容失败");
            }
          } catch (error) {
            console.error("批量替换失败:", error);
            this.$message.error(
              error.response?.data?.message || "批量替换失败"
            );
          }
        })
        .catch(() => {
          // 取消操作
        })
        .finally(() => {
          this.loadingAll = false;
        });
    },
    // 辅助方法：转义正则表达式特殊字符
    // 修改 escapeRegExp 方法
    /*   escapeRegExp(string) {
      // 先去掉首尾的方括号，然后转义特殊字符
      const content = string.replace(/^\[|\]$/g, "");
      const escaped = content.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
      return "\\[" + escaped + "\\]";
    }, */
    /* 检索当前模版的所有内容 */
    /*  searchEx() {
      console.log("TemList", this.TemList);
      this.TemList.map((el) => {
         const matches = el.content.match(/\[[A-Z0-9]+-[A-Z0-9]+-[0-9]+-[0-9]+\]/g);
        console.log("matches",matches);
        return matches || []; // 如果没有匹配到返回空数组
        el.content = el.content.replace(
          /\[[A-Z0-9]+-[A-Z0-9]+-[0-9]+-[0-9]+\]/g,
          (match) => {
            // match 是匹配到的原始文本，例如 [FT7-RP-00-012]
            // 这里可以根据需求对 match 进行处理
            return `${match}1`; // 例如：替换后的[FT7-RP-00-012]
            // 或者返回其他处理结果
          }
        );
        return el;
      });
    }, */
    /* ai检索 */
    initTableList() {
      let _this = this;
      searchSourceData({ page: 1, pageSize: 999, status: 5 }).then((res) => {
        if (res.status != 200) return;
        _this.tableList = res.data.dataList;
      });
    },
  },
};
</script>
    
<style lang="scss" scoped>
.match-results {
  margin-top: 20px;

  .match-item {
    padding: 10px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .match-content {
      flex: 1;
      display: flex;
      gap: 20px;
    }

    .actions {
      margin-left: 10px;
    }
  }
}
</style>
    