import { useAjax } from "@/Hook/useAjax"
import { getTaskV3LogListApi } from "@/services/adqV3"
import { Button, Drawer, Space, Table, Tag, message } from "antd"
import React, { useEffect, useState } from "react"
import { columnsLog } from "./tableConfig"
import DynamicLog from "./dynamicLog"
import { syncAdInfoApi } from "@/services/adqV3/global"

interface Props {
    data: any
    visible?: boolean,
    onClose?: () => void
}
/**
 * 创建日志
 * @returns 
 */
const Log: React.FC<Props> = (props) => {

    /*****************************/
    const { data, visible, onClose } = props
    const { id, taskName } = data
    const [queryForm, setQueryForm] = useState<PULLIN.GetTaskV3LogProps>({ pageNum: 1, pageSize: 20 })

    const getTaskV3LogList = useAjax((params) => getTaskV3LogListApi(params), { formatResult: true })
    const syncAdInfo = useAjax((params) => syncAdInfoApi(params))
    /*****************************/

    useEffect(() => {
        getList()
    }, [queryForm, id])

    /** 获取列表 */
    const getList = () => {
        if (id) {
            getTaskV3LogList.run({ ...queryForm, taskId: id })
        }
    }

    // 同步
    const sync = (value: any) => {
        const hide = message.loading(`正在同步...`, 0, () => {
            message.success('同步成功，结果可能几分钟之后返回');
        });
        syncAdInfo.run({ accountAdgroupMaps: [value.accountId + ',' + value.adgroupId], adgroupCreateLogId: value.id }).then(res => {
            if(res) {
                getTaskV3LogList.refresh()
                message.success('同步成功，结果可能几分钟之后返回')
                hide()
            }
        })
    }

    return <Drawer
        bodyStyle={{ padding: 0 }}
        title={<Space>
            <span>{taskName + ' 日志'}</span>
            <Button type="link" onClick={() => getTaskV3LogList.refresh()}>刷新</Button>
        </Space>}
        width={1400}
        placement="right"
        onClose={() => { onClose && onClose() }}
        open={visible}
    >
        <Table
            columns={columnsLog(sync)}
            dataSource={getTaskV3LogList?.data?.data?.records}
            size="small"
            loading={getTaskV3LogList?.loading}
            scroll={{ y: 600 }}
            bordered
            rowKey={'id'}
            pagination={{
                pageSize: queryForm.pageSize,
                current: queryForm.pageNum,
                total: getTaskV3LogList?.data?.data?.total || 0,
                showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>
            }}
            onChange={(pagination) => {
                let { current, pageSize } = pagination
                let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                newQueryForm.pageNum = current
                newQueryForm.pageSize = pageSize
                setQueryForm(newQueryForm)
            }}
            expandable={{
                expandedRowRender: record => <DynamicLog record={record} />
            }}
        />
    </Drawer>
}


export default React.memo(Log)