import { Button, Card, DatePicker, 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 TableData from '../components/TableData'
import { useModel } from 'umi'
import { ListType, downLoadUpAdApi, downLoadDetailApi, downLoadDetailMinuteApi } from '@/services/launch/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";
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 } = useModel('useLaunch.useMonitor')
    const { state } = useModel('useOperating.useWxGroupList')
    // 变量开始
    const [queryForm, setQueryForm] = useState<newListType>({ totalTimeUnit: 'day', planTimeUnit: 'hour', page: 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 [mpDatas, setMpDatas] = useState<any[]>([]) // 公众号
    const [mpDatasB, setMpDatasB] = 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, adId, mpAppIds, pitcherIds, page, pageSize, planId, sortField, sort } = queryForm
    // 变量结束
    useEffect(() => {
        if (state?.allOfMember?.length > 0) {//组长数据存在使用组长数据
            setDatas(state?.allOfMember)
        } else if (state?.myallOfUser?.length > 0) {//否则个人
            setDatas(state?.myallOfUser)
        }
    }, [state])
    // 处理公众号
    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)
            }
            if (pitcherIds?.length > 0) {
                let arr: any = []
                pitcherIds?.forEach((pitcherId: any) => {
                    let data = datas?.find((item: { key: any }) => item?.key?.userId == pitcherId)
                    arr.push(data)
                })
                if (arr?.length > 0) {
                    setMpDatas(arr)
                    setMpDatasB(arr)
                }
            } else {
                setMpDatas(datas)
                setMpDatasB(datas)
            }
            // select()//首次搜索数据
        }
    }, [datas, pitcherIds, pichers])
    // // 获取排行数据,柱图
    useEffect(() => {
        if (pichers.length > 0) {
            getPlanCostList()
        }
    }, [totalTimeUnit, mpAppIds, pitcherIds, pichers])
    // 获取起量计划列表 底部table
    useEffect(() => {
        if (pichers.length > 0) {
            if (mode === 'total') {
                getList()
            } else if (mode === 'detail') {
                if (adId) {
                    getDetailList(adId)
                }
            } else if (mode === 'minute') {
                if (adId) {
                    getMinuList(adId)
                }
            }
        }
    }, [mpAppIds, pitcherIds, page, pageSize, planId, pichers, adId, sortField, sort, mode])
    // 获取今日计划总消耗图谱,折线
    useEffect(() => {
        if (pichers.length > 0) {
            getTootalCostList()
        }
    }, [planTimeUnit, adId, mpAppIds, pitcherIds, pichers])
    // 获取起量明细表 点击
    useEffect(() => {
        // if (adId) {
        //     getDetailList(adId)
        // } else {
        //     setMode('total')//切到总表
        // }
        if (!adId) {
            setMode('total')//切到总表
        }
    }, [adId])
    /** 获取折线图 */
    const getTootalCostList = useCallback(async () => {
        let { totalTimeUnit, planTimeUnit, page, pageSize, adId, pitcherIds, mpAppIds, ...newQueryForm } = queryForm
        let params = adId ? { ...newQueryForm, adId } : newQueryForm
        let newPitcherIds = pitcherIds?.join()
        if (!newPitcherIds && (!mpAppIds || mpAppIds?.length === 0)) {//当没有选择投手时选择所有投手，假如选择了公众号这个条件不成立
            newPitcherIds = pichers?.map(item => item.userId)?.join()
        }
        let res = await getTotalCost.run({ ...params, timeUnit: planTimeUnit, pitcherIds: newPitcherIds, mpAppIds: mpAppIds?.join() })
        let data: any[] = [{ legendName: '消耗' }]
        res?.data?.totalCostDtoList?.forEach((item: any) => {
            data[0][item.localDateTime] = item.hourTotalCost
        })
        setLineDis(() => data)
        setLineTitle(() => res?.data?.adName ? res?.data?.adName + '_消耗趋势' : '广告总消耗趋势')
    }, [queryForm, lineDis, pichers])

    /** 获取柱状图 */
    const getPlanCostList = useCallback(async () => {
        let { totalTimeUnit, planTimeUnit, page, pageSize, pitcherIds, mpAppIds, ...newQueryForm } = queryForm
        let { adId, ...planQueryFrom } = newQueryForm
        let newPitcherIds = pitcherIds?.join()
        if (!newPitcherIds && (!mpAppIds || mpAppIds?.length === 0)) {
            newPitcherIds = pichers?.map(item => item.userId)?.join()
        }
        let res = await getPlanCost.run({ ...planQueryFrom, timeUnit: totalTimeUnit, pitcherIds: newPitcherIds, mpAppIds: mpAppIds?.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, pitcherIds, mpAppIds, adId, ...newQueryForm } = queryForm
        let newPitcherIds = pitcherIds?.join()
        if (!newPitcherIds && (!mpAppIds || mpAppIds?.length === 0)) {
            newPitcherIds = pichers?.map(item => item.userId)?.join()
        }
        getPlanList.run({ ...newQueryForm, pitcherIds: newPitcherIds, mpAppIds: mpAppIds?.join() })
    }, [queryForm, pichers])


    // 起量明细表 点击
    const getDetailList = useCallback((adId: any) => {
        let { totalTimeUnit, planTimeUnit, timeUnit, page, pageSize, pitcherIds, mpAppIds, ...newQueryForm } = queryForm
        let newPitcherIds = pitcherIds?.join()
        if (!newPitcherIds && (!mpAppIds || mpAppIds?.length === 0)) {
            newPitcherIds = pichers?.map(item => item.userId)?.join()
        }
        if (adId) {
            setMode('detail')//切到明细
            getPlanDetailList.run({ ...newQueryForm, page: 1, pageSize: 20, adId, pitcherIds: newPitcherIds, mpAppIds: mpAppIds?.join() }).then((res: any) => {
                setPlanDetailList(res?.data ? [...res?.data] : [])
                setQueryForm({ ...queryForm, adId })
            })
        }
    }, [queryForm, getPlanList, pichers, planDetailList])

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

    // 起量5min表
    const getMinuList = useCallback((adId: any) => {
        let { totalTimeUnit, planTimeUnit, timeUnit, page, pageSize, pitcherIds, mpAppIds, ...newQueryForm } = queryForm
        let newPitcherIds = pitcherIds?.join()
        if (!newPitcherIds && (!mpAppIds || mpAppIds?.length === 0)) {
            newPitcherIds = pichers?.map(item => item.userId)?.join()
        }
        if (adId) {
            setMode('minute')
            getMinuteList.run({ ...newQueryForm, page: 1, pageSize: 20, adId, pitcherIds: newPitcherIds, mpAppIds: mpAppIds?.join() }).then((res: any) => {
                setMinuteList(res?.data ? [...res?.data] : [])
                setQueryForm({ ...queryForm, adId })
            })
        }
    }, [queryForm, getPlanList, pichers, minuteList, adId])

    // 计划详情
    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, pitcherIds, mpAppIds, adId, page, pageSize, ...newQueryForm } = queryForm
        let newPitcherIds = pitcherIds?.join()
        if (!newPitcherIds && (!mpAppIds || mpAppIds?.length === 0)) {
            newPitcherIds = pichers?.map(item => item.userId)?.join()
        }
        switch (mode) {
            case 'total':
                params = { ...newQueryForm, pitcherIds: newPitcherIds, mpAppIds: mpAppIds?.join() }
                ajax = downLoadUpAdApi
                break;
            case 'detail':
                params = { ...newQueryForm, adId, pitcherIds: newPitcherIds, mpAppIds: mpAppIds?.join() }
                ajax = downLoadDetailApi
                break;
            case 'minute':
                params = { ...newQueryForm, adId, pitcherIds: newPitcherIds, mpAppIds: mpAppIds?.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.localDateTime] = item.hourTotalCost
        })
        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.pitcherIds}
                        style={{ minWidth: 180 }}
                        mode='multiple'
                        maxTagCount={1}
                        disabled={queryForm?.mpAppIds?.length > 0}
                        allowClear placeholder="请选择投手"
                        onChange={(value: string) => { setQueryForm({ ...queryForm, pitcherIds: value, page: 1 }) }}
                        filterOption={(input, option) =>
                            option?.children.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.mpAppIds}
                        onBlur={() => {
                            setMpDatas(mpDatasB)
                        }}
                        onSearch={(value: string) => {
                            if (value) {
                                let arr: any = []
                                mpDatas.forEach((item: { key: { userId: string, nickName: string }, value: any[] }) => {
                                    let i: any = { key: item.key, value: [] }
                                    item?.value?.forEach(v => {
                                        if (v?.nickName?.includes(value)) {
                                            i.value.push(v)
                                        }
                                    })
                                    if (i.value.length > 0) {
                                        arr.push(i)
                                    }
                                })
                                if (arr.length > 0 && JSON.stringify(mpDatas) !== JSON.stringify(arr)) {
                                    setMpDatas(arr)
                                }
                            } else {
                                setMpDatas(mpDatasB)
                            }
                        }}
                        filterOption={(input, option) => {
                            return true
                        }
                        }
                        style={{ minWidth: 220 }} allowClear placeholder="请选择公众号"
                        onChange={(value: string) => {
                            setQueryForm({ ...queryForm, mpAppIds: value, page: 1 })
                        }
                        }
                    >
                        {mpDatas?.map((item: { key: { userId: string, nickName: string }, value: any[] }, index: number) => {
                            if (item?.value?.length > 0) {
                                return <Select.OptGroup key={item?.key?.userId} label={item?.key?.nickName}>
                                    {
                                        item?.value?.map((value: any) => {
                                            if (value?.nickName && !value?.nickName.includes('注销')) {
                                                return <Select.Option
                                                    value={value.appid}
                                                    key={value.appid + '' + index}
                                                >
                                                    {value?.nickName}
                                                </Select.Option>
                                            }
                                            return null
                                        })
                                    }
                                </Select.OptGroup>
                            }
                            return null
                        })}
                    </Select>
                    <Input value={queryForm.planId} placeholder="计划ID" onChange={(e) => {
                        let value = e.target.value
                        if (!isNaN(Number(value))) {
                            setQueryForm({ ...queryForm, planId: value })
                        }
                    }}
                        allowClear />
                    <Input value={queryForm.adId} placeholder="广告ID" onChange={(e) => {
                        let value = e.target.value
                        if (!isNaN(Number(value))) {
                            setQueryForm({ ...queryForm, adId: 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, adId: value }); setMode('detail') }} planID={queryForm?.adId} />}
                </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?.adInfoVoList : mode === 'detail' ? getPlanDetailList?.data?.data : getMinuteList?.data?.data}
                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={!adId}>小时</Radio.Button>
                            <Radio.Button value="minute" disabled={!adId}>5min</Radio.Button>
                        </Radio.Group>
                        <Button size="small" icon={<CloudDownloadOutlined />} loading={downLoadLoading} onClick={downLoadExcel}>{mode === 'total' ? '总表' : mode === 'detail' ? '小时表' : '5min表'}下载</Button>
                    </Space>
                }
                total={mode === 'total' ? getPlanList?.data?.data?.totalCount : 0}
                onChange={mode === 'total' ? (props: any) => {
                    let { sortData, pagination } = props
                    let { current, pageSize } = pagination
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    newQueryForm.page = 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({ data: order ? getPlanDetailList?.data?.data?.sort(compare(field, order)) : [...planDetailList] })
                        } else if (mode === 'minute') {
                            getMinuteList?.mutate({ data: order ? getMinuteList?.data?.data?.sort(compare(field, order)) : [...minuteList] })
                        }
                    }
                }}
                page={mode === 'total' ? getPlanList?.data?.data?.page : undefined}
                pageSize={mode === 'total' ? getPlanList?.data?.data?.pageSize : undefined}
                scroll={{ y: 620 }}
                config={mode === 'minute' ? qiliangpaihangminute : qiliangpaihang}
                configName={mode === 'total' ? '起量广告排行' : mode === 'detail' ? '起量广告排行明细' : '起量广告5min'}
            />
        </div>

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


export default React.memo(Monitor)