/**
 * 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 {moveItem, 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[]>([]);
    // 3
    const [importUrgent, setImportUrgent] =  useState<DataType[]>([]);
    // 2
    const [notImportUrgent, setNotImportUrgent] =  useState<DataType[]>([]);
    // 1
    const [importNotUrgent, setImportNotUrgent] =  useState<DataType[]>([]);
    // 0
    const [notImportNotUrgent, setNotImportNotUrgent] =  useState<DataType[]>([]);

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

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

    function selectData() {
        const requestParam: Request<TaskSelectVO> = {
            pageSize: 1000,
            pageNumber: 1,
            data: {state: data.taskState,pid:pid,treeList:true,treeOrList:false,treeFilter:true},
            sortList:[{property:"sort_no",direction:"ASC"}]
        }
        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)
            setImportUrgent(res.data.content.filter(task => task.priority == '3'))
            setNotImportUrgent(res.data.content.filter(task => task.priority == '2'))
            setImportNotUrgent(res.data.content.filter(task => task.priority == '1'))
            setNotImportNotUrgent(res.data.content.filter(task => task.priority == '0'))
        })
    }

    const filterByIndex = (list:DataType[],filterIndex:number)=>{
        return list.filter((item,index)=>index!=filterIndex)
    }

    const addItemByIndex = (list:DataType[],addIndex:number,item:DataType)=>{
        console.log("list.splice(addIndex,0,item)",list,addIndex,item)
        list.splice(addIndex,0,item)
        return list;
    }
    const moveItemByIndex = (list:DataType[],sourceIndex:number,destinationIndex:number)=>{
        const result = Array.from(list);
        const [removed] = result.splice(sourceIndex, 1);
        result.splice(destinationIndex, 0, removed);
        return result;
    }

    // 处理拖拽结束事件
    const onDragEnd = async (result: DropResult) => {
        console.log('拖拽结束',{result})
        const {source, destination} = result;
        // 如果拖拽到无效区域，直接返回
        if (!destination) return;
        // 如果拖拽到同一个表格的同一个位置，直接返回
        if (destination==source) return;

        let sourceList =allTaskList.filter(task => task.priority == source.droppableId)
        let currentId = sourceList[source.index].id;

        let destinationList=allTaskList.filter(task => task.priority == destination.droppableId);
        let preId;
        let nextId;
        if(destination.droppableId==source.droppableId){
            // 从后往前
            if (source.index>destination.index){
                if (destination.index!=0){
                    preId=destinationList[destination.index-1].id
                }
                nextId=destinationList[destination.index].id
            }else {
                preId=destinationList[destination.index].id
                if (destination.index!=destinationList.length-1){
                    nextId=destinationList[destination.index+1].id
                }
            }
            if (source.droppableId=="3"){setImportUrgent(moveItemByIndex(importUrgent,source.index,destination.index))}
            if (source.droppableId=="2"){setNotImportUrgent(moveItemByIndex(notImportUrgent,source.index,destination.index))}
            if (source.droppableId=="1"){setImportNotUrgent(moveItemByIndex(importNotUrgent,source.index,destination.index))}
            if (source.droppableId=="0"){setNotImportNotUrgent(moveItemByIndex(notImportNotUrgent,source.index,destination.index))}
        }else {
            if (destination.index!=0){
                preId=destinationList[destination.index-1].id
            }
            if (destination.index!=destinationList.length){
                nextId=destinationList[destination.index].id
            }
            // 移除
            if (source.droppableId=="3"){setImportUrgent(filterByIndex(importUrgent,source.index))}
            if (source.droppableId=="2"){setNotImportUrgent(filterByIndex(notImportUrgent,source.index))}
            if (source.droppableId=="1"){setImportNotUrgent(filterByIndex(importNotUrgent,source.index))}
            if (source.droppableId=="0"){setNotImportNotUrgent(filterByIndex(notImportNotUrgent,source.index))}
            // 加入
            if (destination.droppableId=="3"){setImportUrgent(addItemByIndex(importUrgent,destination.index,sourceList[source.index]))}
            if (destination.droppableId=="2"){setNotImportUrgent(addItemByIndex(notImportUrgent,destination.index,sourceList[source.index]))}
            if (destination.droppableId=="1"){setImportNotUrgent(addItemByIndex(importNotUrgent,destination.index,sourceList[source.index]))}
            if (destination.droppableId=="0"){setNotImportNotUrgent(addItemByIndex(notImportNotUrgent,destination.index,sourceList[source.index]))}
        }
        try{
            await moveItem({priority:destination.droppableId,currentId,preId,nextId})
            selectData()
        }catch (e){
            console.log(e)
        }

    };

    return (<div style={{display: 'flex', flexWrap: 'wrap', boxSizing: 'border-box', width: '100vw'}}>
            <DragDropContext onDragEnd={onDragEnd}>
                {/* 紧急重要 */}
                <DroppableTable refreshDate={selectData} tableCode='3' taskList={importUrgent}/>
                {/* 不紧急重要 */}
                <DroppableTable refreshDate={selectData} tableCode='2' taskList={notImportUrgent}/>
                {/* 紧急不重要 */}
                <DroppableTable refreshDate={selectData} tableCode="1" taskList={importNotUrgent}/>
                {/* 不紧急不重要 */}
                <DroppableTable refreshDate={selectData} tableCode='0' taskList={notImportNotUrgent}/>
            </DragDropContext></div>
    );
}
