import React, { useEffect, useState } from "react"
import style from './index.less';
import { Avatar, Badge, Button, DatePicker, Drawer, Input, Modal, Select, Space, Table, Tabs, Tag } from "antd";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCommentDots } from "@fortawesome/free-solid-svg-icons";
import { useAjax } from "@/Hook/useAjax";
import { getProjectGroupsAllListApi } from "../../API/groupManage";
import { ExclamationCircleOutlined, SearchOutlined } from "@ant-design/icons";
import { getMomentCorpUserLogListApi, getMomentJobLogListApi, GetSendMomentLogListProps } from "../../API/logs";
import useNewToken from "@/Hook/useNewToken";
import SearchBox from "../../components/searchBox";
import dayJs from "dayjs";
import { copy } from "@/utils/utils";

interface Props {
    taskTotal: number
    todayAddTask: number
    todayFinishTaskRate: number
    todayFailTask: number
}

/**
 * 朋友圈
 * @returns 
 */
const MomentItem: React.FC<Props> = ({ taskTotal, todayAddTask, todayFinishTaskRate, todayFailTask }) => {

    /*************************************************/
    const [visible, setVisible] = useState<boolean>(false)
    const [activeKey, setActiveKey] = useState<string>('2')
    const [groupList, setGroupList] = useState<{ label: string, value: number }[]>([]);

    const getProjectGroupsAllList = useAjax(() => getProjectGroupsAllListApi())
    /*************************************************/

    useEffect(() => {
        if (visible) {
            getProjectGroupsAllList.run().then(res => {
                setGroupList([{ label: '空项目组', value: 0 }, ...res?.data?.map(item => ({ label: item.name, value: item.id })) || []])
            })
        }
    }, [visible])

    return <>
        <div className={style.moduleCard} onClick={() => setVisible(true)}>
            <div className={style.moduleCard_header}>
                <Avatar style={{ backgroundColor: '#dcfce7', color: '#16a34a' }} size={30}>
                    <FontAwesomeIcon icon={faCommentDots} />
                </Avatar>
                朋友圈
            </div>
            <div className={style.moduleCard_center}>
                总任务数：{taskTotal || 0} | 今日新增：{todayAddTask || 0}
            </div>
            <div className={style.moduleCard_footer}>
                <span>今日完成率：{((todayFinishTaskRate || 0) * 100).toFixed(2)} %</span>
                <span className={style.error}>今日异常：{todayFailTask}</span>
            </div>
        </div>

        <Drawer
            title={'朋友圈'}
            onClose={() => setVisible(false)}
            open={visible}
            width={'70%'}
        >
            <Tabs
                destroyOnHidden={false}
                onChange={(key) => {
                    setActiveKey(key)
                }}
                activeKey={activeKey}
                type="card"
                items={[
                    {
                        key: '2',
                        label: '下发企微号',
                        children: <>
                            {activeKey == '2' && <GroupXfCorpTabls groupList={groupList} />}
                        </>
                    },
                    {
                        key: '4',
                        label: '群发记录',
                        children: <>
                            {activeKey == '4' && <GroupTaskNotes groupList={groupList} />}
                        </>
                    }
                ]}
            />

        </Drawer>
    </>
}


/**
 * 下发企微号
 * @param param0 
 * @returns 
 */
