import { Button, Card, Input, Radio, RadioChangeEvent, Select, Space, Spin, Tag, TimePicker, Tooltip } from "antd";
import React, { useCallback, useEffect, useState } from "react";
import { CloudDownloadOutlined, ColumnHeightOutlined, ColumnWidthOutlined, RedoOutlined } from "@ant-design/icons";
import useEcharts from '@/Hook/useEcharts'
import columnsMonitor from './tableMonitorConfig'
import { useModel } from 'umi'
import { ListType, downLoadUpAdApi, downLoadDetailApi, downLoadDetailMinuteApi } from '@/services/adMonitor/adMonitor'
import { qiliangpaihang, qiliangpaihangminute } from './config'
import { compare } from '@/utils/utils'
import PlanDetail from './components/planDetail'
import { formatDate, downloadFile1 } from '@/utils/downloadFile'
import './table.less'
import moment from "moment";
import TableData from "@/pages/launchSystemNew/components/TableData";
interface newListType extends ListType {
    totalTimeUnit: 'minute' | 'hour' | 'day',
    planTimeUnit: 'minute' | 'hour' | 'day'
}

/**
 * 今日起量监控
 * @param props 
 * @returns 
 */
function Monitor(props: { onChange: () => void }) {
    const { onChange } = props
    const { getPlanList, getTotalCost, getPlanCost, getPlanDetailList, getMinuteList, getAdqAccountList } = useModel('useAdMonitor.useMonitor')
    const { state } = useModel('useOperating.useWxGroupList')
    // 变量开始
    const [queryForm, setQueryForm] = useState<newListType>({ totalTimeUnit: 'day', planTimeUnit: 'hour', pageNum: 1, pageSize: 20 }) // 搜索变量//startTime: moment().format('YYYY-MM-DD'), endTime: moment().format('YYYY-MM-DD'),
    const { BarMonitor, LineMonitor } = useEcharts()
    const [barDis, setBarDis] = useState<any[]>([])
    const [lineDis, setLineDis] = useState<any[]>([])
    const [lineTitle, setLineTitle] = useState<string>('广告总消耗趋势')
    const [datas, setDatas] = useState<any[]>([])  // 所有数据
    const [pichers, setPichers] = useState<any[]>([]) // 投手数据
    const [mode, setMode] = useState<string>('total') // 总/明细
    const [px, setPx] = useState<boolean>(false)//设置顶部图形的排列方式
    const [planDetailList, setPlanDetailList] = useState<any[]>([])
    const [minuteList, setMinuteList] = useState<any[]>([])
    const [visible, setVisible] = useState<boolean>(false) // 详情弹窗控制
    const [aId, setAId] = useState<any>()
    const [downLoadLoading, setDownLoadLoading] = useState<boolean>(false)
    const { totalTimeUnit, planTimeUnit, adgroup, accountId, sysUserId, pageNum, pageSize, campaign, sortField, sort } = queryForm

    // 变量结束
    useEffect(() => {
        if (state?.allOfMember?.length > 0) {//组长数据存在使用组长数据
            setDatas(state?.allOfMember)
        } else if (state?.myallOfUser?.length > 0) {//否则个人
            setDatas(state?.myallOfUser)
        }
    }, [state])
    // 获取广告账号
    useEffect(() => {
        getAdqAccountList.run()
    }, [])
    // 处理投手
    useEffect(() => {
        if (datas.length > 0) {
            let new_pichers = datas?.map((item: { key: { nickname: string, userId: number } }) => ({ nickName: item?.key?.nickname, userId: item?.key?.userId }))
            if (JSON.stringify(pichers) !== JSON.stringify(new_pichers)) {//避免重复设置触发条件多次请求接口
                setPichers(new_pichers)
            }
        }
    }, [datas, pichers])
    // // 获取排行数据,柱图
    useEffect(() => {
        if (pichers.length > 0) {
            getPlanCostList()
        }
    }, [totalTimeUnit, accountId, sysUserId, pichers])
    // 获取起量计划列表 底部table
    useEffect(() => {
        if (pichers.length > 0) {
            if (mode === 'total') {
                getList()
            } else if (mode === 'detail') {
                if (adgroup) {
                    getDetailList(adgroup)
                }
            } else if (mode === 'minute') {
                if (adgroup) {
                    getMinuList(adgroup)
                }
            }
        }
    }, [accountId, sysUserId, pageNum, pageSize, campaign, pichers, adgroup, sortField, sort, mode])
    // 获取今日计划总消耗图谱,折线
    useEffect(() => {
        if (pichers.length > 0) {
            getTootalCostList()
        }
    }, [planTimeUnit, adgroup, accountId, sysUserId, pichers])
    // 获取起量明细表 点击
    useEffect(() => {
        // if (adgroup) {
        //     getDetailList(adgroup)
        // } else {
        //     setMode('total')//切到总表
        // }
        if (!adgroup) {
            setMode('total')//切到总表
        }
    }, [adgroup])
    /** 获取折线图 */
    const getTootalCostList = useCallback(async () => {
        let { totalTimeUnit, planTimeUnit, pageNum, pageSize, adgroup, sysUserId, accountId, ...newQueryForm } = queryForm
        let params = adgroup ? { ...newQueryForm, adgroupId: adgroup } : newQueryForm
        let newPitcherIds = sysUserId?.join()
        let res = await getTotalCost.run({ ...params, timeUnit: planTimeUnit, sysUserId: newPitcherIds, accountId: accountId?.join() })
        let data: any[] = [{ legendName: '消耗' }]
        res?.data?.totalCostDtoList?.forEach((item: any) => {
            data[0][item.currTime] = item.totalCost
        })
        setLineDis(() => data)
        setLineTitle(() => res?.data?.adName ? res?.data?.adName + '_消耗趋势' : '广告总消耗趋势')
    }, [queryForm, lineDis, pichers])

    /** 获取柱状图 */
    const getPlanCostList = useCallback(async () => {
        let { totalTimeUnit, planTimeUnit, pageNum, pageSize, sysUserId, accountId, ...newQueryForm } = queryForm
        let { adgroup, ...planQueryFrom } = newQueryForm
        let newPitcherIds = sysUserId?.join()
        let res = await getPlanCost.run({ ...planQueryFrom, timeUnit: totalTimeUnit, sysUserId: newPitcherIds, accountId: accountId?.join() })
        let data = res?.data?.planCostDtoList?.map((item: { adId: number, cost: number, adName: string }) => {
            return { name: item.adId.toString(), value: item.cost, adName: item.adName }
        })
        data = data?.sort((a: any, b: any) => {
            var value1 = a['value'];
            var value2 = b['value'];
            return value2 - value1;
        })
        setBarDis(() => data)
    }, [queryForm, barDis, pichers])

    // 气量Table总表
    const getList = useCallback(() => {
        let { totalTimeUnit, planTimeUnit, timeUnit, sysUserId, accountId, ...newQueryForm } = queryForm
        getPlanList.run({ ...newQueryForm, sysUserId, accountId: accountId?.join() })
    }, [queryForm, pichers])


    // 起量明细表 点击
    const getDetailList = useCallback((adgroup: any) => {
        let { totalTimeUnit, planTimeUnit, timeUnit, pageNum, pageSize, sysUserId, accountId, ...newQueryForm } = queryForm
        if (adgroup) {
            setMode('detail')//切到明细
            getPlanDetailList.run({ ...newQueryForm, pageNum: 1, pageSize: 20, adgroupId: adgroup, sysUserId, accountId: accountId?.join() }).then((res: any) => {
                setPlanDetailList(res?.data?.records ? [...res?.data?.records] : [])
                setQueryForm({ ...queryForm, adgroup })
            })
        }
    }, [queryForm, getPlanList, pichers, planDetailList])

    // 详情
    const details = (data: any) => {
        setAId(data)
        setVisible(true)
    }

    // 起量5min表
    const getMinuList = useCallback((adgroup: any) => {
        let { totalTimeUnit, planTimeUnit, timeUnit, pageNum, pageSize, sysUserId, accountId, ...newQueryForm } = queryForm
        if (adgroup) {
            setMode('minute')
            getMinuteList.run({ ...newQueryForm, pageNum: 1, pageSize: 20, adgroupId: adgroup, sysUserId, accountId: accountId?.join() }).then((res: any) => {
                setMinuteList(res?.data?.records ? [...res?.data?.records] : [])
                setQueryForm({ ...queryForm, adgroup })
            })
        }
    }, [queryForm, getPlanList, pichers, minuteList, adgroup])

    // 计划详情
    const planDetail = (data: any) => {
        sessionStorage.setItem('ADIDORNAME', JSON.stringify(data))
        onChange && onChange()
    }

    //全部接口刷新
    const refresh = () => {
        getPlanList.refresh()
        getTotalCost.refresh()
        getPlanCost.refresh()
        getPlanDetailList.refresh()
        getMinuteList.refresh()
    }
    // 接口自动刷新10分钟一次
    useEffect(() => {
        let time = setInterval(() => {
            refresh()
        }, 1000 * 60 * 10)
        return () => {
            clearInterval(time)
        }
    }, [pichers])
    //图形排列样式改变重新获取数据刷新图形
    const set = useCallback((b) => {
        setPx(b)
        getTotalCost.refresh()
        getPlanCost.refresh()
    }, [getPlanCost, getTotalCost])

    // 下载
    const downLoadExcel = useCallback(() => {
        // downLoadUpAdApi, downLoadDetailApi, downLoadDetailMinuteApi
        let ajax: any = null
        let params: any = {}
        let { totalTimeUnit, planTimeUnit, timeUnit, sysUserId, accountId, adgroup, pageNum, pageSize, ...newQueryForm } = queryForm
        let newPitcherIds = sysUserId?.join()
        switch (mode) {
            case 'total':
                params = { ...newQueryForm, sysUserId: newPitcherIds, accountId: accountId?.join() }
                ajax = downLoadUpAdApi
                break;
            case 'detail':
                params = { ...newQueryForm, adgroup, sysUserId: newPitcherIds, accountId: accountId?.join() }
                ajax = downLoadDetailApi
                break;
            case 'minute':
                params = { ...newQueryForm, adgroup, sysUserId: newPitcherIds, accountId: accountId?.join() }
                ajax = downLoadDetailMinuteApi
                break;
        }
        if (ajax) {
            setDownLoadLoading(true)
            ajax(params).then((res: any) => {
                setDownLoadLoading(false)
                downloadFile1(res, 'octet-stream', formatDate(new Date()) + ".xlsx")
            }).catch(() => setDownLoadLoading(false))
        }
    }, [queryForm, mode, pichers, downLoadLoading])

    // 处理折线图数据
    const timePickerHandle = async (values: any, formatString: [string, string]) => {
        let res = await getTotalCost.data
        let data: any[] = [{ legendName: '消耗' }]
        res?.data?.totalCostDtoList?.forEach((item: any) => {
            data[0][item.currTime] = item.totalCost
        })
        if (values) {
            let date = moment().format('YYYY-MM-DD')
            let strTime = formatString[0]
            let endTime = formatString[1]
            let dateTimeStr = `${date} ${strTime}:00`
            let dateTimeEnd = `${date} ${endTime}:00`
            let { legendName, ...otherData } = data[0]
            let newData: any = { legendName }
            for (const key in otherData) {
                if (Object.prototype.hasOwnProperty.call(otherData, key)) {
                    const value = otherData[key];
                    if (moment(dateTimeStr) <= moment(key) && moment(key) <= moment(dateTimeEnd)) {
                        newData[key] = value
                    }
                }
            }
            setLineDis(() => [newData])
        } else {
            setLineDis(() => data)
        }
    }

    return <Space direction='vertical' style={{ width: '100%' }} className="monitor">
        <Card hoverable >
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <Space>
                    <Select
                        showSearch
                        value={queryForm.sysUserId}
                        style={{ minWidth: 180 }}
                        mode='multiple'
                        maxTagCount={1}
                        disabled={queryForm?.accountId?.length > 0}
                        allowClear placeholder="请选择投手"
                        onChange={(value: string) => { setQueryForm({ ...queryForm, sysUserId: value, pageNum: 1 }) }}
                        filterOption={(input, option) =>
                            (option?.children as any).toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                    >
                        {pichers?.map((item: { nickName: string, userId: number }, index: number) =>
                            <Select.Option
                                value={item.userId}
                                key={item.userId + '' + index}
                            >
                                {item.nickName}
                            </Select.Option>
                        )}
                    </Select>
                    <Select
                        showSearch
                        mode='multiple'
                        maxTagCount={1}
                        value={queryForm.accountId}
                        style={{ minWidth: 220 }}
                        allowClear
                        placeholder="请选择广告账号"
                        filterOption={(input, option) =>
                            (option?.children as any).toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        onChange={(value: string) => {
                            setQueryForm({ ...queryForm, accountId: value, pageNum: 1 })
                        }}
                    >
                        {getAdqAccountList?.data?.data?.map((item: { id: number, accountId: number, wechatAccountName: string }) => <Select.Option
                            value={item.accountId}
                            key={item.id}
                        >
                            {item.accountId + "_" + item.wechatAccountName}
                        </Select.Option>)}
                    </Select>
                    <Input value={queryForm.campaign} placeholder="计划ID" onChange={(e) => {
                        let value = e.target.value
                        if (!isNaN(Number(value))) {
                            setQueryForm({ ...queryForm, campaign: value })
                        }
                    }}
                        allowClear />
                    <Input value={queryForm.adgroup} placeholder="广告ID" onChange={(e) => {
                        let value = e.target.value
                        if (!isNaN(Number(value))) {
                            setQueryForm({ ...queryForm, adgroup: e.target.value })
                        }
                    }
                    } allowClear />
                </Space>
                <Space>
                    <Tag color="#2db7f5" onClick={refresh}><RedoOutlined />   刷新</Tag>
                </Space>
            </div>
        </Card>
        <Card hoverable>
            <span style={{ position: 'absolute', top: 10 }}>
                {px ?
                    <Tooltip title='左右排列'><Tag color='#f50' onClick={() => { set(false) }}><ColumnWidthOutlined /><span style={{ fontSize: 10 }}>左右排列</span></Tag></Tooltip>
                    :
                    <Tooltip title='上下排列'><Tag color='#f50' onClick={() => { set(true) }} ><ColumnHeightOutlined /><span style={{ fontSize: 10 }}>上下排列</span></Tag></Tooltip>
                }
            </span>
            <div className={!px ? 'charts' : 'charts charts100'}>
                <div>
                    <div className="selectTime">
                        <Space>
                            <span style={{ fontSize: 10, color: '#999' }}>刷新时间:{getPlanCost?.data?.reqTime}</span>
                            <Radio.Group value={queryForm.totalTimeUnit} buttonStyle="solid" size='small' onChange={(e) => { setQueryForm({ ...queryForm, totalTimeUnit: e.target.value }) }}>
                                <Radio.Button value="day">天</Radio.Button>
                                <Radio.Button value="hour">小时</Radio.Button>
                                <Radio.Button value="minute">5min</Radio.Button>
                            </Radio.Group>
                        </Space>
                    </div>
                    {getPlanCost?.loading ? <Spin /> : <BarMonitor style={{ width: '100%', height: '100%' }} data={barDis} xName="今日消耗" yName="广告名称" onChange={(value?: string) => { setQueryForm({ ...queryForm, adgroup: value }); setMode('detail') }} planID={queryForm?.adgroup} />}
                </div>
                <div>
                    <div className="selectTime">
                        <Space>
                            <span style={{ fontSize: 10, color: '#999' }}>刷新时间:{getTotalCost?.data?.reqTime}</span>
                            <Radio.Group value={queryForm.planTimeUnit} buttonStyle="solid" size='small' onChange={(e) => { setQueryForm({ ...queryForm, planTimeUnit: e.target.value }) }}>
                                <Radio.Button value="hour">小时</Radio.Button>
                                <Radio.Button value="minute">5min</Radio.Button>
                            </Radio.Group>
                            {queryForm.planTimeUnit === 'minute' && <TimePicker.RangePicker
                                size="small"
                                format='HH:mm'
                                minuteStep={5}
                                onChange={timePickerHandle}
                            />}
                        </Space>
                    </div>
                    {getTotalCost?.loading ? <Spin /> : <LineMonitor style={{ width: '100%', height: '100%' }} series smooth data={lineDis} title={lineTitle} />}
                </div>
            </div>
        </Card>
        <div className={'MYtable'}>
            <TableData
                columns={columnsMonitor(planDetail, getDetailList, details, getMinuList, mode)}
                dataSource={mode === 'total' ? getPlanList?.data?.data?.records?.map((item: any, index: number) => ({ ...item, id: item.id + '_' + index })) : mode === 'detail' ? getPlanDetailList?.data?.data?.records?.map((item: any, index: number) => ({ ...item, id: item.id + '_' + index })) : getMinuteList?.data?.data?.records?.map((item: any, index: number) => ({ ...item, id: item.id + '_' + index }))}
                loading={mode === 'total' ? getPlanList?.loading : mode === 'detail' ? getPlanDetailList?.loading : getMinuteList?.loading}
                ajax={mode === 'total' ? getPlanList : mode === 'detail' ? getPlanDetailList : getMinuteList}
                leftChild={
                    <Space>
                        <Radio.Group onChange={(e: RadioChangeEvent) => {
                            let value = e.target.value
                            setMode(value)
                        }} value={mode} size='small'>
                            <Radio.Button value="total">总</Radio.Button>
                            <Radio.Button value="detail" disabled={!adgroup}>小时</Radio.Button>
                            <Radio.Button value="minute" disabled={!adgroup}>5min</Radio.Button>
                        </Radio.Group>
                        <Button size="small" icon={<CloudDownloadOutlined />} loading={downLoadLoading} onClick={downLoadExcel}>{mode === 'total' ? '总表' : mode === 'detail' ? '小时表' : '5min表'}下载</Button>
                    </Space>
                }
                fixed={{ left: 0, right: 2 }}
                total={mode === 'total' ? getPlanList?.data?.data?.total : 0}
                onChange={mode === 'total' ? (props: any) => {
                    let { sortData, pagination } = props
                    let { current, pageSize } = pagination
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    newQueryForm.pageNum = current
                    newQueryForm.pageSize = pageSize
                    if (sortData && JSON.stringify('sortData') !== '{}') {
                        let { field, order } = sortData   // descend 降序 大到小  ascend 升序 小到大
                        if (order) {
                            newQueryForm.sortField = field
                            newQueryForm.sort = order === 'ascend' ? 'ASC' : 'DESC'
                        } else {
                            Object.keys(newQueryForm).forEach(key => {
                                if (key === 'sortField' || key === 'sort') {
                                    delete newQueryForm[key]
                                }
                            })
                        }
                    } else {
                        Object.keys(newQueryForm).forEach(key => {
                            if (key === 'sortField' || key === 'sort') {
                                delete newQueryForm[key]
                            }
                        })
                    }
                    setQueryForm({ ...newQueryForm })
                } : (props: any) => {
                    let { sortData } = props
                    if (sortData && JSON.stringify('sortData') !== '{}') {
                        let { field, order } = sortData   // descend 降序 大到小  ascend 升序 小到大 planDetailList
                        if (mode === 'detail') {
                            getPlanDetailList?.mutate({ records: order ? getPlanDetailList?.data?.data?.records?.sort(compare(field, order)) : [...planDetailList] })
                        } else if (mode === 'minute') {
                            getMinuteList?.mutate({ records: order ? getMinuteList?.data?.data?.records?.sort(compare(field, order)) : [...minuteList] })
                        }
                    }
                }}
                page={mode === 'total' ? queryForm.pageNum : undefined}
                pageSize={mode === 'total' ? queryForm.pageSize : undefined}
                scroll={{ y: 620 }}
                config={mode === 'minute' ? qiliangpaihangminute : qiliangpaihang}
                configName={mode === 'total' ? '起量广告排行' : mode === 'detail' ? '起量广告排行明细' : '起量广告5min'}
            />
        </div>

        {visible && <PlanDetail visible={visible} onClose={() => { setVisible(false) }} data={aId} />}
    </Space>
}


export default React.memo(Monitor)