import { Button, Card, DatePicker, Input, message, Popconfirm, Table, Tag } from "antd"
import React, { useEffect, useState } from "react"
import '../index.less'
import { SearchOutlined } from "@ant-design/icons"
import { useAjax } from "@/Hook/useAjax"
import { getTaskV3ListApi, stopAdgroupTaskApi } from "@/services/adqV3"
import moment from "moment"
import { useModel } from "umi"
import columns from "./tableConfig"
import Log from "./log"
import ExecuteLog from "./executeLog"

const TaskList: React.FC = () => {

    /****************************************/
    const { initTargeting, geoLocationList, modelList } = useModel('useLaunchV3.useTargeting')

    const [queryParams, setQueryParams] = useState<PULLIN.GetTaskV3Props>({ pageNum: 1, pageSize: 20 })
    const [queryParamsNew, setQueryParamsNew] = useState<PULLIN.GetTaskV3Props>({ pageNum: 1, pageSize: 20 })
    const [logVisible, setLogVisible] = useState<boolean>(false)
    const [executeLogVisible, setExecuteLogVisible] = useState<boolean>(false)
    const [logData, setLogData] = useState<any>({})
    const [selectedRows, setSelectedRows] = useState<any[]>([])

    const getTaskV3List = useAjax((params) => getTaskV3ListApi(params), { formatResult: true })
    const stopAdgroupTask = useAjax((params) => stopAdgroupTaskApi(params))
    /****************************************/

    useEffect(() => {
        initTargeting()
        let taskName = sessionStorage.getItem('CAMPV3')
        if (taskName) {
            setQueryParamsNew({ ...queryParamsNew, taskName })
            setQueryParams({ ...queryParamsNew, taskName })
            sessionStorage.removeItem('CAMPV3')
        }
    }, [])

    useEffect(() => {
        getTaskV3List.run(queryParamsNew)
    }, [queryParamsNew])


    const callback = (data: any, type: 'log' | 'page' | 'copy' | 'zxLog', allData?: any) => {
        switch (type) {
            case 'log':
                setLogData({ ...data })
                setLogVisible(true)
                break
            case 'copy':
                sessionStorage.setItem('TASKID3.0', data.id)
                window.location.href = '/#/launchSystemV3/tencentAdPutIn/create'
                break
            case 'zxLog':
                setLogData({ ...data })
                setExecuteLogVisible(true)
                break
        }
    }

    const handleSuspend = () => {
        stopAdgroupTask.run(selectedRows.map(item => item.id)).then(res => {
            if (res) {
                message.success('终止成功')
                getTaskV3List.refresh()
            }
        })
    }

    return <Card
        className="cardResetCss"
        title={<div className="flexStart" style={{ gap: 8 }}>
            <Input style={{ width: 180 }} placeholder="请输入任务名称" value={queryParams?.taskName} allowClear onChange={(e) => setQueryParams({ ...queryParams, taskName: e.target.value, pageNum: 1 })} />
            <DatePicker.RangePicker style={{ width: 250 }} placeholder={['创建开始时间', '创建结束时间']} value={(queryParams?.createTimeMin && queryParams?.createTimeMax) ? [moment(queryParams?.createTimeMin), moment(queryParams?.createTimeMax)] as any : undefined} onChange={(_, option) => setQueryParams({ ...queryParams, createTimeMin: option[0], createTimeMax: option[1], pageNum: 1 })} />
            <Button type="primary" icon={<SearchOutlined />} loading={getTaskV3List.loading} onClick={() => setQueryParamsNew({ ...queryParams })}>搜索</Button>
            <Popconfirm
                title="确定中止任务?"
                onConfirm={handleSuspend}
                disabled={selectedRows.length === 0}
            >
                <Button type="primary"danger loading={stopAdgroupTask.loading} disabled={selectedRows.length === 0}>终止任务</Button>
            </Popconfirm>
        </div>}
    >
        <Table
            columns={columns(geoLocationList, modelList, callback)}
            dataSource={getTaskV3List?.data?.data?.records}
            size="small"
            loading={getTaskV3List?.loading}
            scroll={{ y: 600 }}
            bordered
            rowKey={'id'}
            pagination={{
                pageSize: queryParamsNew.pageSize,
                current: queryParamsNew.pageNum,
                total: getTaskV3List?.data?.data?.total || 0,
                showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>
            }}
            onChange={(pagination) => {
                let { current, pageSize } = pagination
                let newQueryForm = JSON.parse(JSON.stringify(queryParamsNew))
                newQueryForm.pageNum = current
                newQueryForm.pageSize = pageSize
                setQueryParamsNew(newQueryForm)
                setQueryParams(newQueryForm)
            }}
            rowSelection={{
                selectedRowKeys: selectedRows.map(item => item.id),
                onSelect: (record: { id: number, mpName: string }, selected: boolean) => {
                    if (selected) {
                        selectedRows.push({ ...record })
                        setSelectedRows([...selectedRows])
                    } else {
                        let newSelectAccData = selectedRows.filter((item: { id: number }) => item.id !== record.id)
                        setSelectedRows([...newSelectAccData])
                    }
                },
                onSelectAll: (selected: boolean, selectedRowss: { id: number }[], changeRows: { id: number }[]) => {
                    if (selected) {
                        let newSelectAccData = [...selectedRows]
                        changeRows.forEach((item: { id: number }) => {
                            let index = newSelectAccData.findIndex((ite: { id: number }) => ite.id === item.id)
                            if (index === -1) {
                                let data: any = { ...item }
                                newSelectAccData.push(data)
                            }
                        })
                        setSelectedRows([...newSelectAccData])
                    } else {
                        let newSelectAccData = selectedRows.filter((item: { id: number }) => {
                            let index = changeRows.findIndex((ite: { id: number }) => ite.id === item.id)
                            if (index !== -1) {
                                return false
                            } else {
                                return true
                            }
                        })
                        setSelectedRows([...newSelectAccData])
                    }
                }
            }}
        />

        {/* 任务日志 */}
        {logVisible && <Log
            visible={logVisible}
            data={logData}
            onClose={() => {
                setLogData({})
                setLogVisible(false)
            }}
        />}

        {/* 执行记录 */}
        {executeLogVisible && <ExecuteLog
            visible={executeLogVisible}
            data={logData}
            onClose={() => {
                setLogData({})
                setExecuteLogVisible(false)
            }}
        />}
    </Card>
}

export default React.memo(TaskList)