import React, {useEffect, useRef, useState} from 'react';
import {Avatar, Dropdown, Input, List, MenuProps, message} from 'antd';
import VirtualList from 'rc-virtual-list';
import {Button, Drawer} from 'antd';
import {ListDiary, SelectDiary} from "@/components/type/Diary";
import TextArea from "antd/es/input/TextArea";
import style from "@/components/DiaryOption.module.css"
import dayjs from "dayjs";
import {addTaskLogAPI} from "@/components/service/Diary";
import {ListBodyRef} from "antd/es/transfer/ListBody";
import {ListRef} from "rc-virtual-list/lib/List";

const CONTAINER_HEIGHT = 400;
const PAGE_SIZE = 20;

const DiaryOption = (props: SelectDiary) => {
    // 抽屉 start
    const [open, setOpen] = useState(false);
    const showDrawer = () => {
        setOpen(true);
    };
    const onClose = () => {
        setOpen(false);
    };
    // 抽屉 end

    // 头按钮设置 start
    const [currentIndex, setCurrentIndex] = useState(1);
    // 头按钮设置 end
    // 数据 start
    const [diaryList, setDiaryList] = useState<ListDiary[]>([]);
    const [diaryReduceList, setDiaryReduceList] = useState<ListDiary[]>([])
    const [page, setPage] = useState(1);
    const noMore = {
        id: '0',
        keyId: 'o0',
        createdDate: new Date(),
        description: '没有更多了',
        taskId: props.taskId,
        enableFlag: 'day-separate'
    };
    const [noMoreFlag, setNoMoreFlag] = useState(false)
    const [sendValue, setSendValue] = useState<string>();
    const [sendValueFlag, setSendValueFlag] = useState(false);
    const handleSend = () => {
        if (sendValueFlag) {
            return
        }
        setSendValueFlag(true);
        if (!sendValue?.trim()) {
            message.info("发送信息不能为空");
            return;
        }
        addTaskLogAPI({
            description: sendValue!,
            taskId: props.taskId,
            enableFlag: '1'
        }).then(res => {
            setDiaryList([res.data.data, ...diaryList])
            setSendValue(undefined)
        }).finally(() => {
            setSendValueFlag(false);
        })
    }

    const appendData = (showMessage = true) => {
        const fakeDataUrl = process.env.NEXT_PUBLIC_TODO_REQUEST_URL + `/task/message/diary/select`;
        fetch(fakeDataUrl, {
            method: 'POST', headers: {
                'Content-Type': 'application/json', // 指定 JSON 格式
                'Authorization': `Bearer ${localStorage.getItem('platform-security')}`,
            }, body: JSON.stringify({pageNumber: page, pageSize: 100, data: {taskId: props.taskId}})
        })
            .then((res) => res.json())
            .then((body) => {
                const results = Array.isArray(body.data.content) ? body.data.content : [];
                if (results.length === 0) {
                    diaryList.push(noMore);
                    setNoMoreFlag(true);
                }
                setDiaryList(diaryList.concat(results));
                setPage(page + 1);
                showMessage && message.success(`${results.length} more items loaded!`);
                if (!showMessage) {
                    if (listRef && listRef.current && typeof listRef.current.scrollTo == 'function') {
                        listRef.current.scrollTo({top: 9999999 });
                    }
                }
            });
    };

    useEffect(() => {
        appendData(false);
        // 视口高度
        window.innerHeight
    }, []);

    useEffect(() => {
        console.log("处理日志集合", diaryList)
        const returnResult: ListDiary[] = []
        diaryList.filter(taskLog => {
            if (currentIndex === 0) {
                return true
            } else if (currentIndex === 1 && taskLog.enableFlag === "1") {
                return true
            } else if (currentIndex === 2 && taskLog.enableFlag === "0") {
                return true
            } else return false;
        }).reduce((map, taskLog) => {
            if (!map.has(dayjs(taskLog.createdDate).format("YYYY-MM-DD"))) {
                map.set(dayjs(taskLog.createdDate).format("YYYY-MM-DD"), []);
            }
            map.get(dayjs(taskLog.createdDate).format("YYYY-MM-DD"))?.push(taskLog);
            return map;
        }, new Map()).forEach((value, Key) => {
            returnResult.push(...value)
            returnResult.push({
                description: dayjs(Key).isSame(dayjs(), 'date') ? "今天" : dayjs(Key).format("YYYY-MM-DD"),
                id: dayjs(Key).format("YYYY-MM-DD"),
                enableFlag: "day-separate",
                taskId: props.taskId,
                createdDate: new Date()
            })
        })
        setDiaryReduceList(returnResult.reverse());
    }, [diaryList, currentIndex]);

    const listRef = useRef<ListRef>(null);
    const onScroll = (e: React.UIEvent<HTMLElement, UIEvent>) => {
        // Refer to: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#problems_and_solutions
        if (
            Math.abs(e.currentTarget.scrollHeight - e.currentTarget.scrollTop - CONTAINER_HEIGHT) <= 1 &&
            !noMoreFlag
        ) {
            appendData();
        }
    };

    // 数据 end

    // 点击操作 start
    const [clickTaskDiary, setClickTaskDiary] = useState<ListDiary>()
    const onClickTAskDiary = (item: ListDiary, operate: string) => {
        if (clickTaskDiary == item && operate == 'L') {
            setClickTaskDiary(undefined)
        } else {
            setClickTaskDiary(item)
        }
    }
    const items: MenuProps['items'] = [
        {
            label: '复制',
            key: '1',
            onClick: () => {
            }
        },
        {
            label: '失效',
            key: '2',
        },
        {
            label: '创建计划',
            key: '3',
        },
        {
            label: '删除',
            key: '4',
        },
        {
            label: '取消',
            key: '5',
        },
    ];
    // 点击操作 end

    return (
        <>
            <Button type="primary" onClick={showDrawer}>
                日志心得
            </Button>
            <Drawer
                style={{boxSizing: "border-box"}}
                styles={{
                    body: {padding: "0 24px"}
                }}
                mask={false}
                title={props.taskName}
                closable={{'aria-label': 'Close Button'}}
                onClose={onClose}
                open={open}
                footer={
                    <div style={{
                        display: 'flex',
                        alignItems: 'stretch', // 关键：强制子项等高
                        justifyContent: 'space-between',
                        height: 'auto', // 父容器高度由内容决定
                    }}>
                        <TextArea
                            rows={4}
                            maxLength={255}
                            showCount
                            classNames={{count: 'ant-input-data-count-inner'}}
                            styles={{
                                count: {
                                    // color:"red",
                                    bottom: "0px"
                                }
                            }}
                            style={{
                                resize: 'none',
                                flex: 1, // 占据剩余空间
                            }}
                            value={sendValue}
                            onChange={(val) => setSendValue(val.target.value)}
                            placeholder='输入日记心得，长按日记心得有惊喜'
                            onKeyDown={event => {
                                console.log({event})
                                if (event.ctrlKey && event.key === 'Enter') {
                                    handleSend();
                                    // 阻止换行符插入
                                    event.preventDefault();
                                }
                            }}
                        />
                        <Button
                            type="primary"
                            style={{
                                flexShrink: 0,
                                width: '2rem',
                                whiteSpace: 'normal',
                                wordWrap: 'break-word',
                                margin: 0,
                                padding: "2px",
                                height: 'auto'// 移除 ，依赖父容器的 alignItems: 'stretch'
                            }}
                            loading={sendValueFlag}
                            onClick={handleSend}
                        >
                            {sendValueFlag ? '发送中...' : '发送'}
                        </Button>
                    </div>
                }
            >
                <div className="displayFlexRow"
                     style={{position: "sticky", top: "0", background: "white", zIndex: "100"}}>
                    <Button style={{flexGrow: 1}} onClick={() => setCurrentIndex(0)}
                            type={currentIndex == 0 ? "primary" : "default"}>全部</Button>
                    <Button style={{flexGrow: 1}} onClick={() => setCurrentIndex(1)}
                            type={currentIndex == 1 ? "primary" : "default"}>生效</Button>
                    <Button style={{flexGrow: 1}} onClick={() => setCurrentIndex(2)}
                            type={currentIndex == 2 ? "primary" : "default"}>失效</Button>
                </div>
                <List style={{height: "auto"}}>
                    <VirtualList
                        data={diaryReduceList}
                        // height={CONTAINER_HEIGHT}
                        // itemHeight={47}
                        itemKey="email"
                        onScroll={onScroll}
                        style={{height: "auto"}}
                        ref={listRef}
                    >
                        {item => (
                            item.enableFlag === 'day-separate' ?
                                <div className={style.container} key={item.keyId}>
                                    <div className={style.lineWithText}>
                                        <text className={style.centerText}>{item.description}</text>
                                    </div>
                                </div>
                                : <div className={style.logTaskContent} key={item.id}>
                                    <Dropdown menu={{items}} trigger={['contextMenu']}>
                                        <div
                                            className={`${style.detailLine} ${item.id === clickTaskDiary?.id ? style.detailLineClick : ''}`}
                                            onClick={() => onClickTAskDiary(item, "L")}
                                            onContextMenu={() => onClickTAskDiary(item, "R")}>
                                            <text
                                                style={{
                                                    textDecoration: item.enableFlag === '0' && currentIndex === 0 ? 'line-through' : '',
                                                    whiteSpace: 'pre-line'
                                                }}>
                                                {item.description}
                                            </text>
                                        </div>
                                    </Dropdown>
                                </div>
                        )}
                    </VirtualList>
                </List>
            </Drawer>
        </>
    );
};
export default DiaryOption;