import { useAjax } from "@/Hook/useAjax"
import useNewToken from "@/Hook/useNewToken"
import { useUpdateEffect } from "ahooks"
import { App, Badge, Button, DatePicker, Input, Select, Space, Table, Tag } from "antd"
import React, { useEffect, useState } from "react"
import { SearchOutlined, SyncOutlined } from '@ant-design/icons';
import { groupMsgCorpUserListConfig } from "./groupTableConfig"
import { cancelGroupSendApi, getSendGroupTaskGroupuserListApi, GetSendTaskGroupuserListProps, remindGroupSendApi, syncSendGroupTaskExternalApi, syncSendGroupTaskUserApi } from "@/pages/weComTask/API/businessPlan/create"


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

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

    const getSendTaskuserList = useAjax((params) => getSendGroupTaskGroupuserListApi(params))
    const syncSendTaskUser = useAjax((params) => syncSendGroupTaskUserApi(params))
    const cancelSend = useAjax((params) => cancelGroupSendApi(params))
    const remindSend = useAjax((params) => remindGroupSendApi(params))
    const syncSendTaskExternal = useAjax((params) => syncSendGroupTaskExternalApi(params))
    /******************************/

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

    useUpdateEffect(() => {
        if (queryForms.taskId) {
            getSendTaskuserList.run(queryForms)
        }
    }, [queryForms])

    const syncHandle = () => {
        if (queryForms.taskId) {
            syncSendTaskUser.run({ taskId: queryForms.taskId }).then(res => {
                if (res) {
                    syncHandleUser()
                }
            })
        } else {
            message.error('企微ID任务ID空')
        }
    }

    // 客户同步
    const syncHandleUser = () => {
        if (queryForms.taskId) {
            syncSendTaskExternal.run({ taskId: queryForms.taskId }).then(res => {
                if (res) {
                    message.success('同步成功')
                    getSendTaskuserList.refresh()
                }
            })
        } else {
            message.error('企微ID任务ID空')
        }
    }

    const changeHandle = (data: any, type: string) => {
        const hide = message.loading('设置中...', 0)
        if (type === 'txSend') {
            remindSend.run({ corpId: data?.corpId, msgId: data?.msgId }).then(res => {
                hide()
                message.success('提醒成功')
                getSendTaskuserList.refresh()
            }).catch(() => hide())
        } else if (type === 'qxSend') {
            cancelSend.run({ corpId: data?.corpId, msgId: data?.msgId }).then(res => {
                hide()
                message.success('取消成功')
                getSendTaskuserList.refresh()
            }).catch(() => hide())
        }
    }

    return <div>
        <Space style={{ width: '100%' }} wrap>
            <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 as string, pageNum: 1}) }} />
            <DatePicker placeholder="发送结束时间" onChange={(e, date) => { setQueryForms({ ...queryForms, sendTimeEndTime: date as string, pageNum: 1 }) }} />
            <DatePicker.RangePicker placeholder={['预计送达时间(起始)', '预计送达时间(结束)']} onChange={(e, date) => { setQueryForms({ ...queryForms, createStartDate: date[0], createEndDate: date[1], pageNum: 1 }) }} />
            <Button onClick={() => getSendTaskuserList.refresh()} loading={getSendTaskuserList.loading} icon={<SearchOutlined />}>搜索</Button>
            <Button onClick={() => syncHandle()} loading={syncSendTaskUser.loading || syncSendTaskExternal.loading} type="primary" icon={<SyncOutlined />}>同步</Button>
        </Space>

        {/* 表 */}
        <Table
            style={{ marginTop: 10 }}
            dataSource={getSendTaskuserList?.data?.data?.records}
            loading={getSendTaskuserList?.loading}
            columns={groupMsgCorpUserListConfig(changeHandle)}
            scroll={{ x: 400, y: 280 }}
            rowKey={(s) => {
                return s.id
            }}
            size='small'
            onRow={(row) => {
                return !row.status ? {
                    style: { background: token.colorPrimaryBgHover }
                } : {}
            }}
            pagination={{
                total: getSendTaskuserList?.data?.data?.total,
                showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                showSizeChanger: true,
                showLessItems: true,
                defaultCurrent: 1,
                defaultPageSize: 200,//默认初始的每页条数
                current: getSendTaskuserList?.data?.data?.current || 1,
                pageSize: getSendTaskuserList?.data?.data?.size || 20,
                onChange: (page, pageSize) => {
                    setQueryForms({ ...queryForms, pageNum: page, pageSize })
                }
            }}
        />
    </div>
}

export default React.memo(GroupXfCorpTabls)