<template>
  <div class="editor">
    <draggable
      v-model="comList"
      @add="onAdd"
      @update="onDragEnd"
      group="itxst"
      animation="300"
      :style="draggableStyle"
      handle=".drag-handle"
      :scroll="true"
      :scrollSensitivity="100"
      :scrollSpeed="20"
    >
      <transition-group style="display: block; min-height: 100vh">
        <template v-for="(it, index) in comList">
          <div
            class="layers"
            :key="index"
            :class="comIndex == index ? 'active-layer' : ''"
          >
            <div class="drag-handle" draggable>
              <svg-icon icon-class="drag" />
            </div>
            <!-- :options="categoryList":props="props" -->
            <div style="padding: 10px 0">
              <el-form label-position="left" class="inline-form">
                <el-row :gutter="24" style="margin-left: 0; margin-right: 0">
                  <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
                    <el-form-item label="模块分类:">
                      <!-- 此处需要处理为只有admin账号可编辑 -->
                      <!--  <el-cascader
                        v-if="showCategorySelect(it)"
                        v-model="it.category_id"
                        clearable
                        :options="categoryList"
                        :props="props"
                        :show-all-levels="false"
                        @change="onChangeCategory(it)"
                        placeholder="请选择模块分类"
                      />
                     {{ $store.state.user }} -->
                      <!-- <el-select
                        v-if="showCategorySelect(it)"
                        v-model="it.category_id"
                        placeholder="请选择模块分类"
                        size="large"
                        style="width: 80%"
                      >
                        <el-option
                          v-for="item in categoryList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>  v-else-->

                      <span @click="enableSelect(it)" style="cursor: pointer">{{
                        getCategory(it.category_id)
                      }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
                    <el-form-item label="模块名称:">
                      <!--  <el-input
                        v-if="showCategoryName(it)"
                        class="input-item"
                        v-model="it.name"
                        placeholder="请填写模块名称"
                      />v-else -->
                      <span @click="enableName(it)" style="cursor: pointer">{{
                        it.name
                      }}</span>
                    </el-form-item>
                  </el-col>
                  <!-- <el-col :span="6">
                    <el-form-item label="模块描述:">
                      <el-input
                        v-if="$store.state.user.id == 2"
                        class="input-item"
                        v-model="it.intro"
                        placeholder="请填写模块介绍"
                      />
                      <span v-else>{{ it.intro }}</span>
                    </el-form-item>
                  </el-col> -->
                  <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
                    <el-form-item v-if="$store.state.user.id == 2">
                      <div class="btn-save">
                        <el-tooltip
                          v-if="type !== 'document'"
                          class="item"
                          effect="dark"
                          content="保存模块"
                          placement="top"
                        >
                          <el-button
                            size="mini"
                            @click="onSaveTemplate(it)"
                            icon="el-icon-document-add"
                            circle
                          >
                          </el-button>
                        </el-tooltip>
                        <!--  <el-tooltip
                          class="item"
                          effect="dark"
                          content="另存为"
                          placement="top"
                        >
                          <el-button
                            circle
                            size="mini"
                            @click="onSaveAs(it)"
                            v-if="it.id > 0"
                            icon="el-icon-document-copy"
                          >
                          </el-button>
                        </el-tooltip> -->
                        <el-button
                          circle
                          size="mini"
                          v-if="it.isEdit !== 1"
                          @click="onEdit(index, 1)"
                        >
                          <svg-icon icon-class="edit" />
                        </el-button>
                        <el-button
                          circle
                          size="mini"
                          @click="onEdit(index, 2)"
                          icon="el-icon-view"
                          v-else
                        >
                        </el-button>
                        <el-tooltip
                          v-if="!templateId && type !== 'document'"
                          class="item"
                          effect="dark"
                          content="删除"
                          placement="top"
                        >
                          <el-button
                            circle
                            size="mini"
                            @click="onRemove(index)"
                          >
                            <svg-icon icon-class="delete"
                          /></el-button>
                        </el-tooltip>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div class="main" @click="onSetActive(index)">
              <component
                :is="it.type"
                :com="it"
                :coms="comList"
                :currentIndex="index"
                :isAdmin="isAdmin"
                :insertCmd="insertCmd"
                @onUpdate="onUpdate"
                @onUpdateAttr="onUpdateAttr"
                @onUpdata="onUpdata"
                @onUpdateProdAttr="onUpdateProdAttr"
                :isEdit="it.isEdit"
              />
            </div>
            <!--  <div class="label">
              {{ it.name }}
              <div class="del">
                <svg-icon
                  @click="onEdit(index, 1)"
                  v-if="it.isEdit !== 1"
                  icon-class="edit"
                  style="color: #fff; margin-right: 10px"
                />
                <svg-icon
                  @click="onEdit(index, 2)"
                  v-else
                  icon-class="view"
                  style="color: #fff; margin-right: 10px"
                />
                <svg-icon
                  @click="onRemove(index)"
                  icon-class="delete"
                  style="color: #fff; margin-left: 10px"
                />
              </div>
            </div> -->
          </div>
        </template>
        <template v-if="comList.length <= 0">
          <div class="editor-empty" :key="-1">
            <el-empty description="请拖放组件至当前页面" />
          </div>
        </template>
      </transition-group>
    </draggable>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import Table from "./components/Table";
import TextArea from "./components/TextArea";
import Empty from "./components/Empty";
import {
  getAllList,
  createTemplate,
  updateTemplate,
  treeCategory,
} from "@/api/template";
export default {
  name: "editor",
  emits: [
    "onSetActiveIndex",
    "onDelete",
    "onInsert",
    "onLoadArticle",
    "onRebuild",
    "onSetComs",
  ],
  components: {
    Table,
    TextArea,
    draggable,
    Empty,
  },
  props: {
    coms: {
      type: Array,
      default: null,
    },
    comIndex: {
      type: Number,
      default: 0,
    },
    templateCate: {
      type: Array,
      default: () => {
        return [];
      },
    },
    insertCmd: {
      type: Object,
      default: null,
    },
    isAdmin: {
      type: Number,
      default: 2,
    },
  },
  watch: {
    coms: {
      handler(val) {
        if (val == null) return;
        this.comList = JSON.parse(JSON.stringify(val));
        console.log('comList',this.comList);
      },
      immediate: true, //立即执行
      deep: true,
    },
    comIndex: {
      handler(val) {
        if (val <= 0) return;
        this.comList = this.comList.map((it) => {
          it.isEdit = 2;
          it.selDisabled = true;
          it.valDisabled = true;
          if (
            typeof it.category_id === "string" &&
            it.category_id.includes(" ")
          ) {
            it.category_id = it.category_id.split(" ");
          } else if (!Array.isArray(it.category_id)) {
            // 如果不是数组，将其转换为包含单个元素的数组
            it.category_id = [it.category_id].filter(Boolean);
          }
          return it;
        });
      },
      immediate: true, //立即执行
      deep: true,
    },
  },
  data() {
    return {
      showEditor: false,
      operation: "",
      id: 0,
      comList: [],
      categoryList: [],
      props: {
        value: "id",
        label: "name",
        children: "children",
        checkStrictly: true,
      },
      saveAs: false,
      draggableStyle: {
        width: "100%",

        overflowY: "auto",
      },
      type: "",
    };
  },
  mounted() {
    this.initCategoryList();
    this.type = this.$route.query.type;
    this.templateId = this.$route.query.templateId;
  },
  methods: {
    showCategoryName(item) {
      return (
        this.type == "module" &&
        this.$store.state.user.id == 2 &&
        !item.valDisabled
      );
    },
    enableName(item) {
      item.valDisabled = false;
      this.$forceUpdate();
    },
    showCategorySelect(item) {
      return (
        this.type === "module" &&
        this.$store.state.user.id === 2 &&
        !item.selDisabled
      );
    },
    /* 选择分类 */
    enableSelect(item) {
      item.selDisabled = true;
      console.log(item);
      this.$forceUpdate();
    },
    /* 获取分类名称 */
    getCategory(item) {
      const findCategory = (list, id) => {
        for (const el of list) {
          if (el.id === id) {
            return el.name;
          }
          if (el.children) {
            const name = findCategory(el.children, id);
            if (name) {
              return name;
            }
          }
        }
        return null;
      };

      return findCategory(this.categoryList, item) || "请选择分类";
      /* return (
        this.categoryList.find((el) => el.id === item)?.name || "请选择分类"
      ); */
    },
    onSaveAs(e) {
      this.saveAs = true;
      this.onSaveTemplate(e);
    },
    /* 保存模块 */
    onSaveTemplate(e) {
      let _this = this;
      /* e.category_id='1' */
      let data = JSON.parse(JSON.stringify(e));
      console.log(data);
      if (data.category) {
        delete data.category;
      }
      data.attrs = JSON.stringify(data.attrs);
      data.code = data.name;
      data.status = 5;
      // 检查 category_id 是否为数组
      if (Array.isArray(e.category_id)) {
        // 如果是数组,取最后一个元素作为 category_id
        data.category_id = e.category_id[e.category_id.length - 1];
      } else {
        // 如果不是数组,直接赋值
        data.category_id = e.category_id;
      }

      if (data.id == undefined || this.saveAs) {
        createTemplate(data).then((res) => {
          if (res.status != 200) return;
          data.id = res.data;
          e.id = res.data;

          _this.$alert("模板信息保存成功");
          _this.$emit("onRefresh");
          this.saveAs = false;
          data.selDisabled = false;
          data.valDisabled = false;
          this.$forceUpdate();
        });
      } else {
        updateTemplate(data).then((res) => {
          if (res.status != 200) return;
          _this.$alert("模板信息更新成功");
          _this.$emit("onRefresh");
          data.selDisabled = false;
          data.valDisabled = false;
          this.$forceUpdate();
        });
      }
    },
    /* 获取模块分类 */
    //获取模板分类信息
    async initCategoryList() {
      let _this = this;
      let res = await treeCategory(); //await getAllList();
      console.log(res);
      this.categoryList =
        res.data; /* //this.processDataForCascader(res.data); */
    },
    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;
    },
    onChangeCategory(item, value) {
      const selectedId = value[value.length - 1];
      item.category_id = selectedId;
      // You can now use the selected ID as needed
    },
    //更新产品属性
    onUpdateProdAttr(comIndex, attrIndex, data) {
      this.comList[comIndex].attrs[attrIndex].content = data;

      let attrName = this.comList[comIndex].attrs[attrIndex].attrs.name;
      let attrType = this.comList[comIndex].attrs[attrIndex].attrs.type;

      for (var i = 0; i < this.comList.length; i++) {
        for (var j = 0; j < this.comList[i].attrs.length; j++) {
          if (this.comList[i].attrs[j].type == "ProductAttr") {
            if (
              this.comList[i].attrs[j].attrs.name == attrName &&
              this.comList[i].attrs[j].attrs.type == attrType
            ) {
              this.comList[i].attrs[j].content = data;
            }
          }
        }
      }
      this.$emit("onRebuild", this.comList);
    },

    onUpdateAttr(comIndex, attrIndex, data) {
      this.comList[comIndex].attrs[attrIndex].content = data;

      let dataType = this.comList[comIndex].attrs[attrIndex].type;
      let dataId = this.comList[comIndex].attrs[attrIndex].data;

      for (var i = 0; i < this.comList.length; i++) {
        for (var j = 0; j < this.comList[i].attrs.length; j++) {
          if (
            this.comList[i].attrs[j].type == dataType &&
            this.comList[i].attrs[j].id == dataId
          ) {
            this.comList[i].attrs[j].content = data;
          }
        }
      }
      this.$emit("onRebuild", this.comList);
    },
    /* 修改单个值 */
    onUpdata(comIndex, attrIndex, attrId, data, type) {
      let _this = this;
      let com = _this.coms[comIndex];

      if (type === "variableNull") {
        // 只更新特定的 variableNull 属性
        if (
          com &&
          com.attrs &&
          com.attrs[attrIndex] &&
          com.attrs[attrIndex].id === attrId
        ) {
          this.$set(com.attrs[attrIndex], "content", data);
        }
      } else {
        // 原有的逻辑，更新所有相同类型的属性
        let dataType = com.attrs[attrIndex].type;
        for (var i = 0; i < _this.coms.length; i++) {
          for (var j = 0; j < _this.coms[i].attrs.length; j++) {
            if (
              _this.coms[i].attrs[j].type == dataType &&
              _this.coms[i].attrs[j].id == attrId
            ) {
              _this.coms[i].attrs[j].content = data;
            }
          }
        }
      }

      _this.$emit("onRebuild", _this.coms);
    },
    onRemove(index) {
      this.$emit("onDelete", index);
    },
    onEdit(e, state) {
      this.comList = this.comList.map((it) => {
        it.isEdit = 2;
        return it;
      });
      if (state == 1) {
        this.comList[e].isEdit = 1;
        this.onSetActive(e);
      }

      this.$emit("onRebuild", this.comList);
    },
    onAdd(e) {
      e.preventDefault();
      e.stopPropagation();
      this.$emit("onRebuild", this.comList);
    },
    onDragEnd(e) {
      e.preventDefault();
      e.stopPropagation();
      this.$emit("onRebuild", this.comList);
    },
    onUpdate(index, content) {
      let _this = this;
      this.coms[index].content = content;
    },
    //激活当前层
    onSetActive(e) {
      this.$emit("onSetActiveIndex", e);
    },
  },
};
</script>
<style lang="scss">
@import "./editor.scss";
.layers {
  margin-left: 26px;
  .drag-handle {
    position: absolute;
    top: 0;
    left: -27px;
    cursor: move;
    padding: 0 5px;
    display: flex;
    align-items: center;
    /*  background-color: #f0f0f0; */

    &:hover {
      /*  background-color: #e0e0e0; */
    }
  }

  .content-wrapper {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
  }

  .main {
    flex-grow: 1;
  }
}
.inline-form {
  display: block;
  width: 100%;
  /* flex-wrap: wrap;
  gap: 10px; */
}

.inline-form .el-form-item {
  display: flex;
  align-items: center;
  margin-bottom: 0;
  flex: 1;
  min-width: 300px;
}

.inline-form .el-form-item__label {
  flex-shrink: 0;
  width: auto;
  padding-right: 12px;
}

.inline-form .el-form-item__content {
  flex-grow: 1;
  margin-left: 0 !important;
}
.input-item {
  width: 200px;
}
</style>
