<template>
  <div class="editor-attribute" v-if="com != null">
    <el-form>
      <el-form-item label="模块分类:">
        <!--  <el-select
          v-model="com.category_id"
          placeholder="请选择模块分类"
          size="large"
          style="width: 100%"
          >
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select> -->
        <!-- @change="onChangeCategory" -->
        <el-cascader
          v-model="com.category_id"
          :options="categoryList"
          clearable
          :props="props"
          :show-all-levels="false"
          @change="onChangeCategory"
          placeholder="请选择模块分类"
        />
      </el-form-item>
     <!--  <el-form-item label="模块引用名:">
        <el-input
          v-model="com.code"
          class="input-item"
          placeholder="请填写模块引用名"
        />
      </el-form-item> -->
      <el-form-item label="模块名称:">
        <el-input
          v-model="com.name"
          class="input-item"
          placeholder="请填写模块名称"
        />
      </el-form-item>
      <el-form-item label="模块描述:">
        <el-input
          type="textarea"
          class="input-item"
          v-model="com.intro"
          placeholder="请填写模块介绍"
        />
      </el-form-item>
      <el-form-item>
        <div class="btn-save">
          <el-button type="primary" size="mini" @click="onSaveTemplate(com)"
            >保存模块</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="onSaveAs(com)"
            v-if="com.id > 0"
            >另存为</el-button
          >
        </div>
      </el-form-item>
      <!-- 文本开始-->
      <!-- <template v-for="(sub, subIndex) in com.attrs">
       
        <template v-if="com.type == 'TextArea'">
          <template
            v-if="
              sub.type != 'pager' &&
              sub.type != 'constant' &&
              sub.type != 'attr' &&
              sub.type != 'formual' &&
              sub.type != 'sourceData'&&
              sub.type !='Directory'
            "
          >
            <el-form-item :label="sub.name + ' (引用名:[' + sub.id + '])'">
              <el-input type="textarea" v-model="sub.content"></el-input>
            </el-form-item>
          </template>

          <template v-if="sub.type == 'formual'">
            <el-form-item :label="sub.name + ' (引用名:[' + sub.id + '])'">
              <el-input type="textarea" v-model="sub.formula"></el-input>
            </el-form-item>
          </template>

          <template v-if="sub.type == 'sourceData'">
            <el-form-item :label="sub.name + ' (引用名:[' + 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,
  getAllList,
} 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: () => {
        return null;
      },
    },
  },
  watch: {},
  data() {
    return {
      dialogVisible: false,
      activeNames: "0",
      categoryList: [],
      articleCategoryList: [],
      activeHeaderIndex: -1,
      headerItemName: "",
      props: {
        value: "id",
        label: "name",
        children: "children",
        checkStrictly: true,
      },
    };
  },
  mounted() {
    this.initCategoryList();
  },
  methods: {
    formatSourceData(id, e) {
      var pattern = /\[(.*?)\]\[(.*?)\]\[(.*?)\]\[(.*?)\]/;
      var reg = new RegExp(pattern);
      let items = e.match(reg);
      let data = id + "=" + items[2] + "." + items[3];

      var dataIndex = items[4];
      dataIndex = items[4].split(",");
      data +=
        "." +
        String.fromCharCode(65 + parseInt(dataIndex[1])) +
        (parseInt(dataIndex[0]) + 1);
      return data;
    },

    onSaveAs(e) {
      this.saveAs = true;
      this.onSaveTemplate();
    },

    onChangeCategory(value) {
      let _this = this;
      /* _this.com.category_id = e[1]; */
      this.com.category_id = value[value.length - 1];
    },

    onSaveTemplate(e) {
      let _this = this;
      /* e.category_id='1' */
      let data = JSON.parse(JSON.stringify(e));
      data.attrs = JSON.stringify(data.attrs);
      data.code=data.name
      data.status = 5;
      data.category_id = this.com.category_id;
      if (data.id == undefined || this.saveAs) {
        createTemplate(data).then((res) => {
          if (res.status != 200) return;
          data.id = res.data;
          _this.com.id = res.data;
          _this.$alert("模板信息保存成功");
          _this.$emit("onRefresh");
          this.saveAs = false;
        });
      } else {
        updateTemplate(data).then((res) => {
          if (res.status != 200) return;
          _this.$alert("模板信息更新成功");
          _this.$emit("onRefresh");
        });
      }
    },

    /* initCategoryList(){
          let _this=this;
          searchSourceDataCategory({page:1,pageSize:99,status:''}).then(res=>{
            _this.categoryList=res.data.sourcecategories;
            
          })
      }, */
    processDataForCascader(data) {
      console.log("Raw data:", data); // 调试原始数据
      const idMap = new Map();
      const rootItems = [];

      // First pass: create a map of all items
      data.forEach((item) => {
        const processedItem = { ...item, children: [] };
        idMap.set(item.id, processedItem);
      });

      // Second pass: build the tree structure
      data.forEach((item) => {
        if (item.parent_id === "0" || item.parent_id === 0) {
          rootItems.push(idMap.get(item.id));
        } else {
          const parent = idMap.get(parseInt(item.parent_id));
          if (parent) {
            parent.children.push(idMap.get(item.id));
          } else {
            console.warn(
              `Parent with id ${item.parent_id} not found for item:`,
              item
            );
            rootItems.push(idMap.get(item.id)); // 如果找不到父项，作为根项添加
          }
        }
      });

      console.log("Processed data:", rootItems); // 调试处理后的数据
      return rootItems;
    },
    //获取模板分类信息
    async initCategoryList() {
      let _this = this;
      let res = await getAllList();
      this.categoryList = this.processDataForCascader(res.data);
      /* let res = await searchTemplateCategory({
        page: 1,
        pageSize: 99,
        status: 5,
      });
      if (res.status != 200) return;
      _this.categoryList = res.data.dataList || [];
      for (var i = 0; i < _this.categoryList.length; i++) {
        _this.categoryList[i].dataList = await _this.getTemplateList(
          _this.categoryList[i].id
        );
      } */
    },

    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) {
        if (this.activeHeaderIndex >= 0) {
          this.components[this.currentIndex].components[
            this.componentIndex
          ].attrs.tableHeader[this.activeHeaderIndex] = name;
        } else {
          this.components[this.currentIndex].components[
            this.componentIndex
          ].attrs.tableHeader.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) {
      if (e == this.activeHeaderIndex) {
        this.activeHeaderIndex = -1;
      } else {
        this.activeHeaderIndex = e;
      }
    },
    //获取模板列表
    async getTemplateList(categoryId) {
      let _this = this;
      let res = await searchTemplate({
        page: 1,
        pageSize: 999,
        category_id: categoryId,
        status: 5,
      });
      if (res.status != 200) return [];
      let dataList = res.data.dataList.map((item) => {
        item.attrs = JSON.parse(item.attrs);
        return item;
      });
      return dataList;
    },
  },
};
</script>

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