<script lang="ts" setup>
import type { PropType } from 'vue';

import type { IVFormComponent } from '../types';

import Draggable from 'vuedraggable';

import { Icon } from '#/components/icon';

const props = defineProps({
  fields: {
    type: Array as PropType<Array<string>>,
    required: true,
  },
  list: {
    type: Array as PropType<IVFormComponent[]>,
    required: true,
  },
  handleListPush: {
    type: Function,
    default: null,
  },
});
const emit = defineEmits(['copy', 'start', 'addAttrs', 'handleListPush']);
const handleClick = (element: any) => {
  emit('handleListPush', element);
};

const handleClone = (element: any) => {
  return props.handleListPush(element);
};

const handleStart = (element: any, data: IVFormComponent[]) => {
  emit('start', data[element.oldIndex]?.component);
};
// const handleAdd = (element: any) => {
//   console.log('handleAdd', element);
// };

const handleDragstart = (index: number) => {
  emit('addAttrs', props.list, index);
};
</script>
<template>
  <div>
    <Draggable
      tag="ul"
      :model-value="list"
      v-bind="{
        group: { name: 'form-draggable', pull: 'clone', put: false },
        sort: false,
        clone: handleClone,
        animation: 180,
        ghostClass: 'ghost',
      }"
      item-key="type"
      class="control-mark"
      @start="handleStart($event, list)"
    >
      <template #item="{ element, index }">
        <li
          v-if="fields.includes(element.component)"
          class="control-mark-item"
          :class="{ 'no-put': element.component === 'divider' }"
          @dragstart="handleDragstart(index)"
          @click="handleClick(element)"
        >
          <a>
            <Icon :icon="element.icon" class="svg" />
            <span>{{ element.label }}</span>
          </a>
        </li>
      </template>
    </Draggable>
  </div>
</template>

<style scoped lang="less">
.control-mark {
  width: 100%;

  &-item {
    float: left;
    width: 44%;
    margin-right: 6%;
    margin-bottom: 8px;
    padding: 8px 0;
    text-align: center;
    font-size: 12px;
    border: 1px solid #e4e4e4;

    & a {
      color: #333;

      & svg {
        width: 14px !important;
        height: 14px !important;
        margin-right: 5px;
      }
    }

    &:hover {
      border: 1px dashed #eef4ff;
      background-color: #eef4ff;
      cursor: v-bind("props.disabled ? 'not-allowed' : 'pointer'");

      & a {
        color: #0960bd;
        cursor: v-bind("props.disabled ? 'not-allowed' : 'pointer'");
      }
    }
  }
}

.clear {
  clear: both;
}
</style>
