import { useAjax } from "@/Hook/useAjax"
import useNewToken from "@/Hook/useNewToken"
import { Badge, Button, DatePicker, Input, Popconfirm, Select, Space, Table, Tag } from "antd"
import React, { useEffect, useState } from "react"
import { SearchOutlined } from '@ant-design/icons';
import SearchBox from "@/pages/weComTask/components/searchBox"
import { getSendGroupTaskRobotListApi, putMessageUpdateReloadApi } from "@/pages/weComTask/API/businessPlan/create"
import { useUpdateEffect } from "ahooks";


interface Props {
    taskId: number,
}

export function msToHMS(ms) {
    const totalSeconds = Math.floor(ms / 1000);
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;

    return [
        hours.toString().padStart(2, '0'),
        minutes.toString().padStart(2, '0'),
        seconds.toString().padStart(2, '0')
    ].join(':');
}

/**
 * 下发企微号列表
 * @param param0 
 * @returns 
 */
const ShareTabls: React.FC<Props> = ({ taskId }) => {

    /******************************/
    const { token } = useNewToken()
    const [queryForms, setQueryForms] = useState<any>({ pageNum: 1, pageSize: 20, taskId })

    const getMessageSendTaskuserList = useAjax((params) => getSendGroupTaskRobotListApi(params))
    const putMessageUpdateApi = useAjax((id) => putMessageUpdateReloadApi(id))
    /******************************/

    useEffect(() => {
        setQueryForms({ ...queryForms, taskId })
    }, [taskId])

    useUpdateEffect(() => {
        if (queryForms.taskId) {
            getMessageSendTaskuserList.run(queryForms).catch(err => { })
        }
    }, [queryForms])
    const reload = (id) => {
        console.log(id);
        putMessageUpdateApi.run(id).then(res => {
            getMessageSendTaskuserList.refresh()
        })
    }
    return <Space direction="vertical" style={{ width: '100%' }}>
        <SearchBox
            bodyPadding={1}
            buttons={<>
                <Button onClick={() => getMessageSendTaskuserList.refresh()} loading={getMessageSendTaskuserList.loading} icon={<SearchOutlined />}>搜索</Button>
            </>}
        >
            <>
                <Input placeholder="消息ID" style={{ width: 120 }} allowClear onChange={(e) => setQueryForms({ ...queryForms, msgId: e.target.value, pageNum: 1 })} />
                <Select
                    showSearch
                    style={{ minWidth: 100 }}
                    allowClear
                    onChange={(value) => {
                        setQueryForms({ ...queryForms, status: value, pageNum: 1 })
                    }}
                    value={queryForms?.status}
                    placeholder="发送状态"
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                    }
                    options={[{ label: <Badge status="error" text='未发送' />, value: 0 }, { label: <Badge status="success" text='已发送' />, value: 2 }]}
                />
                <DatePicker placeholder="发送开始时间" onChange={(e, date) => { setQueryForms({ ...queryForms, sendTimeStartTime: date, pageNum: 1 }) }} />
                <DatePicker placeholder="发送结束时间" onChange={(e, date) => { setQueryForms({ ...queryForms, sendTimeEndTime: date, pageNum: 1 }) }} />
                <DatePicker.RangePicker placeholder={['预计送达时间(起始)', '预计送达时间(结束)']} onChange={(e, date) => { setQueryForms({ ...queryForms, createStartDate: date[0], createEndDate: date[1], pageNum: 1 }) }} />
            </>
        </SearchBox>
        {/* 表 */}
        <Table
            style={{ marginBottom: 1 }}
            dataSource={getMessageSendTaskuserList?.data?.data?.records}
            loading={getMessageSendTaskuserList?.loading}
            columns={[{
                title: '所属企业',
                dataIndex: 'corpName',
                key: 'corpName',
                align: 'center',
                width: 120,
            },
            {
                title: '企微号',
                dataIndex: 'userName',
                key: 'userName',
                align: 'center',
                width: 120,
                ellipsis: true,
                render: (a: string, b: any) => {
                    return b?.userId
                }
            },
            {
                title: '发送开始时间',
                dataIndex: 'createTime',
                key: 'createTime',
                align: 'center',
                width: 140,
                ellipsis: true,
            },
            {
                title: '发送结束时间',
                dataIndex: 'sendTime',
                key: 'sendTime',
                align: 'center',
                width: 140,
                ellipsis: true,
            },
            {
                title: '任务耗时',
                dataIndex: 'timeClac',
                key: 'timeClac',
                align: 'center',
                width: 100,
                ellipsis: true,
                render: (_: any, b: any) => {
                    let hm, pj
                    if (b?.sendTime && b?.createTime) {
                        hm = new Date(b?.sendTime).getTime() - new Date(b?.createTime).getTime()
                        pj = hm / b?.userCount / 1000
                    }

                    return hm ? <>{msToHMS(hm)}<br />{pj?.toFixed(1)}秒/群</> : "--"
                }
            },
            {
                title: '发送状态',
                dataIndex: 'status',
                key: 'status',
                align: 'center',
                width: 100,
                render: (a: number) => {
                    return <span>{{ '1': <Badge status="error" text='未发送' />, '2': <Badge status="success" text='已发送' /> }[a]}</span>
                }
            },
            {
                title: '发送数',
                dataIndex: 'userCount',
                key: 'userCount',
                align: 'center',
                width: 100,
                render: (a: number, b: any) => {
                    return b?.status == "1" ? 0 : a
                }
            },
            {
                title: '失败用户/群',
                dataIndex: 'errChatNameList',
                key: 'errChatNameList',
                align: 'center',
                width: 200,
                ellipsis: true,
                render: (a: any) => {
                    return a
                }
            },
            {
                title: '失败原因',
                dataIndex: "errorMsg",
                align: 'center',
                width: 200,
                ellipsis: true,
                render: (a: string, b: any) => {
                    return b?.status == "1" ? a : ""
                }
            },
            {
                title: '操作',
                dataIndex: 'action',
                key: 'action',
                align: 'center',
                width: 50,
                render: (a: any, b: any) => {
                    return <Space>
                        {
                            b?.status == "1" ? <Popconfirm title='确定重新发送？' onConfirm={() => {
                                reload(b?.id)
                            }}>
                                <Button type="link" danger style={{ padding: 0 }} >{'重新发送'}</Button>
                            </Popconfirm> : <></>
                        }
                    </Space>
                }
            }]}
            scroll={{ x: 600, y: 350 }}
            rowKey={(s) => {
                return s.id
            }}
            size='small'
            onRow={(row) => {
                return !row.status ? {
                    style: { background: token.colorPrimaryBgHover }
                } : {}
            }}
            pagination={{
                total: getMessageSendTaskuserList?.data?.data?.total,
                showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                showSizeChanger: true,
                showLessItems: true,
                defaultCurrent: 1,
                defaultPageSize: 200,//默认初始的每页条数
                current: getMessageSendTaskuserList?.data?.data?.current || 1,
                pageSize: getMessageSendTaskuserList?.data?.data?.size || 20,
                onChange: (page, pageSize) => {
                    setQueryForms({ ...queryForms, pageNum: page, pageSize })
                }
            }}
        />
    </Space>
}

export default React.memo(ShareTabls)