/**
 * A layout is UI that is shared between multiple routes. On navigation, layouts preserve state, remain interactive, and do not re-render.
 */
'use client'
import React, {useContext, useEffect, useState} from 'react';
import {DragDropContext, DropResult} from 'react-beautiful-dnd';
import {DroppableTable} from "@/ui/task/drag/DroppableTable";
import {DataType, Request} from "@/lib/definitions";
import {TaskSelectVO} from "@/lib/task/drag/data";
import {selectTaskAPI} from "@/lib/task/drag/service";
import LocalContext from "@/ui/LocalContent";
import {useSearchParams} from "next/dist/client/components/navigation";

export default function Layout({children}: { children: React.ReactNode }) {
    const [allTaskList, setAllTaskList] = useState<DataType[]>([]);

    const data = useContext(LocalContext);
    console.log('data',data);
    let pid = useSearchParams().get('pid');

    useEffect(() => {
        addData()
    }, [data])

    function addData() {
        const requestParam: Request<TaskSelectVO> = {
            pageSize: 1000,
            pageNumber: 1,
            data: {state: data.taskState,pid:pid}
        }
        if (data.expectedStartTime.length>0){
            const parse = JSON.parse(data.expectedStartTime);
            requestParam.data.expectedStartTimeStart=parse[0].value;
            requestParam.data.expectedStartTimeEnd=parse[1].value;
        }
        selectTaskAPI(requestParam).then(res=>{
            setAllTaskList(res.data.content)
        })
    }

    // 处理拖拽结束事件
    const onDragEnd = (result: DropResult) => {
        console.log('拖拽结束')
        const {source, destination} = result;
        console.log('Source Droppable ID:', source.droppableId);
        console.log('Destination Droppable ID:', destination?.droppableId);
        if (!destination || !['table1', 'table2'].includes(destination.droppableId)) return;
        // 如果拖拽到无效区域，直接返回
        if (!destination) return;
        // 如果拖拽到同一个表格的同一个位置，直接返回
        if (source.droppableId === destination.droppableId && source.index === destination.index) {
            return;
        }
    };

    return (<div style={{display: 'flex', flexWrap: 'wrap', boxSizing: 'border-box', width: '100vw'}}>
            <DragDropContext onDragEnd={onDragEnd}>
                {/* 紧急重要 */}
                <DroppableTable tableCode='3' taskList={allTaskList.filter(task => task.priority == '3')}/>
                {/* 不紧急重要 */}
                <DroppableTable tableCode='2' taskList={allTaskList.filter(task => task.priority == '2')}/>
                {/* 紧急不重要 */}
                <DroppableTable tableCode="1" taskList={allTaskList.filter(task => task.priority == '1')}/>
                {/* 不紧急不重要 */}
                <DroppableTable tableCode='0' taskList={allTaskList.filter(task => task.priority == '0')}/>
            </DragDropContext></div>
    );
}
