<template>
  <div id="tablecontainer">
    <el-tabs v-model="activeName">
      <el-tab-pane label="绘图工具" name="first"></el-tab-pane>
      <el-main>
        <el-menu mode="vertical">
          <el-submenu :index="group.name" v-for="(group, groupIndex) in drawtoolGroups" :key="groupIndex">
            <template #title>
              {{ group.name }}
              <el-button
                v-if="groupIndex !== 0"
                type="text"
                size="small"
                @click.stop="editGroupName(groupIndex)"
              >编辑名称</el-button>
              <el-button
                v-if="groupIndex !== 0"
                type="text"
                size="small"
                @click.stop="removeGroup(groupIndex)"
              >删除分组</el-button>
            </template>
            <el-menu-item :index="tool.value" v-for="tool in (groupIndex === 0 ? group.tools : availableTools)" :key="tool.label">
              <el-checkbox
                v-model="group.checkList"
                :label="tool.value"
                border
                style="width: 160px; margin-top: 10px;"
              >
                {{ tool.label }}
              </el-checkbox>
            </el-menu-item>
          </el-submenu>
        </el-menu>

        <el-button
          type="primary"
          size="small"
          style="margin-top: 30px; margin-left: 40px"
          @click="addGroup"
        >
          添加分组
        </el-button>

        <el-button
          id="buttonStyle"
          type="primary"
          size="small"
          style="margin-top: 30px; margin-left: 40px"
          v-if="getInfo == '1'"
          @click="UploadData()"
        >保存并下一步</el-button>
      </el-main>
    </el-tabs>
  </div>
</template>

