<template>
  <div class="editor-attribute" v-if="com != null">
    <el-form>
      <template v-for="(sub, subIndex) in filteredAttrs">
        <template v-if="com.type == 'TextArea'">
          <template v-if="isTextAreaType(sub.type)">
            <el-form-item :label="sub.id + ':'"
              ><!--  + ' (引用名:[' + sub.id + '])' -->
              <!-- <el-input
                type="textarea"
                @input="updateAllReferences(sub, $event)"
                v-model="sub.content"
              ></el-input> -->
              <span @click="toggleBackground(sub.id)" style="cursor: pointer">{{
                sub.content
              }}</span>
            </el-form-item>
          </template>
          <template v-if="sub.type == 'formual'">
            <el-form-item :label="sub.id + ':'"
              ><!-- + ' (引用名:[' + sub.id + '])' -->
              <!-- <el-input type="textarea" v-model="sub.formula"></el-input> -->
              <span @click="toggleBackground(sub.id)" style="cursor: pointer">{{
                sub.formula
              }}</span>
            </el-form-item>
          </template>
          <template v-if="sub.type == 'sourceData'">
            <el-form-item :label="sub.id + ':'"
              ><!-- + ' (引用名:[' + sub.id + '])' -->
              {{ formatSourceData(sub.id, sub.formula) }}
            </el-form-item>
          </template>
        </template>
      </template>
    </el-form>

    <el-dialog
      :visible.sync="dialogVisible"
      append-to-body
      v-el-drag-dialog
      width="300"
      custom-class="prod-verify"
      title="编辑表头"
    >
      <headerSetting
        :headerItemName="headerItemName"
        @onSetHeader="onSetHeader"
      ></headerSetting>
    </el-dialog>
  </div>
</template>

<script>
import headerSetting from "../headerSetting";
import elDragDialog from "@/directive/el-drag-dialog";
import { getAllCategory, createTemplate, updateTemplate } from "@/api/template";
import { searchSourceDataCategory } from "@/api/sourceData";
import { searchDocumentCategory } from "@/api/document";
import { searchTemplateCategory, searchTemplate } from "@/api/template";

