import { nextTick } from 'vue';

const useModalDrag = (container: string) => {
    let canMove = true;
    const start = () => {
        nextTick(() => {
            const modalWrap: any = document.querySelector(
                `.${container} .ant-modal`
            );

            if (modalWrap) {
                let isDragging = false;
                const offset = { x: 0, y: 0 };
                const modalHeader: any =
                    modalWrap.querySelector('.ant-modal-header');
                const modalFooter: any =
                    modalWrap.querySelector('.ant-modal-footer');
                if (modalHeader) {
                    modalHeader.style.cursor = 'move';
                    modalFooter.style.cursor = 'move';

                    modalHeader.addEventListener('mousedown', (e) => {
                        isDragging = true;
                        offset.x = e.clientX - modalWrap.offsetLeft;
                        offset.y = e.clientY - modalWrap.offsetTop;
                        document.body.style.userSelect = 'none';
                    });
                    modalFooter.addEventListener('mousedown', (e) => {
                        isDragging = true;
                        offset.x = e.clientX - modalWrap.offsetLeft;
                        offset.y = e.clientY - modalWrap.offsetTop;
                        document.body.style.userSelect = 'none';
                    });

                    document.addEventListener('mousemove', (e) => {
                        if (!isDragging || !canMove) return;
                        const left = e.clientX - offset.x;
                        const top = e.clientY - offset.y;
                        modalWrap.style.left = `${left}px`;
                        modalWrap.style.top = `${top}px`;
                    });

                    document.addEventListener('mouseup', () => {
                        isDragging = false;
                        document.body.style.userSelect = '';
                    });
                }
            }
        });
    };

    const stop = () => {
        canMove = false;
    };

    // 新增：重置模态框位置为居中
    const resetPosition = () => {
        nextTick(() => {
            const modalWrap: any = document.querySelector(
                `.${container} .ant-modal`
            );
            if (modalWrap) {
                const windowWidth = window.innerWidth;
                const windowHeight = window.innerHeight;
                const modalWidth = modalWrap.offsetWidth;
                const modalHeight = modalWrap.offsetHeight;

                const left = (windowWidth - modalWidth) / 2;
                const top = (windowHeight - modalHeight) / 2;

                modalWrap.style.left = `${left}px`;
                modalWrap.style.top = `${top}px`;
            }
        });
    };
    return { start, stop, resetPosition };
};

export default useModalDrag;
