<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">
                  <el-col :span="8">
                    <el-form-item label="模块分类:">
                      <!-- 此处需要处理为只有admin账号可编辑 -->
                      <!-- <el-cascader
                        v-model="it.category_id"
                        clearable
                        :options="categoryList"
                        :props="props"
                        :show-all-levels="false"
                        @change="onChangeCategory"
                        placeholder="请选择模块分类"
                      /> -->
                      <!-- {{ $store.state.user }} -->
                      <!-- <el-select
                        v-if="$store.state.user.id == 2"
                        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> -->
                      <span>{{ getCategory(it.category_id) }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="模块名称:">
                      <!-- <el-input
                       
                        class="input-item"
                        v-model="it.name"
                        placeholder="请填写模块名称"
                      /> -->
                      <span >{{ 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 :span="3" :offset="5">
                    <el-form-item v-if="$store.state.user.id == 2">
                      <div class="btn-save">
                        <el-tooltip
                          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
                          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"
                @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 } 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(this.comList);
      },
      immediate: true, //立即执行
      deep: true,
    },
    comIndex: {
      handler(val) {
        if (val <= 0) return;
        this.comList = this.comList.map((it) => {
          it.isEdit = 2;
          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'
      }
    };
  },
  mounted() {
    this.initCategoryList();
    console.log(this.$store.state.user);
  },
  methods: {
    /* 获取分类名称 */
    getCategory(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));
      if (data.category) {
        delete data.category;
      }
      data.attrs = JSON.stringify(data.attrs);
      data.code = data.name;
      data.status = 5;
      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;
        });
      } else {
        updateTemplate(data).then((res) => {
          if (res.status != 200) return;
          _this.$alert("模板信息更新成功");
          _this.$emit("onRefresh");
        });
      }
    },
    /* 获取模块分类 */
    //获取模板分类信息
    async initCategoryList() {
      let _this = this;
      let res = await getAllList();
      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() {},
    //更新产品属性
    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);
    },
    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: flex;
  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>
