<!-- 编辑弹窗 -->
<template>
    <ele-modal
        form
        :width="width"
        v-model="visible"
        :title="title"
        position="center"
        destroy-on-close
        :body-style="{ maxHeight: '84vh', position: 'relative', ...bodyStyle }"
    >
        <slot name="other"></slot>

        <SimpleForm
            :items="items"
            :labelWidth="labelWidth"
            ref="formRef"
            v-bind="formProps"
            :disabled="type === 'detail'"
        >
            <template
                v-for="(val, key) in $slots"
                #[key]="{ item, model, updateValue }"
            >
                <slot
                    :name="key"
                    :item="item"
                    :model="model"
                    :updateValue="updateValue"
                ></slot>
            </template>
        </SimpleForm>

        <template #footer>
            <el-button @click="handleCancel">关闭</el-button>
            <el-button
                type="primary"
                @click="handleSumbit"
                v-if="type !== 'detail'"
                >确定</el-button
            >
        </template>
    </ele-modal>
</template>

<script setup>
    import { ref, reactive, nextTick, getCurrentInstance, useSlots } from 'vue';
    import { Flag, ChatDotSquare } from '@element-plus/icons-vue';
    import orderTimeline from '@/views/recycleOrder/components/order-timeline.vue';
    import SimpleForm from '@/components/CommonPage/SimpleForm.vue';
    import validators from '@/utils/validators';
    import { EleMessage } from 'ele-admin-plus/es';
    let { proxy } = getCurrentInstance();

    const props = defineProps({
        items: { type: Array, default: () => [] },
        title: { type: String, default: '编辑' },
        type: { type: String },
        bodyStyle: { type: Object, default: () => ({}) },
        width: { type: String, default: '520px' },
        labelWidth: { type: String, default: '90px' },
        formProps: { type: Object, default: () => ({}) },
        baseUrl: { type: Object, default: () => ({}) },
        //是否需要合并打开时传入的参数
        isMerge: { type: Boolean, default: false },
        formatData: {
            type: Function,
            default: (data) => data
        }, //格式化提交数据
        idKey: { type: String, default: 'id' },
        fallbackData: { type: Function, default: (data) => data }, //回填数据
        submitHandler: { type: Function } // 自定义提交函数，如果存在则使用该函数代替默认的http请求
    });
    const emit = defineEmits(['success', 'refresh']);
    /** 弹窗是否打开 */
    const visible = defineModel({ type: Boolean });

    /** 关闭弹窗 */
    const handleCancel = () => {
        visible.value = false;
    };

    const form = ref({});
    const mergeData = ref({});
    /** 弹窗打开事件 */
    const handleOpen = async (data) => {
        visible.value = true;
        nextTick(() => {
            // Reset form data completely
            form.value = {};
            formRef.value?.resetForm();

            // For new items (no ID), initialize with empty data
            if (!data || !data[props.idKey]) {
                mergeData.value = {};
                formRef.value?.setData(data || {});
            } else {
                // For edit mode
                mergeData.value = data;
                if (!props.baseUrl.detail) {
                    form.value = data;
                    formRef.value?.setData(data);
                } else {
                    getDetail(data.id).then((res) => {
                        form.value = res.data;
                        let data = props.fallbackData(res.data);
                        formRef.value?.setData(data);
                    });
                }
            }

            // 重置滚动条位置
            resetScrollPosition();
        });
    };

    // 重置滚动条位置
    const resetScrollPosition = () => {
        nextTick(() => {
            setTimeout(() => {
                const modalBody = document.querySelectorAll('.ele-modal-body');
                if (modalBody) {
                    modalBody[modalBody.length - 1].scrollTop = 0;
                }
            }, 100);
        });
    };

    //获取详情数据
    const getDetail = (id) => {
        if (!props.baseUrl.detail || !id) return;
        let url = `${props.baseUrl.detail}/${id}`;
        return new Promise((resolve, reject) => {
            proxy.$http.get(url).then((res) => {
                if (res.data.code !== 200)
                    return EleMessage.error(res.data.msg);
                resolve(res.data || {});
            });
        });
    };

    const formRef = ref();
    const handleSumbit = () => {
        formRef.value?.submitForm().then((data) => {
            console.log(data, data[props.idKey], '格式化数据data');

            // Only set ID if we're in edit mode (form.value has ID)
            if (form.value && form.value[props.idKey]) {
                data[props.idKey] = form.value[props.idKey];
            }

            let url = data[props.idKey]
                ? props.baseUrl.update
                : props.baseUrl.add;
            data = props.isMerge ? { ...mergeData.value, ...data } : data;
            let format = props.formatData(data);

            if (props.submitHandler) {
                props
                    .submitHandler(format, data[props.idKey] ? 'update' : 'add')
                    .then(() => {
                        visible.value = false;
                        emit('success', data);
                        EleMessage.success('操作成功');
                    })
                    .catch((err) => {
                        EleMessage.error(err.message || '操作失败');
                    });
            } else {
                proxy.$http.post(url, format).then((res) => {
                    if (res.data.code !== 200)
                        return EleMessage.error(res.data.msg);
                    visible.value = false;
                    emit('success', data);
                    EleMessage.success('操作成功');
                    // EleMessage.success(format[props.idKey] ? '操作成功' : '操作成功');
                });
            }
        });
    };

    const setData = (data) => {
        formRef.value?.setData(data);
    };

    defineExpose({
        handleOpen,
        handleSumbit,
        setData,
        resetScrollPosition
    });
</script>
