<script setup lang="ts">
import type { Component } from 'vue'
import { Delete } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import draggable from 'vuedraggable'
import ReportDesignContent from './ReportDesignContent.vue'
import ReportDesignAttachment from './ReportDesignAttachment.vue'
import ReportDesignQuestion from './ReportDesignQuestion.vue'
import ReportDesignPaper from './ReportDesignPaper.vue'

interface Props {
  modelValue: any[]
}
const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update:modelValue', data: any[]): void
}>()

let datalist = $ref<any[]>([])

watchEffect(() => {
  datalist = [...props.modelValue] || []
})

function getComponent(type: number) {
  const map: Record<number, Component> = {
    1: ReportDesignContent,
    2: ReportDesignAttachment,
    3: ReportDesignQuestion,
    4: ReportDesignPaper
  }
  return map[type]
}

// 添加
function handleAdd(type: number) {
  datalist.unshift({ type, id: Date.now(), name: '', score: 10 })
  emit('update:modelValue', datalist)
}
// 删除
function handleRemove(index: number) {
  ElMessageBox.confirm('删除组件将导致报告分值的变化，请确认是否删除组件？', '提示').then(() => {
    datalist.splice(index, 1)
    emit('update:modelValue', datalist)
  })
}
function handleChange(data: any, index: number) {
  datalist[index] = data
  emit('update:modelValue', datalist)
}
function handleDraggableUpdate() {
  emit('update:modelValue', datalist)
}
</script>

<template>
  <div class="report-design">
    <div class="report-design-hd">
      <el-button-group>
        <el-button type="primary" @click="handleAdd(1)">添加内容组件</el-button>
        <el-button type="primary" @click="handleAdd(2)">添加附件组件</el-button>
        <el-button type="primary" @click="handleAdd(3)">添加思考题组件</el-button>
        <el-button type="primary" disabled @click="handleAdd(4)">添加试卷组件</el-button>
      </el-button-group>
      <slot name="header"></slot>
    </div>
    <div class="report-design-bd">
      <draggable v-model="datalist" item-key="id" @update="handleDraggableUpdate">
        <template #item="{ element, index }">
          <div class="report-design-item-card">
            <component
              :is="getComponent(element.type)"
              :index="index"
              :data="element"
              :key="index"
              @change="(data:any) => handleChange(data, index)" />
            <el-button type="danger" :icon="Delete" circle @click="handleRemove(index)" />
          </div>
        </template>
      </draggable>
    </div>
  </div>
</template>

<style lang="scss">
.report-design-hd {
  display: flex;
  align-items: center;
}
.report-design-item-card {
  display: flex;
  align-items: center;
  .report-design-item {
    flex: 1;
    margin-right: 20px;
  }
}
.report-design-item {
  position: relative;
  margin: 20px 0;
  padding: 10px;
  background-color: #e8eff7;
  border: 1px solid #bbb;
  border-radius: 6px;
}
</style>