export default {
  name: "attributes",
  components: { headerSetting },
  directives: { elDragDialog },
  emits: ["onRefresh"],
  props: {
    com: {
      type: Object,
      default: () => null,
    },
  },
  watch: {
    com: {
      handler(newVal) {
        if (newVal && newVal.content) {
          this.processContent();
        }
      },
      deep: true,
    },
  },
  data() {
    return {
      dialogVisible: false,
      activeNames: "0",
      categoryList: [],
      articleCategoryList: [],
      activeHeaderIndex: -1,
      headerItemName: "",
      props: {
        value: "id",
        label: "name",
        children: "children",
      },
      processedAttrs: [],
    };
  },
  computed: {
    filteredAttrs() {
      console.log("processedAttrs", this.processedAttrs);
      return this.processedAttrs;
    },
  },
  mounted() {
    this.initCategoryList();
    if (this.com && this.com.content) {
      this.processContent();
    }
  },
  methods: {
    toggleBackground(id) {
      const element = document.getElementById(id);
      if (element) {
        if (element.style.backgroundColor === "yellow") {
          element.style.backgroundColor = "";
        } else {
          element.style.backgroundColor = "yellow";
        }
      }
    },
    updateAllReferences(val, newValue) {
      this.com.attrs.map((el) => {
        if (el.name == val.name) {
          el.content = newValue;
        }
      });

      /*  this.processedAttrs.forEach((attr) => {
        if (attr.id === id) {
          attr.content = newValue;
        }
      });

      // Update the original com.attrs as well
      if (this.com && this.com.attrs) {
        this.com.attrs.forEach((attr) => {
          if (attr.id === id) {
            attr.content = newValue;
          }
        });
      }

      // Update the content of the component
      if (this.com && this.com.content) {
        const regex = new RegExp(`\\{\\{${id}\\}\\}`, "g");
        this.com.content = this.com.content.replace(regex, `{{${newValue}}}`);
      } */
    },
    isTextAreaType(type) {
      return ![
        "pager",
        "constant",
        "attr",
        "formual",
        "sourceData",
        "Directory",
      ].includes(type);
    },

    extractTemplates(content) {
      const templateRegex = /\{\{(.*?)\}\}/g;
      let match;
      const templates = [];

      while ((match = templateRegex.exec(content)) !== null) {
        templates.push(match[1].trim());
      }

      return templates;
    },

    processContent() {
      if (this.com && this.com.content) {
        const templates = this.extractTemplates(this.com.content);

        if (this.com.attrs && Array.isArray(this.com.attrs)) {
          this.processedAttrs = this.com.attrs.filter(
            (el) => templates.includes(el.id) || el.type === "formual"
          );
        }
      } else {
        this.processedAttrs = [];
      }
    },
    formatSourceData(id, e) {
      const pattern = /\[(.*?)\]\[(.*?)\]\[(.*?)\]\[(.*?)\]/;
      const items = e.match(pattern);
      const dataIndex = items[4].split(",");
      return `${id}=${items[2]}.${items[3]}.${String.fromCharCode(
        65 + parseInt(dataIndex[1])
      )}${parseInt(dataIndex[0]) + 1}`;
    },
    async onSaveTemplate(e) {
      const data = { ...e, attrs: JSON.stringify(e.attrs), status: 5 };
      delete data.category;

      if (data.id === undefined || this.saveAs) {
        const res = await createTemplate(data);
        if (res.status === 200) {
          data.id = res.data;
          this.com.id = res.data;
          this.$alert("模板信息保存成功");
          this.$emit("onRefresh");
          this.saveAs = false;
        }
      } else {
        const res = await updateTemplate(data);
        if (res.status === 200) {
          this.$alert("模板信息更新成功");
          this.$emit("onRefresh");
        }
      }
    },
    async initCategoryList() {
      const res = await searchTemplateCategory({
        page: 1,
        pageSize: 99,
        status: 5,
      });
      if (res.status === 200) {
        this.categoryList = res.data.dataList || [];
        for (const category of this.categoryList) {
          category.dataList = await this.getTemplateList(category.id);
        }
      }
    },
    async getTemplateList(categoryId) {
      const res = await searchTemplate({
        page: 1,
        pageSize: 999,
        category_id: categoryId,
        status: 5,
      });
      if (res.status === 200) {
        return res.data.dataList.map((item) => ({
          ...item,
          attrs: JSON.parse(item.attrs),
        }));
      }
      return [];
    },
    onModify(index, subIndex, headerIndex) {
      this.currentIndex = index;
      this.componentIndex = subIndex;
      this.activeHeaderIndex = headerIndex;
      this.headerItemName =
        this.components[index].components[subIndex].attrs.tableHeader[
          headerIndex
        ];
      this.dialogVisible = true;
    },
    onSetHeader(name) {
      if (this.currentIndex >= 0) {
        const header =
          this.components[this.currentIndex].components[this.componentIndex]
            .attrs.tableHeader;
        if (this.activeHeaderIndex >= 0) {
          header[this.activeHeaderIndex] = name;
        } else {
          header.push(name);
        }
      }
      this.$emit("onSetComponents", [...this.components]);
      this.dialogVisible = false;
    },
    onInsert(index, subIndex) {
      this.currentIndex = index;
      this.componentIndex = subIndex;
      this.headerItemName = "";
      this.dialogVisible = true;
    },
    onDeleteHeaderItem(index, subIndex, headerIndex) {
      this.components[index].components[subIndex].attrs.tableHeader.splice(
        headerIndex,
        1
      );
      this.$emit("onSetComponents", [...this.components]);
    },
    onSetActiveIndex(e) {
      this.activeHeaderIndex = e === this.activeHeaderIndex ? -1 : e;
    },
  },
};
</script>

<style lang="scss">
@import "./index.scss";
</style>