import { Avatar, Card, Col, DatePicker, Flex, Popover, Row, Select, Spin, Statistic } from "antd";
import { ArrowDownOutlined, ArrowUpOutlined, QuestionCircleOutlined } from "@ant-design/icons";
import useNewToken from "@/Hook/useNewToken";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faListAlt, faPlusCircle, faExclamationTriangle, faChartPie, faUsers, faUsersCog, faRobot, faUserFriends } from "@fortawesome/free-solid-svg-icons";
import { useEffect, useRef, useState } from "react";
import dayjs from "dayjs";
import style from "./index.less";
import { useSize } from "ahooks";
import { RangePickerProps } from "antd/es/date-picker";
import { useAjax } from "@/Hook/useAjax";
import { getTotalModelApi, getTotalTaslApi } from "../../API/logs";
import CalendarItem from "./calendarItem";
import PullGroup from "./pullGroup";
import GroupItem from "./groupItem";
import MomentItem from "./momentItem";
import TransferItem from "./transferItem";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";

const weekMap = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
const taskTypeMap = {
    'TASK_STAT_GROUP_SEND': '官方群发',
    'TASK_STAT_GROUP_SEND_CHAT': '官方群群发',
    'TASK_STAT_GROUP_ROBOT': '机器人群发',
    'TASK_STAT_MOMENT': '朋友圈',
    'TASK_STAT_TRANSFER': '继承',
    'TASK_STAT_PULL_GROUP': '群聊创建 - 拉群'
}