<script>
import { store } from "@/components/vuex/store.js";
import { ajax as request } from "@/request.js";
export default {
  data() {
    return {
      getInfo: sessionStorage.getItem("getInfo"),
      activeName: "first",
      defaultTools: [
        { value: "location", label: "位置" },
        { value: "point", label: "点" },
        { value: "line", label: "线" },
        { value: "polygon", label: "面" },
        { value: "rectangle", label: "矩形" },
        { value: "circle", label: "圆" },
        { value: "freehand_polygon", label: "手绘面" },
        { value: "freehand_line", label: "手绘线" },
        { value: "path", label: "轨迹" },
        { value: "draft", label: "草图" },
        { value: "transfer_point", label: "引点定位" }
      ],
      drawtoolGroups: [
        {
          name: "default",
          checkList: [],
          tools: [
            { value: "location", label: "位置" },
            { value: "point", label: "点" },
            { value: "line", label: "线" },
            { value: "polygon", label: "面" },
            { value: "rectangle", label: "矩形" },
            { value: "circle", label: "圆" },
            { value: "freehand_polygon", label: "手绘面" },
            { value: "freehand_line", label: "手绘线" },
            { value: "path", label: "轨迹" },
            { value: "draft", label: "草图" },
            { value: "transfer_point", label: "引点定位" }
          ]
        }
      ],
      drawtool: {},
      id: "-1",
      key: "",
      name: "",
    };
  },
  computed: {
    availableTools() {
      const defaultGroupSelectedTools = this.drawtoolGroups[0].checkList;
      return this.defaultTools.filter(tool => !defaultGroupSelectedTools.includes(tool.value));
    }
  },
  methods: {
    init() {
      let that = this;
      let config = sessionStorage["Data"];
      if (config) {
        config = JSON.parse(config);
        console.log('从sessionStorage获取的配置:', config);
        this.drawtool = config.meta.drawtool;
        if (this.drawtool) {
          console.log('绘图工具配置:', this.drawtool);
          const newGroups = [];
          if (this.drawtool.default) {
            newGroups.push({
              name: "default",
              checkList: this.drawtool.default.map(tool => tool.name),
              tools: [...this.defaultTools]
            });
          }
          for (const [groupName, tools] of Object.entries(this.drawtool)) {
            if (groupName !== 'default') {
              newGroups.push({
                name: groupName,
                checkList: tools.map(tool => tool.name),
                tools: [...this.defaultTools]
              });
            }
          }
          console.log('解析后的分组数据:', newGroups);
          this.drawtoolGroups = newGroups;
          this.$nextTick(() => {
            console.log('视图更新后的勾选状态:', this.drawtoolGroups);
          });
        }
      } else if (this.id != "-1") {
        request({
          url: "/xml/requesting",
          method: "post",
          params: {
            id: that.id,
          },
        }).then(function (response) {
          if (response.data.data) {
            console.log('从接口获取的原始数据:', response.data.data);
            config = sessionStorage["Data"];
            if (!config) {
              var jsondata = JSON.parse(response.data.data);
              console.log('解析后的配置:', jsondata);
              that.$store.dispatch("updateData", { config: jsondata });
              sessionStorage["Data"] = JSON.stringify(that.$store.state.config);
            }
            config = sessionStorage["Data"];
            config = JSON.parse(config);
            that.drawtool = config.meta.drawtool;
            if (that.drawtool) {
              console.log('绘图工具配置:', that.drawtool);
              that.drawtoolGroups = [];
              if (that.drawtool.default) {
                that.drawtoolGroups.push({
                  name: "default",
                  checkList: that.drawtool.default.map(tool => tool.name),
                  tools: that.defaultTools
                });
              }
              for (const [groupName, tools] of Object.entries(that.drawtool)) {
                if (groupName !== 'default') {
                  that.drawtoolGroups.push({
                    name: groupName,
                    checkList: tools.map(tool => tool.name),
                    tools: that.defaultTools
                  });
                }
              }
              console.log('解析后的分组数据:', that.drawtoolGroups);
            }
          } else if (response.data.status == "401") {
            that.$alert(response.data.message);
            that.$router.push({ path: "/login" });
          }
        });
      }
    },
    addGroup() {
      this.$prompt('请输入分组名称', '新建分组', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S+/,
        inputErrorMessage: '分组名称不能为空！'
      }).then(({ value }) => {
        this.drawtoolGroups.push({
          name: value,
          checkList: []
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消创建'
        });
      });
    },
    editGroupName(index) {
      const oldName = this.drawtoolGroups[index].name;
      this.$prompt('请输入新分组名称', '编辑分组', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: oldName,
        inputPattern: /\S+/,
        inputErrorMessage: '分组名称不能为空！'
      }).then(({ value }) => {
        // 更新分组名称
        this.drawtoolGroups[index].name = value;
        // 删除旧名称的分组数据
        if (oldName !== 'default' && oldName in this.drawtool) {
          delete this.drawtool[oldName];
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消编辑'
        });
      });
    },
    removeGroup(index) {
      if (index === 0) return;
      this.drawtoolGroups.splice(index, 1);
      // 更新sessionStorage
      this.drawtool = {};
      this.drawtoolGroups.forEach(group => {
        this.drawtool[group.name] = group.checkList.map(name => ({ name }));
      });
      this.$store.dispatch("updateDrawtool", { drawtool: this.drawtool });
      sessionStorage["Data"] = JSON.stringify(this.$store.state.config);
    },
    updateGroupCheckList(groupIndex, val) {
      // 获取default分组的选中工具
      const defaultSelected = this.drawtoolGroups[0].checkList;
      // 如果是非default分组，过滤掉default分组已选的工具
      const filteredVal = groupIndex === 0 ? val : val.filter(
        tool => !defaultSelected.includes(tool)
      );
      this.drawtoolGroups[groupIndex].checkList = filteredVal;
    },
    UploadData() {
      let that = this;
      // 获取default分组的选中工具
      const defaultSelected = this.drawtoolGroups[0].checkList;

      // 处理每个分组，确保不包含default分组已选的工具
      this.drawtoolGroups.forEach(group => {
        if (!this.drawtool[group.name]) {
          this.drawtool[group.name] = [];
        }
        // 过滤掉default分组已选的工具
        const filteredCheckList = group.name === 'default'
          ? group.checkList
          : group.checkList.filter(tool => !defaultSelected.includes(tool));
        this.drawtool[group.name] = filteredCheckList.map(name => ({ name }));
      });

      this.$store.dispatch("updateDrawtool", { drawtool: this.drawtool });
      sessionStorage["Data"] = JSON.stringify(that.$store.state.config);
      this.$notify.success({
        title: "提示",
        message: "保存成功",
      });
      if (this.name && this.key && this.id) {
        this.$router.push({
          path: `/home/${this.name}/${this.key}/${this.id}/position`,
        });
      } else {
        console.error('缺少必要的路由参数');
        this.$notify.error({
          title: '错误',
          message: '无法跳转，缺少必要的参数'
        });
      }
    },
  },
  watch: {
    'drawtoolGroups': {
      handler() {
        this.$forceUpdate();
      },
      deep: true
    },
    '$route': {
      handler(to) {
        this.name = to.params.name;
        this.id = to.params.id;
        if (to.params.key) {
          this.key = to.params.key;
        }
        console.log('路由参数更新:', {
          name: this.name,
          key: this.key,
          id: this.id
        });
      },
      immediate: true
    }
  },
  store,
  created: function () {
    this.init();
  },
};
</script>

<style lang="scss" scoped>

#tablecontainer .el-menu .el-submenu__title:hover {
  background-color: #f0f7ff !important;
}
.el-menu-item:hover {
  background-color: #f0f7ff !important;
}
#buttonStyle {
  background: #9dbbe7;
  border-radius: 4px;
  border-color: #9dbbe7;
}
.el-tabs__active-bar {
  background-color: #304156;
}
.el-tabs__item.is-active {
  color: #304156;
}
.el-checkbox__input.is-checked + .el-checkbox__label {
  color: #304156;
}
.el-checkbox__input.is-checked .el-checkbox__inner,
.el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: #304156;
  border-color: #304156;
}
.el-checkbox.is-bordered.is-checked {
  border-color: #dcdfe6;
}
@media screen and (min-height: 800px) {
  #checkcontainer {
    height: 500px !important;
  }
}
@media screen and (min-height: 700px) and (max-height: 800px) {
  #checkcontainer {
    height: 400px !important;
  }
}
@media screen and (min-height: 600px) and (max-height: 700px) {
  #checkcontainer {
    height: 350px !important;
  }
}
@media screen and (min-height: 500px) and (max-height: 600px) {
  #checkcontainer {
    height: 300px !important;
  }
}
@media screen and (max-height: 500px) {
  #checkcontainer {
    height: 250px !important;
  }
}
</style>
