<template>
    <div v-for="item in itemEvents" :key="item.type" class="epic-event-item">
        <div class="epic-event-info">
            <div class="epic-event-label" :title="item.describe">
                {{ item.describe }}
            </div>
            <div class="epic-event-btn">
                <EIcon name="icon-tianjia1" @click="handleOpen(item.type)" />
            </div>
        </div>
        <div class="epic-action-editor-main">
            <draggable
                v-model="internalEvents[item.type]"
                item-key="id"
                :component-data="{
                    type: 'transition-group'
                }"
                group="option-list"
                handle=".handle"
                :animation="200"
                @update:modelValue="handleEventsUpdate(item.type, $event)"
            >
                <template #item="{ element: action, index }">
                    <div class="epic-editor-item">
                        <div class="w-36px text-lg">
                            <EIcon class="mr-2 text-lg cursor-move handle" name="icon-tuozhuai" />
                        </div>
                        <div class="flex-1">
                            <div v-if="action.type === 'component'">
                                {{ getLabel(action.componentId) }}
                            </div>
                            <div v-else-if="action.type === 'custom'">自定义函数</div>
                            <div v-else-if="action.type === 'public'">公共函数</div>
                            {{ action.methodName }}
                        </div>
                        <div class="epic-action-box">
                            <div class="epic-edit-btn" @click="handleEdit(index, item.type, action)">
                                <EIcon name="icon-tiaozheng" />
                            </div>
                            <div class="epic-del-btn" @click="handleDelete(index, item.type)">
                                <EIcon name="icon-shanchu1" />
                            </div>
                        </div>
                    </div>
                </template>
            </draggable>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { type PropType, inject, ref, watch } from "vue";
import { findSchemaById } from "@/components/EpicDesigner/utils";
import { PageSchema } from "../../../types/epic-designer";
import EIcon from "../../../components/icon";
import draggable from "vuedraggable";

const props = defineProps({
    itemEvents: {
        type: Array as PropType<any>,
        default: () => []
    },
    allEvents: {
        type: Array as PropType<any>,
        default: () => []
    },
    modelValue: {
        type: Object as PropType<any>,
        default: () => ({}) // 修复默认值类型，与类型声明一致
    },
    events: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
});
const emit = defineEmits(["add", "edit", "update:modelValue"]);

// 核心修复：创建内部响应式数据，避免直接修改props
const internalEvents = ref<Record<string, any[]>>({});

// 监听props变化，同步到内部数据
watch(
    () => props.events,
    newEvents => {
        internalEvents.value = { ...newEvents };
    },
    { immediate: true, deep: true }
);

const pageSchema = inject("pageSchema") as PageSchema;

function handleOpen(type: string) {
    emit("add", type);
}

function getLabel(id: string) {
    const schema = findSchemaById(pageSchema.schemas, id);
    return schema?.label || ""; // 增加空值处理
}

function handleDelete(index: number, type: string) {
    // 基于内部数据操作
    const newEvents = getNewEvents(type);
    newEvents[type] = internalEvents.value[type]?.filter((_item: any, i: number) => index !== i) || [];

    if (!newEvents[type]?.length) {
        delete newEvents[type];
    }

    // 更新内部数据并通知父组件
    internalEvents.value = newEvents;
    emit("update:modelValue", newEvents);
}

function handleEdit(index: number, type: string, action: any) {
    emit("edit", index, type, action);
}

function getNewEvents(type: string) {
    const newEvents: { [type: string]: any } = {};
    props.allEvents.forEach((item: any) => {
        // 增加空值检查
        if (!internalEvents.value[item.type]?.length) {
            return;
        }
        if (item.type === type) {
            return;
        }
        newEvents[item.type] = internalEvents.value[item.type];
    });
    return newEvents;
}

// 处理拖拽导致的事件顺序变化
function handleEventsUpdate(type: string, newValue: any[]) {
    internalEvents.value[type] = newValue;

    // 构建完整的事件对象并通知父组件
    const updatedEvents = { ...internalEvents.value };
    emit("update:modelValue", updatedEvents);
}
</script>
