<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)];
    },
    // 格式化请求参数
    formatRequestParams(locations) {
      // 确保 locations 是数组
      const locationArray = Array.isArray(locations) ? locations : [locations];
      return {
        template_location: locationArray,
        middle_layer_location: locationArray.map(() => ""),
        tech_report_location: locationArray.map(() => ""),
        other_location: locationArray.map(() => ""),
      };
    },

    // 单个替换
    replaceItem(item) {
      // 去掉方括号
      const cleanItem = item.replace(/[\[\]]/g, "");
      this.$confirm(`确认替换 ${item}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            // 修改这里，确保传入数组形式的参数
            const params = this.formatRequestParams(cleanItem); /* item */
            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>
    