<template>
  <div class="layer">
    <div class="layer-header">
      <span>组件图层</span>
      <Button type="text" shape="circle" size="small">
        <CloseOutlined />
      </Button>
    </div>
    <div class="line"></div>
    <InputSearch
      allowClear
      size="small"
      placeholder="请输入图层名称"
      @search="handleFilterLayer"
    />

    <div class="layer-list">
      <VueDraggable
        v-if="layerList.length"
        :list="layerList"
        ghost-class="item-ghost"
        chosen-class="item-chosen"
        animation="300"
        itemKey="id"
        @end="dragEnd"
      >
        <template #item="{ element }">
          <LayerItem :data="element" />
        </template>
      </VueDraggable>

      <Empty
        v-else
        description="暂无图层"
        :image="Empty.PRESENTED_IMAGE_SIMPLE"
        :style="{ marginTop: '100px' }"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import type { CustomElement } from "#/project";
import { ref, watch } from "vue";
import { Button, InputSearch, Empty } from "ant-design-vue";
import { CloseOutlined } from "@ant-design/icons-vue";
import VueDraggable from "vuedraggable";
import LayerItem from "./LayerItem.vue";
import { useProjectStore } from "@/store/modules/project";

const projectStore = useProjectStore();
const filter = ref<string>("");
const layerList = ref<CustomElement[]>([]);

watch(
  () => [
    projectStore.elements,
    filter.value,
  ],
  () => {
    const list = projectStore.elements.filter((item) =>
      item.name.includes(filter.value)
    );
    layerList.value = list.sort((a, b) => b.zIndex - a.zIndex);
  },
  {
    immediate: true,
    deep: true
  }
);

const handleFilterLayer = (value: string) => {
  filter.value = value;
};

const dragEnd = (event: CustomEvent & {newIndex: number}) => {
  const length = layerList.value.length;
  layerList.value.forEach((item, index) => {
    projectStore.updateElement(item.key, "zIndex", length - index);
  });
  projectStore.setSelectedElementKeys([layerList.value[event.newIndex].key]);
};
</script>

<style lang="less" scoped>
.layer {
  position: absolute;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 8px;
  &-header {
    height: 24px;
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    line-height: 24px;
    color: #666;
    margin-bottom: 8px;
  }

  &-list {
    flex: 1;
    overflow-y: auto;
    margin-top: 8px;

    .item-ghost {
      border-bottom: dashed 1px #ccc;
    }
  }

  .line {
    width: calc(100% + 16px);
    border-top: solid 1px #eee;
    margin-bottom: 8px;
    margin-left: -8px;
  }
}
</style>
