<template>
  <div>
    <a-collapse v-model:activeKey="activeKey" :collapsible="isPanel ? 'disabled' : null">
      <a-collapse-panel
        v-for="(item, index) in collapses"
        :key="index"
        :showArrow="isPanel ? false : true"
      >
        <template #header>
          <div class="py-3 px-10px" v-if="config?.options.showLabel && isPanel">{{
            item.title
          }}</div>
          <div class="py-3 px-10px" v-else-if="!isPanel">{{ item.title }}</div>
        </template>
        <DraggableItem
          :list="item.list"
          @add="
            (e) => {
              handleMoveAdd(e, item);
            }
          "
          @copy="
            (e) => {
              handleMoveCopy(e, item);
            }
          "
          @delete="
            (e) => {
              handleMoveDelete(e, item);
            }
          "
        />
      </a-collapse-panel>
    </a-collapse>
  </div>
</template>
<script lang="ts" setup>
  import { computed, onMounted, ref, toRaw, watch } from 'vue';
  import DraggableItem from './draggableItem.vue';
  import { buildUUID } from '/@/utils/uuid';
  import { cloneDeep } from 'lodash-es';
  const props = defineProps({ config: Object });
  const activeKey = ref([0]);
  const collapses = ref(props.config?.layout || []);
  const isPanel = computed(() => {
    return props.config?.type == 'panel';
  });
  const emit = defineEmits(['addCollapse']);
  watch(
    () => props.config?.options.collapseType,
    (val) => {
      initKeys(val);
    },
  );

  watch(
    () => collapses.value,
    (val) => {
      emit('addCollapse', val);
    },
    { deep: true },
  );
  onMounted(() => {
    initKeys(props.config?.options.collapseType);
  });
  function initKeys(val) {
    if (isPanel.value) return;
    if (val == 'show') {
      for (let i = 0; i < collapses.value.length; i++) {
        activeKey.value.push(i);
      }
    } else {
      activeKey.value = [];
    }
  }
  const handleMoveAdd = (event: any, item) => {
    const list = JSON.parse(JSON.stringify(item.list));
    const { newIndex } = event;

    const key = buildUUID().replaceAll('-', '');

    list[newIndex] = {
      ...toRaw(list[newIndex]),
      key,
    };

    item.list.splice(newIndex, 1, list[newIndex]);
    //emit('addCollapse', collapses.value);
  };
  function handleMoveCopy(obj, item) {
    const key = buildUUID().replaceAll('-', '');
    let newobj = {
      ...toRaw(cloneDeep(obj)),
      key,
    };
    item.list.push(newobj);
    // emit('addCollapse', collapses.value);
  }
  function handleMoveDelete(idx, item) {
    item.list.splice(idx, 1);
    // emit('addCollapse', collapses.value);
  }
</script>
<style lang="less" scoped>
  :deep(.ant-collapse > .ant-collapse-item > .ant-collapse-header) {
    padding: 0;
    align-items: center;

    .ant-collapse-arrow {
      margin: 10px;
    }
  }
</style>