const Logs: React.FC<{ weComTaskStore: { data: { bookPlatForm: TASK_CREATE.BookPlatFormProps[] } } }> = ({ weComTaskStore }) => {

    /****************************************/
    const { token } = useNewToken()
    const { bookPlatForm } = toJS(weComTaskStore.data)
    const ref = useRef<HTMLDivElement>(null)
    const size = useSize(ref);

    const [weekQuery, setWeekQuery] = useState<{ startTime: string, endTime: string }>({
        startTime: dayjs().subtract(6, 'day').format('YYYY-MM-DD'),
        endTime: dayjs().format('YYYY-MM-DD')
    })
    const [dates, setDates] = useState<any>([]);
    const [startClickDate, setStartClickDate] = useState<string>()
    const [endClickDate, setEndClickDate] = useState<string>()
    const [rangeStart, setRangeStart] = useState<boolean>(false)
    const [taskType, setTaskType] = useState<string>('TASK_STAT_GROUP_SEND_CHAT')

    const getTotalTasl = useAjax(() => getTotalTaslApi())
    const getTotalModel = useAjax(() => getTotalModelApi())
    /****************************************/

    useEffect(() => {
        getTotalTasl.run()
        getTotalModel.run()
    }, [])

    const disabledDate: RangePickerProps['disabledDate'] = (current) => {
        // console.log(dayjs(current).format('YYYY-MM-DD'))
        // Can not select days before today and today
        if (current > dayjs().endOf("day")) return true;

        if (startClickDate) {
            return current && current >= dayjs(startClickDate).add(7, 'day');
        }
        if (endClickDate) {
            return current && current <= dayjs(endClickDate).subtract(7, 'day');
        }
        return false
    };

    const height = size?.height ? `calc(100vh - ${size?.height}px - 96px)` : 600
    return <div className={style.logsPage}>
        <Row gutter={[10, 10]} style={{ marginInline: 0 }} className={style.container}>
            <Col xs={24} xl={19}>
                <Flex vertical gap={10}>
                    <Spin spinning={getTotalTasl.loading}>
                        <Flex gap={10} ref={ref}>
                            <Card variant="borderless" style={{ width: '100%' }} hoverable styles={{ body: { position: 'relative', padding: '10px 16px' } }}>
                                <Flex vertical>
                                    <Statistic
                                        title={<strong style={{ fontSize: 14 }}>总任务数</strong>}
                                        value={getTotalTasl?.data?.data?.taskTotal}
                                        style={{ flex: 1 }}
                                        valueStyle={{ fontSize: 26, fontWeight: 'bold', lineHeight: 1.2 }}
                                    />
                                    <Flex vertical>
                                        <Statistic
                                            value={Math.abs(getTotalTasl?.data?.data?.compareLastMonthTaskTotal || 0) * 100}
                                            precision={2}
                                            {...(getTotalTasl?.data?.data?.compareLastMonthTaskTotal >= 0 ? {
                                                valueStyle: { color: '#3f8600', fontSize: 14 },
                                                prefix: <ArrowUpOutlined />
                                            } : {
                                                valueStyle: { color: '#cf1322', fontSize: 14 },
                                                prefix: <ArrowDownOutlined />
                                            })}
                                            suffix="%"
                                        />
                                        <span style={{ fontSize: 13, color: token.colorTextDescription }}>较上月变化百分比</span>
                                    </Flex>
                                </Flex>
                                <Avatar style={{ backgroundColor: '#DBEAFE', color: '#2563eb', position: 'absolute', right: 15, top: 15 }} size={38}>
                                    <FontAwesomeIcon icon={faListAlt} />
                                </Avatar>
                            </Card>
                            <Card variant="borderless" style={{ width: '100%' }} hoverable styles={{ body: { position: 'relative', padding: '10px 16px' } }}>
                                <Flex vertical>
                                    <Statistic
                                        title={<strong style={{ fontSize: 14 }}>今日新增任务数</strong>}
                                        value={getTotalTasl?.data?.data?.todayAddTask}
                                        style={{ flex: 1 }}
                                        valueStyle={{ fontSize: 26, fontWeight: 'bold', lineHeight: 1.2 }}
                                    />
                                    <Flex vertical>
                                        <Statistic
                                            value={Math.abs(getTotalTasl?.data?.data?.compareYesterdayAddTask || 0) * 100}
                                            precision={2}
                                            {...(getTotalTasl?.data?.data?.compareYesterdayAddTask >= 0 ? {
                                                valueStyle: { color: '#3f8600', fontSize: 14 },
                                                prefix: <ArrowUpOutlined />
                                            } : {
                                                valueStyle: { color: '#cf1322', fontSize: 14 },
                                                prefix: <ArrowDownOutlined />
                                            })}
                                            suffix="%"
                                        />
                                        <span style={{ fontSize: 13, color: token.colorTextDescription }}>较昨日新增变化百分比</span>
                                    </Flex>
                                </Flex>
                                <Avatar style={{ backgroundColor: '#dcfce7', color: '#16a34a', position: 'absolute', right: 15, top: 15 }} size={38}>
                                    <FontAwesomeIcon icon={faPlusCircle} />
                                </Avatar>
                            </Card>

                            <Card variant="borderless" style={{ width: '100%' }} hoverable styles={{ body: { position: 'relative', padding: '10px 16px' } }}>
                                <Flex vertical>
                                    <Statistic
                                        title={<strong style={{ fontSize: 14 }}>今日异常/失败任务数</strong>}
                                        value={getTotalTasl?.data?.data?.todayFailTask}
                                        style={{ flex: 1 }}
                                        valueStyle={{ fontSize: 26, fontWeight: 'bold', lineHeight: 1.2 }}
                                    />
                                    <Flex vertical>
                                        <Statistic
                                            value={Math.abs(getTotalTasl?.data?.data?.compareYesterdayFailTask || 0) * 100}
                                            precision={2}
                                            {...(getTotalTasl?.data?.data?.compareYesterdayFailTask >= 0 ? {
                                                valueStyle: { color: '#3f8600', fontSize: 14 },
                                                prefix: <ArrowUpOutlined />
                                            } : {
                                                valueStyle: { color: '#cf1322', fontSize: 14 },
                                                prefix: <ArrowDownOutlined />
                                            })}
                                            suffix="%"
                                        />
                                        <span style={{ fontSize: 13, color: token.colorTextDescription }}>较昨日变化百分比</span>
                                    </Flex>
                                </Flex>
                                <Avatar style={{ backgroundColor: '#fee2e2', color: '#dc2626', position: 'absolute', right: 15, top: 15 }} size={38}>
                                    <FontAwesomeIcon icon={faExclamationTriangle} />
                                </Avatar>
                            </Card>

                            <Card variant="borderless" style={{ width: '100%' }} hoverable styles={{ body: { position: 'relative', padding: '10px 16px' } }}>
                                <Flex vertical>
                                    <Statistic
                                        title={<strong style={{ fontSize: 14 }}>今日任务完成率</strong>}
                                        value={(getTotalTasl?.data?.data?.todayFinishTaskRate || 0) * 100}
                                        style={{ flex: 1 }}
                                        suffix="%"
                                        precision={2}
                                        valueStyle={{ fontSize: 26, fontWeight: 'bold', lineHeight: 1.2 }}
                                    />
                                    <Flex vertical>
                                        <Statistic
                                            value={Math.abs(getTotalTasl?.data?.data?.compareYesterdayFinishTaskRate || 0) * 100}
                                            precision={2}
                                            {...(getTotalTasl?.data?.data?.compareYesterdayFinishTaskRate >= 0 ? {
                                                valueStyle: { color: '#3f8600', fontSize: 14 },
                                                prefix: <ArrowUpOutlined />
                                            } : {
                                                valueStyle: { color: '#cf1322', fontSize: 14 },
                                                prefix: <ArrowDownOutlined />
                                            })}
                                            suffix="%"
                                        />
                                        <span style={{ fontSize: 13, color: token.colorTextDescription }}>较昨日变化百分比</span>
                                    </Flex>
                                </Flex>
                                <Avatar style={{ backgroundColor: '#f3e8ff', color: '#9333ea', position: 'absolute', right: 15, top: 15 }} size={38}>
                                    <FontAwesomeIcon icon={faChartPie} />
                                </Avatar>
                            </Card>
                        </Flex>
                    </Spin>
                    <Card style={{ width: '100%', height, minHeight: 380 }} hoverable styles={{ body: { height: '100%' } }}>
                        <Flex justify="space-between" gap={8} align="center" style={{ marginBottom: 8, height: 30 }}>
                            <Flex gap={10}>
                                <Popover
                                    placement="bottomLeft"
                                    content={<div style={token?.Checkbox ? { display: 'flex', flexFlow: 'column', color: "#fff" } : { display: 'flex', flexFlow: 'column' }}>
                                        <strong style={{ fontSize: 15 }}>任务列表的颜色状态说明：</strong>
                                        <span><span style={{ backgroundColor: '#f3f4f6', lineHeight: "20px", display: 'inline-block', color: "initial" }}>等待执行</span>：该任务发送时间未到，或该任务已被暂停、取消、删除；</span>
                                        <span><span style={{ backgroundColor: '#88e1aa', lineHeight: "20px", display: 'inline-block', color: "initial" }}>执行成功</span>：该任务已被正常发送，并且任务结果没有异常情况；</span>
                                        <span><span style={{ backgroundColor: '#e38989', lineHeight: "20px", display: 'inline-block', color: "initial" }}>任务失败</span>：该任务存在未正常发送情况，包含任务中部分企微号未点击发送、由于手机设备不在线导致任务未发送等多种任务未发送的异常；</span>
                                        <span><span style={{ backgroundColor: '#ffd8bf', lineHeight: "20px", display: 'inline-block', color: "initial" }}>任务异常</span>：该任务已被正常发送，但任务结果中存在异常客户（单向好友或当日接受推送额度达到上限）未接收到任务推送；</span>
                                        <span><span style={{ backgroundColor: '#ffadd2', lineHeight: "20px", display: 'inline-block', color: "initial" }}>无记录</span>：该任务在当天不满足条件未创建发送任务异常；</span>
                                    </div>}>
                                    <QuestionCircleOutlined style={{ color: 'red', fontSize: 20 }} />
                                </Popover>
                                <DatePicker.RangePicker
                                    placeholder={['开始日期', '结束日期']}
                                    variant="filled"
                                    onCalendarChange={(e, dateStrings, info) => {
                                        setDates(e)
                                        if (rangeStart) { // 点过一次
                                            setWeekQuery({ ...weekQuery, startTime: dateStrings[0], endTime: dateStrings[1] })
                                        } else {
                                            if (info.range === 'start') {
                                                setStartClickDate(dateStrings[0])
                                            } else {
                                                setEndClickDate(dateStrings[1])
                                            }
                                            setRangeStart(true)
                                        }
                                    }}
                                    onOpenChange={(open) => {
                                        if (!open) {
                                            setDates([])
                                            setRangeStart(false)
                                            setStartClickDate(undefined)
                                            setEndClickDate(undefined)
                                        }
                                    }}
                                    allowClear={false}
                                    disabledDate={disabledDate}
                                    value={dates?.length > 1 ? dates : (weekQuery.startTime && weekQuery.endTime) ? [dayjs(weekQuery.startTime), dayjs(weekQuery.endTime)] : undefined}
                                />
                            </Flex>
                            <Select
                                style={{ width: 130 }}
                                value={taskType}
                                placeholder="请选择任务类型"
                                variant="filled"
                                onChange={(value) => {
                                    setTaskType(value)
                                }}
                                options={Object.keys(taskTypeMap).map(key => ({ label: taskTypeMap[key], value: key }))}
                            />
                        </Flex>
                        <Flex gap={8} style={{ height: 'calc(100% - 38px)' }}>
                            {Array.from({ length: 7 }, (_, i) => {
                                const date = i === 0 ? dayjs(weekQuery.startTime) : dayjs(weekQuery.startTime).add(i, "day");
                                return {
                                    date: date.format("MM/DD"),
                                    weekday: weekMap[date.day()],
                                    nowDate: date.format("YYYY-MM-DD"),
                                    index: i
                                };
                            }).map(item => <CalendarItem
                                key={item.date}
                                weekday={item.weekday}
                                date={item.date}
                                taskDay={item.nowDate}
                                taskType={taskType}
                                index={item.index}
                                endDay={weekQuery.endTime}
                            />)}
                        </Flex>

                    </Card>
                </Flex>
            </Col>
            <Col xs={24} xl={5}>
                <Card style={{ width: '100%', height: `calc(100vh - 86px)` }} hoverable classNames={{ body: 'summaryCardSpin' }} styles={{ body: { height: '100%', paddingInline: 0 } }}>
                    <Spin spinning={getTotalModel.loading}>
                        <Flex justify="space-between" gap={8} align="center" style={{ paddingInline: token.paddingLG, marginBottom: 8, height: 30 }}>
                            <strong style={{ fontSize: 16 }}>任务列表摘要</strong>
                        </Flex>
                        <div className={style.summaryList} style={{ paddingInline: token.paddingLG }}>
                            {getTotalModel?.data?.data?.map((item: any, index: number) => {
                                switch (item.taskType) {
                                    case 'TASK_STAT_GROUP_SEND': // 官方用户群发
                                        return <GroupItem
                                            key={index}
                                            title="官方用户群发"
                                            icon={faUsers}
                                            taskTotal={item?.taskTotal}
                                            todayAddTask={item?.todayAddTask}
                                            todayFinishTaskRate={item?.todayFinishTaskRate}
                                            todayFailTask={item?.todayFailTask}
                                        />
                                    case 'TASK_STAT_GROUP_SEND_CHAT': // 官方群群发
                                        return <GroupItem
                                            key={index}
                                            title="群聊群发"
                                            icon={faUsersCog}
                                            taskTotal={item?.taskTotal}
                                            todayAddTask={item?.todayAddTask}
                                            todayFinishTaskRate={item?.todayFinishTaskRate}
                                            todayFailTask={item?.todayFailTask}
                                            projectType={1}
                                        />
                                    case 'TASK_STAT_GROUP_ROBOT': // 机器人群发
                                        return <GroupItem
                                            key={index}
                                            title="机器人群发"
                                            icon={faRobot}
                                            taskTotal={item?.taskTotal}
                                            todayAddTask={item?.todayAddTask}
                                            todayFinishTaskRate={item?.todayFinishTaskRate}
                                            todayFailTask={item?.todayFailTask}
                                            projectType={2}
                                        />
                                    case 'TASK_STAT_MOMENT': // 朋友圈
                                        return <MomentItem
                                            key={index}
                                            taskTotal={item?.taskTotal}
                                            todayAddTask={item?.todayAddTask}
                                            todayFinishTaskRate={item?.todayFinishTaskRate}
                                            todayFailTask={item?.todayFailTask}
                                        />
                                    case 'TASK_STAT_PULL_GROUP': // 群聊创建 - 拉群
                                        return <PullGroup
                                            key={index}
                                            pullGroupCount={item?.pullGroupCount}
                                            pullSuccessCount={item?.pullSuccessCount}
                                            pullSuccessRate={item?.pullSuccessRate}
                                            pullFailCount={item?.pullFailCount}
                                        />
                                    case 'TASK_STAT_TRANSFER': // 继承
                                        return <TransferItem 
                                            key={index}
                                            taskTotal={item?.taskTotal}
                                            todayAddTask={item?.todayAddTask}
                                            todayFailTask={item?.todayFailTask}
                                            todayFinishTaskRate={item?.todayFinishTaskRate}
                                            bookPlatForm={bookPlatForm}
                                        />
                                    default:
                                        return null;
                                }
                            })}
                        </div>
                    </Spin>
                </Card>
            </Col>
        </Row>
    </div>
}

export default inject('store')(observer((props: any) => Logs(props.store)));