<template>
  <div class="elements">
    <div class="title" style="margin: 8px 0 0 12px">视图结构</div>
    <t-tree
      class="flex-grow"
      ref="tree"
      :data="data.tree"
      v-model:actived="data.actived"
      activable
      :expand-parent="true"
      @active="onActive"
      style="padding: 0 4px 8px 8px"
    >
      <template #label="{ node }: any">
        <div class="flex middle" :class="{ gray: node.data.visible === false }">
          <template v-if="node.getChildren()">
            <t-icon v-if="node.expanded" name="folder-open" />
            <t-icon v-else name="folder" />
          </template>
          <t-icon v-else name="control-platform" />

          <t-input
            v-if="node.data.edited"
            v-model="node.data.label"
            :autofocus="true"
            @blur="onDescription(node)"
            @enter="onDescription(node)"
          />
          <span v-else @dblclick="node.data.edited = true">
            {{ node.label }}
          </span>
        </div>
      </template>
      <template #operations="{ node }: any">
        <div
          class="flex middle operations"
          :class="{
            gray: node.data.visible === false,
            show: node.data.visible === false || node.data.locked,
          }"
          style="width: 36px; height: 16px"
        >
          <t-tooltip
            class="mr-4"
            v-if="!node.data.locked"
            content="可编辑"
            placement="top"
          >
            <svg class="l-icon" aria-hidden="true" @click="lock(node, 1)">
              <use xlink:href="#l-unlock"></use>
            </svg>
          </t-tooltip>
          <t-tooltip
            class="mr-4"
            v-else-if="node.data.locked == 1"
            content="禁止编辑"
            placement="top"
          >
            <svg class="l-icon" aria-hidden="true" @click="lock(node, 2)">
              <use xlink:href="#l-lock"></use>
            </svg>
          </t-tooltip>
          <t-tooltip
            class="mr-4"
            v-else-if="node.data.locked == 2"
            content="禁止编辑和移动"
            placement="top"
          >
            <svg class="l-icon" aria-hidden="true" @click="lock(node, 10)">
              <use xlink:href="#l-wufayidong"></use>
            </svg>
          </t-tooltip>
          <t-tooltip
            class="mr-4"
            v-else-if="node.data.locked == 10"
            content="禁止所有事件"
            placement="top"
          >
            <svg class="l-icon" aria-hidden="true" @click="lock(node, 0)">
              <use xlink:href="#l-jinyong"></use>
            </svg>
          </t-tooltip>

          <t-icon
            v-if="node.data.visible !== false"
            name="browse"
            @click="visible(node, false)"
          />
          <t-icon v-else name="browse-off" @click="visible(node, true)" />
        </div>
      </template>
    </t-tree>
    <div class="groups-panel" style="padding: 8px 0">
      <div class="flex middle between" style="padding: 0 12px">
        <div class="title">分组</div>
        <a @click="addGroup"> +新建分组</a>
      </div>
      <div class="groups">
        <div
          v-for="(item, i) in data.groups"
          class="flex middle between hover"
          :class="{ primary: i == data.activedGroup }"
        >
          <span
            class="flex-grow"
            v-if="i != data.editedGroup"
            @click="activeGroup(i)"
            @dblclick="
              data.activedGroup = data.editedGroup = i;
              data.group = item;
            "
          >
            {{ item }}
          </span>
          <t-input
            v-else
            v-model="data.group"
            :autofocus="true"
            @blur="setGroup"
            @enter="setGroup"
          />
          <t-popconfirm
            content="确认删除该分组吗？"
            @confirm="delGroup"
            @cancel="data.deleteGroup = undefined"
          >
            <t-icon
              name="delete"
              class="ml-8"
              :class="{ block: i == data.deleteGroup }"
              @click="data.deleteGroup = i"
            />
          </t-popconfirm>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onBeforeMount, onBeforeUnmount, reactive, ref } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';

import { LockState, Pen } from '@meta2d/core';
import { getPenTree, setChildrenVisible } from '@/services/common';

const tree = ref<any>(null);
const data = reactive<any>({
  tree: [],
  actived: [],
  groups: [],
});

