import React, { useEffect, useState } from "react";
import Dayjs from "dayjs";
import { useAjax } from "@/Hook/useAjax";
import { getTaskdayApi, GetTaskdayProps } from "../../API/logs";
import InfiniteScroll from 'react-infinite-scroll-component';
import style from "./index.less";
import { Divider, Empty, Flex, Modal, Skeleton, Spin } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { copy } from "@/utils/utils";

const TaskStatusMap = {
    'TASK_STATUS_SUCCESS': '执行成功',
    'TASK_STATUS_FAIL': '任务失败',
    'TASK_STATUS_ERROR': '任务异常',
    'TASK_STATUS_WAIT': '等待执行',
    'TASK_STATUS_EMPTY_LOG': '无记录'
}

interface CalendarProps {
    weekday: string;
    date: string;
    taskDay: string;
    taskType: string;
    index: number
    endDay: string
}

const CalendarItem: React.FC<CalendarProps> = ({ weekday, date, taskDay, taskType, index, endDay }) => {

    /********************************************/
    const [queryParmas, setQueryParmas] = useState<GetTaskdayProps>({ pageNum: 1, pageSize: 10, taskDay, taskType })
    const [data, setData] = useState<any[]>([])
    const [total, setTotal] = useState<number>(0)
    const [modal, contextHolder] = Modal.useModal();
    const getTaskday = useAjax((params) => getTaskdayApi(params))
    /********************************************/

    useEffect(() => {
        if (Dayjs(taskDay) <= Dayjs(endDay)) {
            getList({ pageNum: 1, pageSize: 15, taskDay, taskType })
        }
    }, [taskDay, taskType])

    const getList = (params: GetTaskdayProps) => {
        setQueryParmas(params)
        getTaskday.run(params).then(res => {
            if (res?.data) {
                setTotal(res?.data?.total || 0)
                if (params.pageNum === 1) {
                    setData(res?.data?.records)
                } else {
                    setData(data.concat(res?.data?.records))
                }
            } else {
                setTotal(0)
                setData([])
            }
        })
    }

    // 下一页
    const loadMoreData = () => {
        getList({ ...queryParmas, pageNum: queryParmas.pageNum + 1 })
    }

    return <div className={style.dataList}>
        <Flex justify="space-between" align="center" className={style.dataList_header}>
            <strong style={{ fontSize: 14 }}>{weekday}</strong>
            <a style={{ fontSize: 12 }}>{total}个任务</a>
            <span>{date}</span>
        </Flex>
        <div className={style.dataList_content} id={'scrollableDiv' + index}>
            {contextHolder}
            {getTaskday?.loading && queryParmas.pageNum === 1 ? <div className={style.summaryCardSpin}>
                <Spin />
            </div> : null}
            {Dayjs(taskDay) <= Dayjs(endDay) ? <InfiniteScroll
                dataLength={data?.length}
                next={loadMoreData}
                hasMore={data?.length < total}
                loader={<div style={{ display: 'flex', marginTop: 10, padding: '0 10px' }}>
                    <Skeleton.Input active style={{ width: '100%' }} />
                </div>}
                endMessage={<Divider plain>没有更多了</Divider>}
                scrollableTarget={'scrollableDiv' + index}
            >
                <div style={{ padding: '0 10px' }}>
                    {data.map(item => <div
                        key={item.taskId}
                        title={`${TaskStatusMap[item?.taskStatus]}： ${item.taskName}`}
                        className={`${style.dataList_content_item} ${style.calendar_task}`}
                        style={{
                            backgroundColor:
                                item?.taskStatus === 'TASK_STATUS_WAIT' ? '#f3f4f6' :
                                    item?.taskStatus === 'TASK_STATUS_SUCCESS' ? '#dcfce7' :
                                        item?.taskStatus === 'TASK_STATUS_FAIL' ? '#fee2e2' :
                                            item?.taskStatus === 'TASK_STATUS_ERROR' ? '#fff2e8' : '#ffd6e7'
                        }}
                        onClick={() => {
                            modal.confirm({
                                title: '确认',
                                icon: <ExclamationCircleOutlined />,
                                content: '是否跳转到日志详情？',
                                okText: '确认',
                                cancelText: '复制',
                                onCancel: () => {
                                    copy(item.projectName + '任务Id：' + item.taskId)
                                },
                                onOk: () => {
                                    localStorage.setItem('OPENTASK', JSON.stringify({
                                        id: item.projectId,
                                        projectName: item.projectName,
                                        taskType,
                                        taskId: item.taskId,
                                        msg: '跳转日志详情'
                                    }))
                                    switch (taskType) {
                                        case 'TASK_STAT_GROUP_SEND_CHAT': // 官方群群发
                                            window.open(`/weComTask#/weComTask/groupChatSend/official/taskList`)
                                            break
                                        case 'TASK_STAT_GROUP_ROBOT': // 机器人群发
                                            window.open(`/weComTask#/weComTask/groupChatSend/robot/taskList`)
                                            break
                                        case 'TASK_STAT_TRANSFER': // 继承
                                        case 'TASK_STAT_GROUP_SEND': // 官方群发
                                            window.open(`/weComTask#/weComTask/businessPlan/taskList`)
                                            break
                                        case 'TASK_STAT_MOMENT': // 朋友圈
                                            window.open(`/weComTask#/weComTask/moments/taskList`)
                                            break
                                        case 'TASK_STAT_PULL_GROUP': // 群聊创建 - 拉群
                                            window.open(`/weComTask#/weComTask/groupChat/taskList`)
                                            break
                                    }
                                },
                            });
                        }}
                    >
                        <div
                            className={style.title}
                            style={{
                                color:
                                    item?.taskStatus === 'TASK_STATUS_WAIT' ? '#6b7280' :
                                        item?.taskStatus === 'TASK_STATUS_SUCCESS' ? '#166534' :
                                            item?.taskStatus === 'TASK_STATUS_FAIL' ? '#991b1b' :
                                                item?.taskStatus === 'TASK_STATUS_ERROR' ? '#ff7a45' : '#eb2f96'
                            }}
                        >{item.taskName}</div>
                        <div className={style.time}>{item.sendTime}</div>
                    </div>)}
                </div>
            </InfiniteScroll> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
        </div>
    </div>
};

export default React.memo(CalendarItem);