import Tables from "@/components/Tables";
import useEcharts from "@/Hook/useEcharts";
import { CloudDownloadOutlined, RedoOutlined } from "@ant-design/icons";
import { Button, Card, DatePicker, Modal, Radio, Space, Spin, Statistic, Tag } from "antd";
import moment, { Moment } from "moment";
import React, { useCallback, useEffect, useState } from "react";
import { useModel } from "umi";
import columns from './tableConfig'
import { compare } from '@/utils/utils'
import { formatDate, downloadFile1 } from '@/utils/downloadFile'
import { downLoadSpeedApi } from "@/services/adMonitor/adMonitor";
import '../index.less'

type Props = {
    visible?: boolean,
    onClose?: () => void,
    data?: any,
    dataStartTime?: string
    dataEndTime?: string
}

function PlanDetail(props: Props) {
    const { adgroupId, putUserId, accountId } = props.data
    const { getCostSpeed } = useModel('useAdMonitor.useMonitor')

    /** 变量start */
    const { visible, onClose, dataStartTime, dataEndTime } = props
    const { LineMonitor } = useEcharts()
    const [lineDis, setLineDis] = useState<any[]>([])
    const [queryForm, setQueryForm] = useState<any>({ adgroupId, accountId, sysUserId: putUserId, timeUnit: dataStartTime || dataEndTime ? 'day' : 'hour', dataStartTime: dataStartTime || moment().format('YYYY-MM-DD'), dataEndTime: dataEndTime || moment().format('YYYY-MM-DD') })
    const [speedData, setSpeedData] = useState<{ totalCost: string, viewCount: string, clickCount: string, clickRate: string, orderRate: string, costSpeed: string, adCostSpeedVOList: any[] }>()
    const [adCostSpeedDtoListOri, setAdCostSpeedDtoListOri] = useState<any[]>([])
    const [downLoadLoading, setDownLoadLoading] = useState<boolean>(false)
    /** 变量end */
    useEffect(() => {
        getList()
    }, [queryForm])
    const getList = useCallback(() => {
        getCostSpeed.run(queryForm).then((res: any) => {
            if (res?.data) {
                setSpeedData(() => res?.data)
                setAdCostSpeedDtoListOri(() => [...res?.data?.adCostSpeedVOList])
                let spendData: any = { legendName: '花费' }
                let exposureData: any = { legendName: '曝光次数' }
                res?.data?.adCostSpeedVOList?.forEach((item: { day: string, time: string, cost: string, viewCount: string }) => {
                    if (queryForm.timeUnit === 'hour') {
                        spendData[item?.time] = item?.cost
                        exposureData[item?.time] = item?.viewCount
                    } else {
                        spendData[item?.day] = item?.cost
                        exposureData[item?.day] = item?.viewCount
                    }
                });
                setLineDis(() => [spendData, exposureData])
            }
        })
    }, [queryForm, adCostSpeedDtoListOri, speedData])
    // 设置获取图标数据区间 设置时间
    const setTime = useCallback((str: string[]) => {
        setQueryForm({ ...queryForm, dataStartTime: str[0], dataEndTime: str[1] })
    }, [queryForm])

    const disabledDate = (date: Moment) => {
        if (queryForm?.timeUnit === 'hour') {
            return date && (date < moment().startOf('day').subtract(9, 'day') || date > moment().endOf('day'))
        } else {
            return false
        }
    }

    const downLoadExcel = useCallback(() => {
        setDownLoadLoading(true)
        downLoadSpeedApi(queryForm).then(res => {
            setDownLoadLoading(false)
            downloadFile1(res, 'octet-stream', formatDate(new Date()) + ".xlsx")
        }).catch(() => setDownLoadLoading(false))
    }, [queryForm, downLoadLoading])

    return <Modal
        title={<><Space>
            <span style={{ fontSize: 15, color: '#999' }}>计划名称:<span style={{ color: '#40a9ff' }}>{props?.data?.campaignName || '--'}</span></span>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <span style={{ fontSize: 15, color: '#999' }}>广告名称:<span style={{ color: '#40a9ff' }}>{props?.data?.adgroupName}</span></span>
        </Space></>}
        open={visible}
        width={900}
        bodyStyle={{ padding: '0 5px', backgroundColor: '#f2f2f2' }}
        footer={null}
        onCancel={() => { onClose && onClose() }}
    >
        <Space direction='vertical' style={{ width: '100%', marginBottom: 10 }}>
            <Card hoverable size='small'>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Space>
                        <DatePicker.RangePicker disabledDate={disabledDate} allowClear={false} onChange={(mo: any, str: string[]) => { setTime(str) }} value={(queryForm?.dataStartTime && queryForm?.dataEndTime ? [moment(queryForm?.dataStartTime), moment(queryForm?.dataEndTime)] : null) as any} />
                        <Radio.Group
                            value={queryForm?.timeUnit}
                            buttonStyle="solid"
                            size='small'
                            onChange={(e) => {
                                if (e.target.value === 'hour') {
                                    setQueryForm({ ...queryForm, timeUnit: e.target.value, dataStartTime: moment().format('YYYY-MM-DD'), dataEndTime: moment().format('YYYY-MM-DD') })
                                } else {
                                    setQueryForm({ ...queryForm, timeUnit: e.target.value })
                                }
                            }}>
                            {/* <Radio.Button value="minute">5min</Radio.Button> */}
                            <Radio.Button value="day">分天</Radio.Button>
                            <Radio.Button value="hour">小时</Radio.Button>
                        </Radio.Group>
                    </Space>
                    <Space style={{ marginRight: 30 }}>
                        <span style={{ fontSize: 10, color: '#999' }}>刷新时间:{getCostSpeed?.data?.reqTime}</span>
                        <Tag color="#2db7f5" onClick={() => { getList() }}><RedoOutlined />   刷新</Tag>
                    </Space>
                </div>
            </Card>
            <Card
                hoverable
                title='数据展示'
            >
                <Spin spinning={getCostSpeed?.loading}>
                    <div className='overviewData'>
                        <div>
                            <div>总消耗</div>
                            <Statistic value={speedData?.totalCost || 0} valueStyle={{ color: '#03A613', fontSize: 16 }} />
                        </div>
                        <div>
                            <div>曝光次数</div>
                            <Statistic value={speedData?.viewCount || 0} valueStyle={{ fontSize: 16 }} />
                        </div>
                        <div>
                            <div>点击次数</div>
                            <Statistic value={speedData?.clickCount || 0} valueStyle={{ fontSize: 16 }} />
                        </div>
                        <div>
                            <div>点击率</div>
                            <Statistic value={(speedData?.clickRate ? Number(speedData?.clickRate) * 100 : 0).toFixed(2)} precision={2} valueStyle={{ color: '#3f8600', fontSize: 16 }} suffix="%" />
                        </div>
                        <div>
                            <div>所选时间内平均消耗速度</div>
                            <Statistic value={speedData?.costSpeed ? Number(speedData?.costSpeed).toFixed(2) : 0} valueStyle={{ color: '#cf1322', fontSize: 16 }} />
                        </div>
                    </div>
                </Spin>
            </Card>
            <Card
                hoverable
                title='趋势图'
            >
                <div style={{ width: '100%', height: 260, textAlign: 'center' }}>
                    {getCostSpeed?.loading ? <Spin /> : <LineMonitor style={{ width: '100%', height: 260 }} series smooth data={lineDis} />}
                </div>
            </Card>
            <Card
                hoverable
                title={<Space>
                    <div>明细表</div>
                    <Button size="small" icon={<CloudDownloadOutlined />} loading={downLoadLoading} onClick={downLoadExcel}>下载</Button>
                </Space>}
            >
                <Tables
                    columns={columns(queryForm?.timeUnit)}
                    dataSource={speedData?.adCostSpeedVOList || []}
                    total={speedData?.adCostSpeedVOList?.length}
                    loading={getCostSpeed?.loading}
                    size="small"
                    bordered
                    sortDirections={['ascend', 'descend', null]}
                    onChange={(pagination: any, filters: any, sorter: any) => {
                        if (JSON.stringify(sorter) !== '{}') {
                            let { field, order } = sorter   // descend 降序 大到小  ascend 升序 小到大
                            if (JSON.stringify(speedData) !== '{}') {
                                setSpeedData({ ...speedData as any, adCostSpeedVOList: order ? speedData?.adCostSpeedVOList?.sort(compare(field, order)) : [...adCostSpeedDtoListOri] })
                            }
                        }
                    }}
                />
            </Card>
        </Space>

    </Modal>
}

export default React.memo(PlanDetail)