const GroupXfCorpTabls: React.FC<{ groupList: { label: string, value: number }[] }> = ({ groupList }) => {

    /***********************************/
    const [queryParams, setQueryParams] = useState<GetSendMomentLogListProps>({ pageNum: 1, pageSize: 20 })
    const [oldQueryParams, setOldQueryParams] = useState<GetSendMomentLogListProps>({ pageNum: 1, pageSize: 20 })
    const { token } = useNewToken()
    const [modal, contextHolder] = Modal.useModal();

    const getMomentCorpUserLogList = useAjax((params) => getMomentCorpUserLogListApi(params))
    /***********************************/

    useEffect(() => {
        getMomentCorpUserLogList.run(queryParams)
    }, [queryParams])

    return <div>
        {contextHolder}
        <SearchBox
            bodyPadding={`0 0 10px`}
            buttons={<>
                <Button type="primary" onClick={() => {
                    setQueryParams({ ...oldQueryParams, pageNum: 1, pageSize: queryParams.pageSize })
                }} loading={getMomentCorpUserLogList.loading} icon={<SearchOutlined />}>搜索</Button>
            </>}
        >
            <>
                <Input
                    placeholder="任务名称"
                    style={{ width: 120 }}
                    allowClear
                    onChange={(e) => setOldQueryParams({ ...oldQueryParams, projectName: e.target.value })}
                    value={oldQueryParams?.projectName}
                />
                <Input
                    placeholder="子任务ID"
                    style={{ width: 120 }}
                    allowClear
                    onChange={(e) => setOldQueryParams({ ...oldQueryParams, taskId: e.target.value })}
                    value={oldQueryParams?.taskId}
                />
                <Select
                    placeholder='请选择项目组'
                    allowClear
                    options={groupList}
                    showSearch
                    maxTagCount={1}
                    style={{ minWidth: 150 }}
                    filterOption={(input, option) =>
                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                    mode="multiple"
                    value={oldQueryParams?.projectGroupIds}
                    onChange={(value) => setOldQueryParams({ ...oldQueryParams, projectGroupIds: value })}
                />
                <DatePicker
                    placeholder="发送开始时间"
                    onChange={(e, date) => { setOldQueryParams({ ...oldQueryParams, startDay: date as string }) }}
                    allowClear
                    value={oldQueryParams?.startDay ? dayJs(oldQueryParams?.startDay) : undefined}
                />
                <DatePicker
                    placeholder="发送结束时间"
                    onChange={(e, date) => { setOldQueryParams({ ...oldQueryParams, endDay: date as string }) }}
                    allowClear
                    value={oldQueryParams?.endDay ? dayJs(oldQueryParams?.endDay) : undefined}
                />
            </>
        </SearchBox>

        {/* 表 */}
        <Table
            style={{ marginTop: 10 }}
            dataSource={getMomentCorpUserLogList?.data?.data?.records}
            loading={getMomentCorpUserLogList?.loading}
            bordered
            columns={[
                {
                    title: '操作',
                    dataIndex: 'cz',
                    key: 'cz',
                    width: 100,
                    align: 'center',
                    render: (_, record: any) => {
                        return <Space>
                            <a onClick={() => {
                                modal.confirm({
                                    title: '确认',
                                    icon: <ExclamationCircleOutlined />,
                                    content: '是否跳转到日志详情？',
                                    okText: '确认',
                                    cancelText: '复制',
                                    onCancel: () => {
                                        copy(record.projectName + '任务Id：' + record.taskId)
                                    },
                                    onOk: () => {
                                        localStorage.setItem('OPENTASK', JSON.stringify({
                                            id: record.projectId,
                                            projectName: record.projectName,
                                            taskType: 'TASK_STAT_MOMENT',
                                            taskId: record.taskId,
                                            msg: '跳转日志详情'
                                        }))
                                        window.open(`/weComTask#/weComTask/moments/taskList`)
                                    },
                                });
                            }}>任务跳转</a>
                        </Space>
                    }
                },
                {
                    title: '任务名称',
                    dataIndex: 'projectName',
                    key: 'projectName',
                    width: 180,
                    ellipsis: true,
                    render: (text) => <a onClick={() => copy(text)}>{text}</a>
                },
                {
                    title: '子任务ID',
                    dataIndex: 'taskId',
                    key: 'taskId',
                    width: 70,
                    align: 'center'
                },
                {
                    title: '项目组名称',
                    dataIndex: 'projectGroupName',
                    key: 'projectGroupName',
                    width: 100,
                    ellipsis: true,
                    align: 'center',
                    render: (text) => text ? <a onClick={() => copy(text)}>{text}</a> : '--'
                },
                {
                    title: '项目组ID',
                    dataIndex: 'projectGroupId',
                    key: 'projectGroupId',
                    width: 70,
                    align: 'center'
                },
                {
                    title: '所属企业',
                    dataIndex: 'corpName',
                    key: 'corpName',
                    align: 'center',
                    width: 120,
                    ellipsis: true
                },
                {
                    title: '企微号',
                    dataIndex: 'corpUserName',
                    key: 'corpUserName',
                    align: 'center',
                    width: 120,
                    ellipsis: true,
                    render: (a: string, b: any) => {
                        return a + `(${b?.corpUserId})`
                    }
                },
                {
                    title: '发送状态',
                    dataIndex: 'sendStatus',
                    key: 'sendStatus',
                    align: 'center',
                    width: 80,
                    render: (a) => {
                        return <Badge text={a === 1 ? '已确认发送' : '未确认发送'} status={a === 1 ? 'success' : 'error'} />
                    }
                },
                {
                    title: '预计送达数',
                    dataIndex: 'sendCount',
                    key: 'sendCount',
                    align: 'center',
                    width: 75,
                    ellipsis: true,
                    render: (a) => {
                        return a > 0 ? a : 0
                    }
                },
                {
                    title: '消息ID',
                    dataIndex: 'jobId',
                    key: 'jobId',
                    align: 'center',
                    width: 65,
                    ellipsis: true,
                },
                {
                    title: '发送成功',
                    dataIndex: 'sendSuccessCount',
                    key: 'sendSuccessCount',
                    align: 'center',
                    width: 75,
                    render: (a) => {
                        return a > 0 ? a : 0
                    }
                },
                {
                    title: '发送失败',
                    dataIndex: 'sendFailedCount',
                    key: 'sendFailedCount',
                    align: 'center',
                    width: 75,
                    render: (a) => {
                        return a > 0 ? a : 0
                    }
                },
                {
                    title: '评论数',
                    dataIndex: 'commentCount',
                    key: 'commentCount',
                    align: 'center',
                    width: 65,
                    ellipsis: true,
                },
                {
                    title: '点赞数',
                    dataIndex: 'likeCount',
                    key: 'likeCount',
                    align: 'center',
                    width: 65,
                    ellipsis: true,
                },
                {
                    title: '发送时间',
                    dataIndex: 'sendTime',
                    key: 'sendTime',
                    align: 'center',
                    width: 135,
                    ellipsis: true
                }
            ]}
            scroll={{ x: 1000 }}
            rowKey={'id'}
            size='small'
            onRow={(row: any) => {
                return !row?.status ? {
                    style: { background: token.colorPrimaryBgHover }
                } : {}
            }}
            pagination={{
                total: getMomentCorpUserLogList?.data?.data?.total,
                showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                showSizeChanger: true,
                showLessItems: true,
                defaultCurrent: 1,
                defaultPageSize: 200,//默认初始的每页条数
                current: getMomentCorpUserLogList?.data?.data?.current || 1,
                pageSize: getMomentCorpUserLogList?.data?.data?.size || 20,
                onChange: (page, pageSize) => {
                    setQueryParams({ ...queryParams, pageNum: page, pageSize })
                    setOldQueryParams({ ...oldQueryParams, pageNum: page, pageSize })
                }
            }}
        />
    </div>
}


/**
 * 群发记录
 * @param param0 
 * @returns 
 */
const GroupTaskNotes: React.FC<{ groupList: { label: string, value: number }[] }> = ({ groupList }) => {

    /***********************************/
    const [queryParams, setQueryParams] = useState<GetSendMomentLogListProps>({ pageNum: 1, pageSize: 20 })
    const [oldQueryParams, setOldQueryParams] = useState<GetSendMomentLogListProps>({ pageNum: 1, pageSize: 20 })
    const { token } = useNewToken()
    const [modal, contextHolder] = Modal.useModal();

    const getMomentJobLogList = useAjax((params) => getMomentJobLogListApi(params))
    /***********************************/

    useEffect(() => {
        getMomentJobLogList.run(queryParams)
    }, [queryParams])


    return <div>
        {contextHolder}
        <SearchBox
            bodyPadding={`0 0 10px`}
            buttons={<>
                <Button type="primary" onClick={() => {
                    setQueryParams({ ...oldQueryParams, pageNum: 1, pageSize: queryParams.pageSize })
                }} loading={getMomentJobLogList.loading} icon={<SearchOutlined />}>搜索</Button>
            </>}
        >
            <>
                <Input
                    placeholder="任务名称"
                    style={{ width: 120 }}
                    allowClear
                    onChange={(e) => setOldQueryParams({ ...oldQueryParams, projectName: e.target.value })}
                    value={oldQueryParams?.projectName}
                />
                <Input
                    placeholder="子任务ID"
                    style={{ width: 120 }}
                    allowClear
                    onChange={(e) => setOldQueryParams({ ...oldQueryParams, taskId: e.target.value })}
                    value={oldQueryParams?.taskId}
                />
                <Select
                    placeholder='请选择项目组'
                    allowClear
                    options={groupList}
                    showSearch
                    maxTagCount={1}
                    style={{ minWidth: 150 }}
                    filterOption={(input, option) =>
                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                    mode="multiple"
                    value={oldQueryParams?.projectGroupIds}
                    onChange={(value) => setOldQueryParams({ ...oldQueryParams, projectGroupIds: value })}
                />
                <DatePicker
                    placeholder="发送开始时间"
                    onChange={(e, date) => { setOldQueryParams({ ...oldQueryParams, startDay: date as string }) }}
                    allowClear
                    value={oldQueryParams?.startDay ? dayJs(oldQueryParams?.startDay) : undefined}
                />
                <DatePicker
                    placeholder="发送结束时间"
                    onChange={(e, date) => { setOldQueryParams({ ...oldQueryParams, endDay: date as string }) }}
                    allowClear
                    value={oldQueryParams?.endDay ? dayJs(oldQueryParams?.endDay) : undefined}
                />
            </>
        </SearchBox>

        <Table
            style={{ marginTop: 10 }}
            dataSource={getMomentJobLogList?.data?.data?.records}
            loading={getMomentJobLogList?.loading}
            bordered
            columns={[
                {
                    title: '操作',
                    dataIndex: 'cz',
                    key: 'cz',
                    width: 100,
                    align: 'center',
                    render: (_, record: any) => {
                        return <Space>
                            <a onClick={() => {
                                modal.confirm({
                                    title: '确认',
                                    icon: <ExclamationCircleOutlined />,
                                    content: '是否跳转到日志详情？',
                                    okText: '确认',
                                    cancelText: '复制',
                                    onCancel: () => {
                                        copy(record.projectName + '任务Id：' + record.taskId)
                                    },
                                    onOk: () => {
                                        localStorage.setItem('OPENTASK', JSON.stringify({
                                            id: record.projectId,
                                            projectName: record.projectName,
                                            taskType: 'TASK_STAT_MOMENT',
                                            taskId: record.taskId,
                                            msg: '跳转日志详情'
                                        }))
                                        window.open(`/weComTask#/weComTask/moments/taskList`)
                                    },
                                });
                            }}>任务跳转</a>
                        </Space>
                    }
                },
                {
                    title: '任务名称',
                    dataIndex: 'projectName',
                    key: 'projectName',
                    width: 180,
                    ellipsis: true,
                    render: (text) => <a onClick={() => copy(text)}>{text}</a>
                },
                {
                    title: '子任务ID',
                    dataIndex: 'taskId',
                    key: 'taskId',
                    width: 70,
                    align: 'center'
                },
                {
                    title: '项目组名称',
                    dataIndex: 'projectGroupName',
                    key: 'projectGroupName',
                    width: 100,
                    ellipsis: true,
                    align: 'center',
                    render: (text) => text ? <a onClick={() => copy(text)}>{text}</a> : '--'
                },
                {
                    title: '项目组ID',
                    dataIndex: 'projectGroupId',
                    key: 'projectGroupId',
                    width: 70,
                    align: 'center'
                },
                {
                    title: '消息ID',
                    dataIndex: 'jobId',
                    key: 'jobId',
                    width: 70,
                    ellipsis: true
                },
                {
                    title: '发送时间',
                    dataIndex: 'createTime',
                    key: 'createTime',
                    width: 110
                },
                {
                    title: '任务日志',
                    dataIndex: 'jobLog',
                    key: 'jobLog',
                    width: 250,
                    ellipsis: true
                },
                {
                    title: '任务状态',
                    dataIndex: 'jobStatus',
                    key: 'jobStatus',
                    width: 110,
                    ellipsis: true
                }
            ]}
            scroll={{ x: 1000 }}
            rowKey={(s) => {
                return s.id
            }}
            size='small'
            pagination={{
                total: getMomentJobLogList?.data?.data?.total,
                showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                showSizeChanger: true,
                showLessItems: true,
                defaultCurrent: 1,
                defaultPageSize: 200,//默认初始的每页条数
                current: getMomentJobLogList?.data?.data?.current || 1,
                pageSize: getMomentJobLogList?.data?.data?.size || 20,
                onChange: (page, pageSize) => {
                    setQueryParams({ ...queryParams, pageNum: page, pageSize })
                    setOldQueryParams({ ...oldQueryParams, pageNum: page, pageSize })
                }
            }}
        />
    </div>
}

export default React.memo(MomentItem)