onBeforeMount(() => {
  meta2d.on('opened', getTree);
  meta2d.on('add', getTree);
  meta2d.on('undo', getTree);
  meta2d.on('redo', getTree);
  meta2d.on('delete', getTree);
  meta2d.on('combine', getTree);

  getTree();

  const d = meta2d.store.data as any;
  if (!d.groups) {
    d.groups = [];
  }
  data.groups = d.groups;
});

const getTree = () => {
  data.tree = getPenTree();
};

const calcElem = (node: Pen) => {
  if (!node) {
    return;
  }

  const elem: any = {
    label: (node as any).description || node.name,
    value: node.id,
    locked: node.locked,
    visible: node.visible,
  };

  if (!node.children) {
    return elem;
  }

  elem.children = [];
  for (const id of node.children) {
    const child = calcElem(meta2d.store.pens[id]);
    child && elem.children.push(child);
  }

  return elem;
};

const onActive = (value: string[]) => {
  if (!value.length) {
    return;
  }

  const pens: Pen[] = [];
  for (const item of meta2d.store.data.pens) {
    for (const v of value) {
      if (item.id === v) {
        pens.push(item);
      }
    }
  }
  meta2d.active(pens, false);
  meta2d.render();
};

const lock = (node: any, v: LockState) => {
  node.data.locked = v;
  meta2d.setValue({
    id: node.value,
    locked: v,
  });
};

const visible = (node: any, v: boolean) => {
  node.data.visible = v;
  setChildrenVisible(node, v);
  const pen = meta2d.findOne(node.value);
  pen && meta2d.setVisible(pen, v);
};

const onDescription = (node: any) => {
  node.data.edited = false;
  node.setData({ label: node.data.label });
  meta2d.setValue({
    id: node.value,
    description: node.data.label,
  });
};

const addGroup = () => {
  const i = data.groups.length + 1;
  data.group = '组' + i;
  data.groups.push(data.group);
  data.activedGroup = data.editedGroup = i;
};

const activeGroup = (i: number) => {
  data.activedGroup = i;
  const group = data.groups[i];
  const pens: Pen[] = [];
  for (const item of meta2d.store.data.pens) {
    if (item.tags?.includes(group)) {
      pens.push(item);
    }
  }
  meta2d.active(pens, false);
  meta2d.render();
};

const setGroup = () => {
  if (data.groups[data.editedGroup] === data.group) {
    data.editedGroup = undefined;
    return;
  }

  if (data.groups.includes(data.group)) {
    MessagePlugin.error('已经存在相同分组！');
    return;
  }

  for (const item of meta2d.store.data.pens) {
    // @ts-ignore
    if (item.group === data.groups[data.editedGroup]) {
      // @ts-ignore
      item.group === data.group;
    }
  }

  data.groups[data.editedGroup] = data.group;
  data.editedGroup = undefined;
};

const delGroup = () => {
  for (const item of meta2d.store.data.pens) {
    // @ts-ignore
    if (item.group === data.groups[data.deleteGroup]) {
      // @ts-ignore
      delete item.group;
    }
  }
  data.groups.splice(data.deleteGroup, 1);
  data.deleteGroup = undefined;
};

onBeforeUnmount(() => {
  meta2d.off('opened', getTree);
  meta2d.off('add', getTree);
  meta2d.off('undo', getTree);
  meta2d.off('redo', getTree);
  meta2d.off('delete', getTree);
  meta2d.off('combine', getTree);
});
</script>
<style lang="postcss" scoped>
.elements {
  display: flex;
  flex-direction: column;
  height: 100%;

  & > * {
    overflow-y: auto;
    width: 100%;
  }

  .groups-panel {
    flex-shrink: 0;
    height: 240px;
    border-top: 1px solid var(--color-border-input);
    padding: 8px 12px;
  }

  .groups {
    height: calc(100% - 24px);
    overflow-y: auto;
    padding: 0 12px 16px 12px;
    & > div {
      height: 30px;
      line-height: 30px;

      svg {
        display: none;
        &.block {
          display: block;
        }
      }

      &:hover {
        svg {
          display: block;
        }
      }
    }
  }
}
</style>
