import useEcharts from "@/Hook/useEcharts"
import { GetColumnTrendProps, GetListForAdProps } from "@/services/adMonitor/adMonitor"
import { Card, DatePicker, Drawer, Select, Space, Spin, Tabs } from "antd"
import React, { useEffect, useState } from "react"
import { useModel } from "umi"
import '@/pages/adMonitor/adMonitorList/components/index.less'
import TableData from "@/pages/launchSystemNew/components/TableData"
import { detailsConfig } from "@/pages/adMonitor/adMonitorList/config1"
import moment from "moment"
import { columnsList } from "@/pages/adMonitor/adMonitorList/tableMonitorConfig1"
import { LineField } from "@/pages/adMonitor/adMonitorList/config"
import TabAd from "./TabAd"

interface Props {
    data: any,
    onClose?: () => void,
    visible?: boolean
}
const Details: React.FC<Props> = ({ data, onClose, visible }) => {

    /****************************************/
    const { adgroup_id, account_id } = data
    const [activeKey, setActiveKey] = useState<string>('1')
    const [queryColumnTrend, setQueryColumnTrend] = useState<GetColumnTrendProps>({ accountId: account_id, adgroupId: adgroup_id, trendColumns: ['cost'], timeUnit: 'hour', dataTimeMin: moment().format('YYYY-MM-DD'), dataTimeMax: moment().format('YYYY-MM-DD') })
    const [queryList, setQueryList] = useState<GetListForAdProps>({ accountId: account_id, adgroupId: adgroup_id, columns: [], pageNum: 1, pageSize: 20, timeUnit: 'hour', dataTimeMin: moment().format('YYYY-MM-DD'), dataTimeMax: moment().format('YYYY-MM-DD') })
    const [lineDis, setLineDis] = useState<any[]>([])
    const { LineMonitor } = useEcharts()
    const configName = '数据报表3.0'
    const [totalData, setTotalData] = useState<any[]>([])

    const { getColumnTrendV3, getAdTotalDataV3, getListForAdV3 } = useModel('useAdMonitor.useMonitor')
    /****************************************/

    useEffect(() => {
        getCTList()
    }, [queryColumnTrend])

    const getCTList = () => {
        getColumnTrendV3.run(queryColumnTrend).then(res => {
            if (res?.data) {
                let trendColumns = queryColumnTrend.trendColumns
                let data = trendColumns.map((field) => {
                    let value: any = {}
                    res?.data?.forEach((item: any, index: number) => {
                        if (index === 0) value.legendName = LineField[field];
                        value[item?.trend_unit] = item?.[field]
                    });
                    return value
                })
                setLineDis(() => data)
            }
        })
    }

    useEffect(() => {
        getListList()
    }, [queryList])

    const getListList = () => {
        let columns: string[] = []
        let message = localStorage.getItem(`myAdMonitorConfig1.0.1_${configName}`)
        if (message) {
            message = JSON.parse(message)
        }
        if (message && Array.isArray(message)) {
            message.forEach((item: { serverIndex: any; dataIndex: string; }) => {
                columns.push('adgroup_data.' + item.dataIndex)
            })
        } else {
            detailsConfig.forEach((item: any) => {
                item?.data?.forEach((d: { default: any, serverIndex: string, dataIndex: string }) => {
                    if (d.default) {
                        columns.push('adgroup_data.' + d.dataIndex)
                    }
                })
            })
        }
        getListForAdV3.run({ ...queryList, columns })
        let queryTotal = JSON.parse(JSON.stringify(queryList))
        delete queryTotal.pageNum
        delete queryTotal.pageSize
        delete queryTotal.timeUnit
        getAdTotalDataV3.run({ ...queryTotal, columns }).then(res => {
            console.log(res)
            if (res?.data) {
                let data = res.data
                data.id = 1
                data.time = '总计'
                setTotalData([data])
            }
        })
    }

    return <Drawer
        title={data?.adgroup_name}
        placement="right"
        onClose={onClose}
        visible={visible}
        width={'70%'}
        bodyStyle={{ padding: '0 10px', background: '#efefef' }}
        className="detail_drawer"
    >
        <Tabs activeKey={activeKey} onChange={(e) => setActiveKey(e)} tabBarExtraContent={activeKey === '1' ? <Space>
            <Select
                size="small"
                value={queryColumnTrend.timeUnit}
                style={{ width: 78 }}
                onChange={(e) => {
                    setQueryColumnTrend({ ...queryColumnTrend, timeUnit: e })
                    setQueryList({ ...queryList, timeUnit: e })
                }}
            >
                <Select.Option value="day">天</Select.Option>
                <Select.Option value="hour">小时</Select.Option>
                <Select.Option value="minute">5min</Select.Option>
            </Select>
            <DatePicker.RangePicker
                size="small"
                placeholder={['数据时间筛选(起始)', '数据时间筛选(结束)']}
                value={(queryColumnTrend?.dataTimeMin && queryColumnTrend?.dataTimeMax) ? [moment(queryColumnTrend.dataTimeMin), moment(queryColumnTrend.dataTimeMax)] : undefined as any}
                style={{ width: 320 }}
                onChange={(_, o) => {
                    setQueryColumnTrend({ ...queryColumnTrend, dataTimeMin: o[0], dataTimeMax: o[1] })
                    setQueryList({ ...queryList, dataTimeMin: o[0], dataTimeMax: o[1], pageNum: 1 })
                }}
            />
        </Space> : null}
        >
            <Tabs.TabPane tab="效果数据" key="1">
                <Space direction="vertical" style={{ width: '100%' }}>
                    <Card
                        className="detail_card"
                        hoverable
                    >
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 16px 0' }}>
                            <Space>
                                <strong>趋势</strong>
                                <Select
                                    showSearch
                                    mode='multiple'
                                    maxTagCount={2}
                                    value={queryColumnTrend.trendColumns}
                                    style={{ minWidth: 160 }}
                                    allowClear
                                    placeholder="请选择图表字段"
                                    onChange={(value: string[]) => {
                                        setQueryColumnTrend({ ...queryColumnTrend, trendColumns: value?.length ? value : ['cost'] })
                                    }}
                                    size="small"
                                >
                                    {Object.keys(LineField).map((key) => <Select.Option value={key} key={key}>
                                        {LineField[key]}
                                    </Select.Option>)}
                                </Select>
                            </Space>
                            <Space align="center">
                                <span style={{ fontSize: 10, color: '#999' }}>刷新时间:{getColumnTrendV3?.data?.reqTime}</span>
                                <a onClick={() => getCTList()} style={{ fontSize: 14 }}>刷新</a>
                            </Space>
                        </div>
                        <div style={{ width: '100%', height: 260, textAlign: 'center' }}>
                            {getColumnTrendV3?.loading ? <Spin /> : <LineMonitor style={{ width: '100%', height: 260 }} series smooth data={lineDis} />}
                        </div>
                    </Card>
                    <div className={'MYtable'}>
                        <TableData
                            refreshData={getListList}
                            isZj
                            totalData={totalData}
                            bodyStyle={{ padding: '12px 16px' }}
                            gutter={[0, 12]}
                            columns={columnsList()}
                            dataSource={getListForAdV3?.data?.data?.records?.map((item: any, index: number) => ({ ...item, id: Number(queryList.pageNum.toString() + index.toString()) }))}
                            loading={getListForAdV3?.loading}
                            ajax={getListForAdV3}
                            leftChild={
                                <Space>
                                    <strong>数据报表</strong>
                                </Space>
                            }
                            fixed={{ left: 0, right: 0 }}
                            total={getListForAdV3?.data?.data?.total}
                            onChange={(props: any) => {
                                let { sortData, pagination } = props
                                let { current, pageSize } = pagination
                                let newQueryForm = JSON.parse(JSON.stringify(queryList))
                                newQueryForm.pageNum = current
                                newQueryForm.pageSize = pageSize
                                if (sortData && JSON.stringify('sortData') !== '{}') {
                                    let { order } = sortData   // descend 降序 大到小  ascend 升序 小到大
                                    if (order) {
                                        // newQueryForm.sortColumn = field
                                        newQueryForm.sortAsc = order === 'ascend'
                                    } else {
                                        Object.keys(newQueryForm).forEach(key => {
                                            if (key === 'sortColumn' || key === 'sortAsc') {
                                                delete newQueryForm[key]
                                            }
                                        })
                                    }
                                } else {
                                    Object.keys(newQueryForm).forEach(key => {
                                        if (key === 'sortField' || key === 'sort') {
                                            delete newQueryForm[key]
                                        }
                                    })
                                }
                                setQueryList({ ...newQueryForm })
                            }}
                            page={queryList.pageNum}
                            pageSize={queryList.pageSize}
                            scroll={{ y: 500 }}
                            config={detailsConfig}
                            configName={configName}
                        />
                    </div>
                </Space>
            </Tabs.TabPane>
            <Tabs.TabPane tab="广告详情" key="2">
                <TabAd accountId={account_id} adgroupId={adgroup_id} />
            </Tabs.TabPane>
        </Tabs>
    </Drawer>
}

export default React.memo(Details)