import DatePickePage from '@/components/DatePicker'
import GroupWxTabs from '@/components/GroupWxTabs'
import Tables from '@/components/Tables'
import { quanpin } from '@/utils/fullScreen'
import { CloudDownloadOutlined, FullscreenExitOutlined, FullscreenOutlined, QuestionCircleOutlined, SearchOutlined, SettingOutlined } from '@ant-design/icons'
import { Button, Card, Checkbox, Col, Table, DatePicker, Drawer, Input, InputNumber, Radio, Row, Select, Space, Tag, Tooltip, Transfer, Statistic } from 'antd'
import { SelectValue } from 'antd/es/select'
import { RadioChangeEvent } from 'antd/lib/radio'
import { ColumnsType } from 'antd/lib/table'
import { TransferDirection } from 'antd/lib/transfer'
import { Moment } from 'moment'
import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
import { useModel, history } from 'umi'
import style from './index.less'
import './index1.less'
import Sortable from 'sortablejs'
import { useDebounce } from 'ahooks'
import moment from 'moment'
import arrayMove from "array-move";
import { CheckboxChangeEvent } from 'antd/lib/checkbox'

interface Prosp {
    isTableName?: boolean,//是否开启公众号名称搜索
    sortArr?: { label: string, value: string }[],//排序参数名列表
    isTableId?: boolean,//是否开公众号ID搜索
    isTableDate?: boolean,//是否开启单日期搜索
    isTableDate15?: boolean,//是否开启单日期搜索
    isTableDay?: boolean,//是否开启N天搜索
    isBook?: boolean,//是否开启小说搜索
    isGroup?: boolean,//是否开启切换
    isZj?: boolean,//是否查总计
    isQs?: boolean,//是否开启期数
    isInputName?: boolean, // 是否开启输入框 输入公众号
    isPitcher?: boolean,//默认关闭，关闭下使用左侧组员组件选中的名称，开启后使用input输入筛选
    isAdmin?: boolean, // 是否admin展示 普通员工不展示 与isGroupTab 配合 isGroupTab关闭 isAdmin可打开 
    isCPitcher?: boolean, //是否传Pitcher
    isUserId?: boolean, // 是否传入usid
    isDownload?: boolean,//是否开启下载
    isPlatform?: boolean,//是否开启书城
    isTableDateArr?: boolean,//是否开启双日期搜索
    isTableDateArr15?: boolean,//是否开启双日期搜索
    isDepleteDateArr?: boolean,  // 是否开启消耗时间选择
    isOrderDateArr?: boolean,  // 是否开启订单时间选择
    isTableDateArrSt?: boolean,//是否开启双日期充值时间搜索
    isTableDateOne?: boolean, // 是否开启单日期搜索 [start, end] 相同
    tableTotal?: { [key: string]: string },//是个开启总计
    isLocation?: boolean,//是否开启投放位置
    isType?: boolean,//是否开启投放位置
    scroll?: { x?: number, y?: number },//开启行滑动并设置容器最大宽度
    columns: () => ColumnsType<any>,//table列表配置
    title?: string,//tabel的标题
    subTitle?: JSX.Element | String, // 副标题
    tooltip?: JSX.Element,//是否在标题后加问号展示说明
    dataSource: any[],//table的数据
    expandedRowRender?: (data: any) => JSX.Element,
    ajax: any,//请求
    isTdColor?: boolean,//是否需要开启背景色
    isGroupTab?: boolean,//是否开启组员tab
    className?: string,//自定义class
    isSelctAcc?: boolean, // 是否用data公众号
    isSelctAccTags?: boolean,//公众号多选
    isdownload?: boolean, // 是否下载
    isDataSelectPitcher?: boolean,  // 选择数据服务传回来的投手
    isDataSelectPitcher_isDisabled?: boolean,  // 是否选择公众号 禁用 投手
    isPitcherId?: boolean, // 使用id
    isLoginId?: boolean, // 传登陆ID
    isVideo?: boolean, // 是否判断是视频还是图片
    isCostYear?: boolean, // 是否开启消耗所在年选择
    isOrderMonth?: boolean,  // 是否开启订单所在月份选择
    isShowTotal?: boolean,  // 是否展示总计
    isLastReverse?: boolean,  // 选择年是否倒序
    isHideSort?: boolean,  // 是否隐藏排序
    isPitcherSelf?: boolean,  // 是否包含组员
    defaultSortOrder?: {  // 默认排序
        columnKey: string,
        order: 'descend' | 'ascend' | undefined
    },
    isSummaryHis?: boolean,
}
/**
 * 
 * @param  isTableName boolean是否开启公众号名称搜索
 * @param isTableId boolean,//是否开公众号ID搜索
 * @param isTableDate boolean,//是否开启单日期搜索
 * @param isTableDay  boolean,//是否开启N天搜索
 * @param isBook   boolean,//是否开启小说搜索
 * @param isTableDateArr  boolean,//是否开启双日期搜索
 * @param tableTotal  { [key: string]: string },//是个开启总计
 * @param x  number,//开启行滑动并设置容器最大宽度
 * @param dataSource any[],//table的数据
 * @param columns  () => ColumnsType<any>,//table列表配置
 * @param title  string,//tabel的标题
 * @param tooltip  JSX.Element//是否在标题后加问号展示说明
 * @param ajax  (params: Params) => Promise<any>//请求
 */
const version = '1.0.0'
const Page = forwardRef((props: Prosp, fref) => {
    const { isInputName, isTableName, defaultSortOrder, isSummaryHis, isDataSelectPitcher_isDisabled, isTableDateArr15 = false, isSelctAccTags = false, isHideSort, isLastReverse, isPitcherSelf, isGroup, isShowTotal = true, isTableDateOne, subTitle, isPitcherId, isTableId, isCostYear, isOrderMonth, isTableDate, isTableDate15, isSelctAcc = false, isLoginId = false, isTableDay, isCPitcher = true, isDataSelectPitcher = false, isLocation, isBook, isTableDateArr, isDepleteDateArr, isOrderDateArr, isType, isPitcher = false, isdownload = false, isAdmin = false, isUserId = false, isPlatform, isDownload, isGroupTab = true, tableTotal, isQs, isZj, scroll, columns, title, tooltip, ajax, dataSource, expandedRowRender, sortArr, isTdColor, className, isTableDateArrSt, isVideo } = props
    const { state, dispatch, getAccAjax, getUserAjax, getChannelAnalysisDetails } = useModel('useData.useTableData')
    const { state: userState } = useModel('useOperating.useUser')
    const { currentUser }: any = useModel('@@initialState', model => ({ currentUser: model.initialState?.currentUser }))
    const { state: { groupActionWx } } = useModel('useOperating.useWxGroupList')
    const [size, setSize] = useState<'small' | 'middle' | 'large'>('small')
    const [page, setPage] = useState<number>(1)
    const [pageSize, setPageSize] = useState<number>(100)
    const [total, setTotal] = useState<number>(0)
    const { selectdName, isFell } = userState
    const [visible, setVisible] = useState<boolean>(false)
    const [selectedKeys, setSelectedKeys] = useState<any[]>([])
    const [statistical, setStatistical] = useState<any>({})
    const [fixedNum, setFixedNum] = useState<number | string>(localStorage.getItem(`${title}_${version}fixedNum`) || 1)
    const [targetKeys, setTargetKeys] = useState<any[]>(localStorage?.getItem(`${title}_${version}`) ? JSON.parse(localStorage?.getItem(`${title}_${version}`) as string) : [])
    const { channel, channels, tableDate, date_range, start, end, start15, end15, cost_time_start, cost_time_end, is_pitcher_self, order_time_start, order_time_end, st, et, cost_year, order_month, tableId, book, order_by, order, location, stage, type, platform, pitcher, tableValue = '1', is_video } = state
    const [showZj, setShowZj] = useState<boolean>(false)
    const [value, setValue] = useState<string>('');
    const [searchValue, setSearchValue] = useState<any>([])
    const [detailsDtat, setDetailsData] = useState<any[]>([])//充值详情数据
    const [accNum, setaccNum] = useState<number>(1)  // 多选公众号个数
    const [sortOrder, setSortOrder] = useState<{ columnKey: string, order: 'descend' | 'ascend' | undefined }>(defaultSortOrder || { columnKey: '', order: undefined })
    const [startTime, setStartTime] = useState<string>()
    const [disData, setDisData] = useState<[string, string]>(['', ''])
    const [info, setInfo] = useState<'start' | 'end' | ''>('start')
    const [open, setOpen] = useState<boolean>(false)
    const ref = useRef(null)

    useImperativeHandle(fref, () => ({ tableSubmut }))
    /**点击书名搜索书名 */
    useEffect(() => {
        let bookName = history?.location?.query?.bookName
        if (bookName) {
            dispatch({ type: 'book', params: { book: bookName } })
            tableSubmut({ bookName })
        }
    }, [history.location])
    const handleSearch = useCallback((value: string) => {
        setValue(value)
    }, [value])
    const debouncedValue = useDebounce(value, { wait: 300 });
    useEffect(() => {
        let pitcher_id
        if (pitcher) {
            let pitcherData = searchValue?.find((item: { nick_name: string }) => item.nick_name === pitcher)
            pitcher_id = pitcherData?.user_id
        }
        getAccAjax.run({ user_id: currentUser.userId == 1 ? userState?.selectdUserId : currentUser.userId, name: debouncedValue, pitcher_id })
    }, [debouncedValue, isSelctAcc, userState?.selectdUserId, currentUser.userId, isSelctAccTags, pitcher, searchValue])
    useEffect(() => {
        if (isDataSelectPitcher) {
            getUserAjax.run({ user_id: currentUser.userId == 1 ? userState?.selectdUserId : currentUser.userId }).then((res: any) => {
                setSearchValue(res?.data || [])
            })
        }
    }, [isDataSelectPitcher, userState?.selectdUserId, currentUser.userId])
    /**table搜索事件 */
    const tableSubmut = useCallback(
        (props: {
            pagination?: { current?: number, pageSize?: number, gzh?: string },
            filters?: any,
            sortData?: {
                column: { dataIndex: string },
                order?: "ascend" | "descend",
                columnKey: string
            },
            bookName?: any,
            download?: boolean,
        }) => {
            let { pagination, filters, sortData, bookName, download } = props
            let data = {}
            isDataSelectPitcher && pitcher && (data['pitcher'] = pitcher)
            if (isPitcherId) {
                if (pitcher) {
                    let pitcherData = searchValue?.find((item: { nick_name: string }) => item.nick_name === pitcher)
                    let pitcher_id = pitcherData?.user_id
                    pitcher_id && (data['pitcher_id'] = pitcher_id)
                }
            }
            if (isUserId) {
                if (currentUser.userId === 1) {
                    data['user_id'] = userState.selectdUserId || 1
                } else {
                    data['user_id'] = currentUser.userId || 1
                }
            }
            if (isLoginId) {
                data['user_id'] = currentUser.userId || 1
            }
            !download && (data['page'] = pagination?.current || 1)
            !download && (data['page_size'] = pagination?.pageSize || 100)
            setPageSize(pagination?.pageSize || 100)
            setPage(pagination?.current || 1)
            let gzh = pagination?.gzh || channel //'寒龙书海'||
            isBook && (book || bookName) && (data['book'] = bookName || book)
            isQs && stage && (data['stage'] = stage)
            isPitcherSelf && pitcher && (!channels || channels?.length === 0) && (data['is_pitcher_self'] = !is_pitcher_self)
            isTableName && gzh && (data['channel'] = gzh)
            isInputName && (data['channel'] = channel)
            isSelctAcc && (data['channel'] = channel)
            isSelctAccTags && (data['channel'] = channels)
            isVideo && (data['is_video'] = is_video)
            // data['channel'] = '龙鳞文学'
            isTableId && tableId && (data['state'] = tableId === '2' ? '在投' : '停投')
            isTableDate && tableDate && (data['date'] = tableDate)
            isTableDate15 && tableDate && (data['start'] = tableDate)
            isTableDay && date_range && (data['date_range'] = date_range)
            isTableDateArr && start && (data['start'] = start)
            isTableDateArr && end && (data['end'] = end)
            isTableDateArr15 && start15 && (data['start'] = start15)
            isTableDateArr15 && end15 && (data['end'] = end15)
            isTableDateOne && startTime && (data['start'] = startTime)
            isTableDateOne && startTime && (data['end'] = startTime)
            isDepleteDateArr && cost_time_start && (data['cost_time_start'] = cost_time_start)
            isDepleteDateArr && cost_time_end && (data['cost_time_end'] = cost_time_end)
            isOrderDateArr && order_time_start && (data['order_time_start'] = order_time_start)
            isOrderDateArr && order_time_end && (data['order_time_end'] = order_time_end)
            isCostYear && cost_year && (data['cost_year'] = cost_year)
            isOrderMonth && order_month && (data['order_month'] = order_month)
            isTableDateArrSt && st && (data['st'] = st)
            isTableDateArrSt && et && (data['et'] = et)
            if (!sortData && defaultSortOrder) {
                data['order'] = defaultSortOrder.order === 'ascend' ? 'asc' : 'desc'
                data['order_by'] = defaultSortOrder.columnKey
            }
            sortData?.order && (data['order'] = sortData?.order === 'ascend' ? 'asc' : 'desc');
            sortData?.column?.dataIndex && (data['order_by'] = sortData?.column?.dataIndex)
            if (sortData) { // 返回排序
                setSortOrder({ columnKey: sortData.columnKey, order: sortData?.order })
            } else {
                if (sortOrder) {
                    sortOrder?.order && (data['order'] = sortOrder?.order === 'ascend' ? 'asc' : 'desc');
                    sortOrder?.columnKey && (data['order_by'] = sortOrder?.columnKey)
                }
            }

            if (filters && Object.keys(filters).length > 0) {
                for (const key in filters) {
                    if (Object.prototype.hasOwnProperty.call(filters, key)) {
                        const element = filters[key];
                        element?.forEach((item: any) => {
                            data = { ...data, ...JSON.parse(item) }
                        })
                    }
                }
            }

            isLocation && location && (data['location'] = location)
            isType && type && (data['type'] = type)
            isPlatform && platform && (data['platform'] = platform)
            isDownload && download && (data['download'] = 1)
            if (ajax) {
                ajax.run(data).then((res: any) => {
                    if (isDownload && download) return;
                    if (res?.data) {
                        let dateArr: string[] = []
                        let arr = []
                        if (isTdColor) {
                            arr = res?.data?.map((item: any, index: number) => {
                                item['id'] = (pagination?.current || 1) + index + + Math.random() * 100
                                if (dateArr.indexOf(item.date) !== -1) {//假如日期在dateArr中存在
                                    item['color'] = `color${dateArr.indexOf(item.date)}`//那么颜色等于dateArr的位置
                                } else {//假如不存在dateArr中
                                    dateArr.push(item.date)//向dateArr添加日期以备相同日期对比
                                    item['color'] = `color${dateArr.length - 1}`//颜色的值等于dateArr的长度-1
                                }
                                return item
                            })
                        } else {
                            arr = res?.data?.map((item: any, index: number) => {
                                item['id'] = (pagination?.current || 1) + index + Math.random() * 100
                                return item
                            })
                        }
                        setStatistical(res?.total_data)
                        dispatch({ type: 'dataSource', params: { dataSource: arr } })
                        setTotal(res?.total)
                    } else {
                        setStatistical({})
                        dispatch({ type: 'dataSource', params: { dataSource: [] } })
                    }
                })
            }
        }, [tableDate, isSelctAccTags, is_pitcher_self, sortOrder, defaultSortOrder, startTime, searchValue, channels, cost_year, order_month, cost_time_start, cost_time_end, order_time_start, order_time_end, channel, cost_year, order_month, is_video, start, end, st, et, tableId, book, date_range, selectdName, ajax, order, order_by, isTdColor, location, stage, platform, type])
    /**tableName事件 */
    const tableNameChange = useCallback((value: SelectValue) => {
        dispatch({ type: 'channel', params: { channel: value as string } })
    }, [])
    /**tableBook事件 */
    const tableBookChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        let value = e.target.value
        // setBook(value)
        dispatch({ type: 'book', params: { book: value } })
    }, [])
    /**书城*/
    const platformChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        let value = e.target.value
        // setPlatform(value)
        dispatch({ type: 'setState', params: { platform: value } })
    }, [])
    const platformChangeInput = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        let value = e.target.value
        dispatch({ type: 'setState', params: { platform: value } })
    }, [])
    /**投手名称*/
    const pitcherChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        let value = e.target.value
        // setPitcher(value)
        dispatch({ type: 'setState', params: { pitcher: value } })
    }, [])
    /**tableQs事件 */
    const tableQsChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        let value = e.target.value
        // setStage(value)
        dispatch({ type: 'setState', params: { stage: value } })
    }, [])
    /**table单日期事件 */
    const tableDateChange = useCallback((arr: Moment[], formatString: string | string[]) => {
        // setTableDate(formatString)
        dispatch({ type: 'tableDate', params: { tableDate: formatString as string } })
    }, [])
    /**table双日期事件 */
    const tableDateArrChange = useCallback((arr: Moment[], formatString: string | string[]) => {
        // setStart((formatString as string[])[0])
        // setEnd((formatString as string[])[1])
        dispatch({ type: 'tableDateArr', params: { start: (formatString as string[])[0], end: (formatString as string[])[1] } })
    }, [])
    /**table双日期st事件 */
    const tableDateArrStChange = useCallback((arr: Moment[], formatString: string | string[]) => {
        // setStart((formatString as string[])[0])
        // setEnd((formatString as string[])[1])
        dispatch({ type: 'setState', params: { st: (formatString as string[])[0], et: (formatString as string[])[1] } })
    }, [])
    /**tableDay事件 */
    const tableDayChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        let value = e.target.value
        // setDate_range(value)
        dispatch({ type: 'date_range', params: { date_range: value } })
    }, [])
    /**tableId事件 */
    const tableIdChange = useCallback((value: string) => {
        // setTableId(value)
        dispatch({ type: 'tableId', params: { tableId: value } })
    }, [])
    /**排序选择 */
    const sortChange = useCallback((value: SelectValue) => {
        // setOrder_by(value)
        dispatch({ type: 'setState', params: { order_by: value as string } })
    }, [])
    /**投放位置1 */
    const locationChange = useCallback((value: SelectValue) => {
        // setLocation(value)
        dispatch({ type: 'setState', params: { location: value as 'MP' | 'GDT' } })
    }, [])
    /**投放位置2 */
    const typeChange = useCallback((value: SelectValue) => {
        // setType(value)
        dispatch({ type: 'setState', params: { type: value as 'MP' | 'GDT' } })
    }, [])
    const orderChange = useCallback((value: SelectValue) => {
        // setOrder(value)
        dispatch({ type: 'setState', params: { order: value as 'asc' | 'desc' } })
    }, [])
    /**table字段设置 */
    const handleChange = useCallback((nextTargetKeys: string[], direction: TransferDirection, moveKeys: string[]) => {
        let newTargetKeys = JSON.parse(JSON.stringify(targetKeys))
        if (direction === 'right') { // 加
            newTargetKeys = [...newTargetKeys, ...moveKeys]
        } else { // 减
            newTargetKeys = newTargetKeys?.filter((item: string) => !moveKeys.includes(item))
        }
        setTargetKeys([...newTargetKeys])
    }, [targetKeys])
    const handleSelectChange = useCallback((sourceSelectedKeys: string[], targetSelectedKeys: string[]) => {
        setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys])
    }, [])
    const handleScroll = (direction: TransferDirection, e: React.SyntheticEvent<HTMLUListElement, Event>) => {
        // console.log('direction:', direction);
        // console.log('target:', e.target);
    };
    /**table切换事件 */
    const tableChange = useCallback((e: RadioChangeEvent) => {
        dispatch({ type: 'dataSource', params: { dataSource: [] } })
        let value = e.target.value
        dispatch({ type: 'setState', params: { tableValue: value } })
    }, [])
    /**卸载组件清空数据 */
    useEffect(() => {
        return () => {
            dispatch({ type: 'dataSource', params: { dataSource: [] } })
            // setPitcher('')
            setTargetKeys([])
            // setOrder_by(undefined)
            dispatch({ type: 'setState', params: { order_by: undefined, targetKeys: [] } })
            // setTargetKeys([])
        }
    }, [])
    /**首次加载请求or投手名称变化 */
    useEffect(() => {
        let { channel } = history?.location?.query as any//假如路径中带公众号号名称
        tableSubmut({ pagination: { current: 1, pageSize: 100, gzh: channel, }, download: isdownload })
    }, [selectdName, channel, searchValue])
    /**重组选中的字段 */
    const newColumns = useMemo(() => {
        let arr: any[] = []
        if (targetKeys && targetKeys.length > 0) {
            let column: any[] = columns()
            targetKeys?.forEach((v: string, index: number) => {
                column?.forEach((item: { dataIndex: string, fixed: any }) => {
                    if (item.dataIndex === v) {
                        if (index < fixedNum) {
                            item.fixed = true
                        } else {
                            item.fixed = false
                        }
                        arr.push(item)
                    }
                })
            })
            localStorage.setItem(`${title}_${version}`, JSON.stringify(targetKeys))//保存至本地浏览器
            return arr
        }
        if (isLastReverse) { // 小于今年倒序
            let column: any[] = columns()
            if (cost_year) {
                let year = moment().endOf('year')
                if (moment(cost_year).endOf('year') < year) {
                    arr = column.reverse()
                    let index = column?.findIndex((item: { dataIndex: string }) => item.dataIndex === 'time')
                    if (index !== -1) {
                        arr = arrayMove(arr, index, 0)
                    }
                }
            }
        }
        return arr
    }, [targetKeys, fixedNum, cost_year])
    useEffect(() => {
        if (visible) {
            let ul: any = document.getElementsByClassName('ant-transfer-list-content-show-remove')[0]
            if (ul) {
                new Sortable(ul, {
                    animation: 150,
                    dragClass: style.blue,
                    onEnd: (evt: any) => {
                        let newTargetKeys: any[] = []
                        for (let item of ul?.children) {
                            sortArr?.forEach((arr: any) => {
                                if (item?.title === arr?.title) {
                                    newTargetKeys.push(arr?.key)
                                }
                            })
                        }
                        setTargetKeys(newTargetKeys)
                    }
                });
            }
        }
    }, [visible, targetKeys])
    //获取详情
    const getDetails = useCallback((channel?: string) => {
        let data = { start, end, st, et, channel }
        if (currentUser.userId === 1) {
            data['user_id'] = userState.selectdUserId || 1
        } else {
            data['user_id'] = currentUser.userId || 1
        }
        getChannelAnalysisDetails.run(data).then((res) => {
            setDetailsData(res?.data || [])
        })
    }, [userState, currentUser, start, end, st, et])

    const header = <Col span={24}>
        <Row gutter={[0, 10]}>
            {
                isGroup && <Col span={24}>
                    <Radio.Group onChange={tableChange} value={tableValue}>
                        <Radio.Button value={'1'}>日期汇总</Radio.Button>
                        <Radio.Button value={'2'}>公众号汇总</Radio.Button>
                    </Radio.Group>
                </Col>
            }
            <Col span={24}>
                <Space>
                    {
                        isPitcher && <Input placeholder='请输投手名称' onChange={pitcherChange} allowClear style={{ width: 140 }} value={pitcher} />
                    }
                    {
                        isDataSelectPitcher && <Select
                            style={{ width: 150 }}
                            placeholder='请输投手名称'
                            onChange={(value: any) => { dispatch({ type: 'setState', params: { pitcher: value } }) }}
                            showArrow
                            showSearch
                            disabled={isDataSelectPitcher_isDisabled ? isPitcherSelf ? channels?.length > 0 : channel : false}
                            allowClear
                            value={pitcher || null}
                        >
                            {
                                searchValue?.map((list: any, eq: number) => {
                                    return <Select.Option key={list?.user_id} value={list?.nick_name}>
                                        {list?.nick_name}
                                    </Select.Option>
                                })
                            })
                        </Select>
                    }
                    {
                        isPitcherSelf && pitcher && (!channels || channels?.length === 0) && <Checkbox checked={is_pitcher_self} onChange={(e: CheckboxChangeEvent) => {
                            dispatch({ type: 'isPitcherSelf', params: { is_pitcher_self: e.target.checked } })
                        }}>是否包含组员</Checkbox>
                    }
                    {
                        isBook && <Input placeholder='请输入小说名称' onChange={tableBookChange} allowClear style={{ width: 140 }} value={book} />
                    }
                    {
                        isVideo && <Select
                            style={{ width: 150 }}
                            placeholder="选择类型"
                            onChange={(value: any) => { dispatch({ type: 'isVideo', params: { is_video: value } }) }}
                            showSearch
                            allowClear
                            value={is_video}
                        >
                            <Select.Option value={1}>视频</Select.Option>
                            <Select.Option value={0}>图片</Select.Option>
                        </Select>
                    }
                    {
                        isQs && <Input placeholder='请输入期数名称' onChange={tableQsChange} allowClear style={{ width: 140 }} value={stage} />
                    }
                    {
                        isPlatform && <Input placeholder='请输入书城' onChange={platformChange} allowClear style={{ width: 140 }} value={platform} />
                    }
                    {
                        isTableName && <Select
                            style={{ width: 150 }}
                            placeholder="输入搜索公众号"
                            onChange={(value: any) => { tableNameChange(value) }}
                            showSearch
                            allowClear
                            value={channel}
                        >
                            {
                                groupActionWx?.map((list: any, eq: number) => {
                                    return <Select.Option key={list?.id} value={list?.nickName}>
                                        <img src={list?.headImg || localStorage?.bookImg} className={style.item_img} /> {list?.nickName}
                                    </Select.Option>
                                })
                            })
                        </Select>
                    }
                    {
                        isSelctAcc && <Select
                            style={{ width: 185 }}
                            placeholder="输入搜索公众号"
                            onChange={(value: any) => { tableNameChange(value) }}
                            showSearch
                            allowClear
                            // mode="multiple"
                            defaultActiveFirstOption={false}
                            showArrow={false}
                            filterOption={false}
                            onSearch={handleSearch}
                            value={channel}
                            loading={getAccAjax?.loading}
                            notFoundContent={null}
                        >
                            {
                                getAccAjax?.data?.data?.map((list: any, eq: number) => {
                                    return <Select.Option key={list?.id} value={list?.nick_name}>
                                        {list?.nick_name}
                                    </Select.Option>
                                })
                            })
                        </Select>
                    }
                    {/* 多选公众号 */}
                    {
                        isSelctAccTags && <Select
                            style={{ minWidth: 200 }}
                            placeholder="输入搜索公众号"
                            onChange={(value: any) => { dispatch({ type: 'channels', params: { channels: value } }) }}
                            showSearch
                            allowClear
                            mode="multiple"
                            defaultActiveFirstOption={false}
                            showArrow={false}
                            filterOption={false}
                            onSearch={handleSearch}
                            value={channels}
                            loading={getAccAjax?.loading}
                            notFoundContent={null}
                            tagRender={(props) => {
                                const { label, value, closable, onClose } = props;
                                const onPreventMouseDown = (event: any) => {
                                    event.preventDefault();
                                    event.stopPropagation();
                                };
                                if (accNum === 1 && value) {
                                    if (channels && channels[0] === value) {
                                        return <>
                                            <Tag
                                                color="#F5F5F5"
                                                onMouseDown={onPreventMouseDown}
                                                closable={closable}
                                                onClose={onClose}
                                                className="accTag"
                                                style={{ marginRight: 3 }}
                                            >
                                                {label}
                                            </Tag>
                                            {channels?.length > 1 && <Tag
                                                color="#F5F5F5"
                                                onMouseDown={onPreventMouseDown}
                                                className="accTag"
                                                style={{ marginRight: 3 }}
                                            >
                                                <div style={{ cursor: 'pointer' }} onClick={() => { setaccNum(channels?.length) }}>+ {channels?.length - 1} ...</div>
                                            </Tag>}
                                        </>
                                    } else {
                                        return <></>
                                    }
                                } else {
                                    let length = channels?.length
                                    let lastChannel = channels[length - 1]
                                    return <>
                                        <Tag
                                            color="#F5F5F5"
                                            onMouseDown={onPreventMouseDown}
                                            closable={closable}
                                            onClose={onClose}
                                            className="accTag"
                                            style={{ marginRight: 3 }}
                                        >
                                            {label}
                                        </Tag>
                                        {lastChannel === value && <Tag
                                            color="#1890ff"
                                            onMouseDown={onPreventMouseDown}
                                            className="accTag"
                                            style={{ marginRight: 3 }}
                                        >
                                            <div style={{ cursor: 'pointer', color: '#fff' }} onClick={() => { setaccNum(1) }}>收起</div>
                                        </Tag>}
                                    </>
                                }

                            }}
                        >
                            {
                                getAccAjax?.data?.data?.map((list: any, eq: number) => {
                                    return <Select.Option key={list?.id} value={list?.nick_name}>
                                        {list?.nick_name}
                                    </Select.Option>
                                })
                            })
                        </Select>
                    }
                    {
                        isInputName && <Input onChange={(event: React.ChangeEvent<HTMLInputElement>) => { tableNameChange(event.target.value) }} placeholder='请输入公众号' allowClear />
                    }
                    {
                        isTableId && <Select value={tableId} placeholder='状态' onChange={tableIdChange} allowClear style={{ minWidth: 100 }}>
                            <Select.Option value='1'>停投</Select.Option>
                            <Select.Option value='2'>在投</Select.Option>
                        </Select>
                    }
                    {
                        isLocation && <Select value={location} placeholder='投放位置' onChange={locationChange} allowClear style={{ minWidth: 100 }}>
                            <Select.Option value='MP'>MP</Select.Option>
                            <Select.Option value='GDT'>GDT</Select.Option>
                            <Select.Option value='BYTEDANCE'>BYTEDANCE</Select.Option>
                        </Select>
                    }
                    {
                        isType && <Select value={type} placeholder='投放位置' onChange={typeChange} allowClear style={{ minWidth: 100 }}>
                            <Select.Option value='MP'>MP</Select.Option>
                            <Select.Option value='GDT'>GDT</Select.Option>
                            <Select.Option value='BYTEDANCE'>BYTEDANCE</Select.Option>
                        </Select>
                    }
                    {
                        isTableDate || isTableDate15 && <DatePickePage model='DatePicker' DatePickerChange={tableDateChange} allowClear date={tableDate} />
                    }
                    {
                        isTableDateArr && <DatePickePage model='RangePicker' DatePickerChange={tableDateArrChange} allowClear date={start ? [start, end] : undefined} />
                    }
                    {
                        isTableDateArr15 && <DatePicker.RangePicker onOpenChange={(open) => { setOpen(open); if (!open) { setDisData(['', '']); setInfo('') } }} onCalendarChange={(dates: any, dateStrings: [string, string], info: { range: 'start' | 'end' }) => { setDisData(dateStrings); setInfo(info.range) }} disabledDate={(current: any) => {
                            if (info === 'start' && disData[0]) {
                                return moment(disData[0]).startOf('day') > current || current > moment(disData[0]).add(10, 'days') || current > moment().endOf('day');
                            } else if (info === 'end' && disData[1]) {
                                return current < moment(disData[1]).subtract(10, 'days');
                            } else {
                                return current && current > moment().endOf('day');
                            }
                        }} onChange={(mo: any, str: any) => {
                            dispatch({ type: 'tableDateArr15', params: { start15: (str as string[])[0], end15: (str as string[])[1] } })
                        }} value={!open ? start15 ? [moment(start15), moment(end15)] : undefined : undefined} />
                    }
                    {
                        isTableDateOne && <DatePickePage model='DatePicker' DatePickerChange={(arr: Moment[], formatString: string | string[]) => { setStartTime(formatString as string) }} allowClear date={startTime} />
                    }
                    {
                        isDepleteDateArr && <DatePickePage model='RangePicker' placeholder={['消耗开始时间', '消耗结束时间']} DatePickerChange={(arr: Moment[], formatString: string | string[]) => { dispatch({ type: 'depleteDateDateArr', params: { start: (formatString as string[])[0], end: (formatString as string[])[1] } }) }} allowClear date={cost_time_start ? [cost_time_start, cost_time_end] : undefined} />
                    }
                    {
                        isOrderDateArr && <DatePicker.RangePicker disabledDate={(current: any) => {
                            if (cost_time_start && cost_time_end && current) { // 设置了消耗时间就要控制在消耗时间内
                                return moment(cost_time_start).startOf('day') > current || current && current > moment().endOf('day');
                            } else {
                                return current && current > moment().endOf('day');
                            }
                        }} placeholder={['订单开始时间', '订单结束时间']} onChange={(mo: any, str: any) => { dispatch({ type: 'orderDateDateArr', params: { start: (str as string[])[0], end: (str as string[])[1] } }) }} value={order_time_start ? [moment(order_time_start), moment(order_time_end)] : undefined} />
                    }
                    {
                        isTableDateArrSt && <DatePickePage model='RangePicker' DatePickerChange={tableDateArrStChange} allowClear date={st ? [st, et] : undefined} placeholder={['充值开始时间', '充值结束时间']} />
                    }
                    {/* 年选择 */}
                    {
                        isCostYear && <DatePicker disabledDate={(current: any) => {
                            return current && current > moment().endOf('year');
                        }} onChange={(value: Moment | null, dateString: string) => { dispatch({ type: 'costYear', params: { cost_year: dateString } }) }} picker="year" placeholder='请选择消耗年份' value={cost_year ? moment(cost_year) : null} />
                    }
                    {/* 月选择 */}
                    {
                        isOrderMonth && <DatePicker placeholder='请选择充值月份' disabledDate={(current: any) => {
                            // 选择了年 限制月选择
                            if (cost_year && current) {
                                return moment(cost_year).startOf('year') > current || current && current > moment().endOf('month');
                            } else {
                                return current && current > moment().endOf('month');
                            }
                        }} onChange={(value: Moment | null, dateString: string) => { dispatch({ type: 'orderMonth', params: { order_month: dateString } }) }} picker="month" value={order_month ? moment(order_month) : null} />
                    }
                    {
                        isTableDay && <Input
                            style={{ width: 120 }}
                            value={date_range}
                            onChange={tableDayChange}
                            allowClear
                            placeholder='过去N天'
                        >
                        </Input>
                    }
                    <Button type='primary' onClick={() => tableSubmut({})}><SearchOutlined />搜索</Button>
                    {isDownload && <Button type='primary' onClick={() => tableSubmut({ download: true })}><CloudDownloadOutlined />下载EXCEL</Button>}
                </Space>
                {/*紧凑*/}
                <Space style={{ float: 'right' }}>
                    {!isHideSort && <Button
                        size='small'
                        type='text'
                        onClick={() => {
                            setVisible(true)
                        }}>
                        <SettingOutlined />
                    </Button>}
                    <Button
                        type='text'
                        size='small'
                        onClick={() => {
                            if (ref?.current) {
                                quanpin(ref?.current)
                            }
                        }}>
                        {
                            <Tooltip title={!isFell ? '全屏' : '退出全屏'}>{!isFell ? <FullscreenOutlined /> : <FullscreenExitOutlined />}</Tooltip>
                        }
                    </Button>
                    <Drawer
                        title="table字段设置"
                        width={420}
                        visible={visible}
                        getContainer={ref?.current || false}
                        onClose={() => {
                            setVisible(false)
                        }}
                    >
                        <div>
                            <span>请输入固定列数值：</span>
                            <InputNumber
                                size="small"
                                min={1}
                                max={100000}
                                onChange={(v) => {
                                    setFixedNum(v as number)
                                    localStorage.setItem(`${title}_${version}fixedNum`, `${v}`)
                                }}
                                value={fixedNum}
                                style={{ marginBottom: 10 }}
                                placeholder='请输入固定列数值'
                            />
                        </div>
                        <Transfer
                            dataSource={sortArr || []}
                            titles={['不展示', '展示']}
                            showSearch
                            targetKeys={targetKeys || []}
                            selectedKeys={selectedKeys || []}
                            onChange={handleChange}
                            onSelectChange={handleSelectChange}
                            onScroll={handleScroll}
                            render={(item: any) => item?.title}
                            oneWay
                            style={{ marginBottom: 16 }}
                            listStyle={{
                                height: 'calc(100vh - 140px)',
                            }}
                        />
                    </Drawer>
                </Space>
            </Col>
        </Row>
    </Col>
    const content = <Row gutter={[0, 20]} ref={ref} style={isFell ? { background: '#fff' } : {}}>
        {/**table */}
        <Col span={24}>
            <Card
                hoverable
                title={
                    <Space direction='vertical'>
                        <Space>
                            {isGroupTab ? selectdName + '--' + title : (isAdmin && currentUser.userId === 1) ? selectdName + '--' + title : title}
                            {
                                tooltip && <Tooltip
                                    title={tooltip}>
                                    <QuestionCircleOutlined style={{ color: 'red' }} />
                                </Tooltip>
                            }
                        </Space>
                        {subTitle && subTitle}
                    </Space>
                }
                headStyle={{ textAlign: 'center' }}
            >
                <Row gutter={[0, 20]}>
                    {header}
                    <Tab {...{ size, className, isZj, newColumns, isShowTotal, columns, sortOrder, isSummaryHis, statistical, dispatch, scroll, isFell, showZj, page, pageSize, dataSource, tableSubmut, expandedRowRender, total, ajax, getDetails, detailsDtat }} />
                </Row>
            </Card>
        </Col>
    </Row >
    return <>
        {
            isGroupTab ? <GroupWxTabs height='calc(100vh - 180px)'>
                {content}
            </GroupWxTabs > : (isAdmin && currentUser.userId === 1) ? <GroupWxTabs height='calc(100vh - 180px)'>
                {content}
            </GroupWxTabs> : content
        }
    </>
})

/**表格 */
const Tab = React.memo((props: any) => {
    const { size, getDetails, detailsDtat, className, isZj, isShowTotal = true, dispatch, newColumns, isSummaryHis, sortOrder, columns, statistical, scroll, isFell, showZj, page, pageSize, dataSource, tableSubmut, expandedRowRender, total, ajax } = props

    return < Col span={24} >
        <div className={`${style[size]} ${className ? style[className] : ''} `}>
            {
                isZj && <Tables
                    bordered
                    columns={newColumns?.length > 0 ? newColumns : columns({ getDetails, data: detailsDtat, sortOrder, dispatch })}
                    dataSource={[{ ...statistical, id: 1 }]}
                    scroll={scroll ? isFell ? { ...scroll, y: document.body.clientHeight - 300 } : scroll : {}}
                    size={size}
                    pagination={false}
                    hideOnSinglePage
                    className={`all_table ${className ? className : ''}`}
                />
            }
            <Tables
                className={`all_table ${className ? className : ''}`}
                bordered
                current={showZj ? 1 : page}
                pageSize={pageSize}
                columns={newColumns?.length > 0 ? newColumns : columns({ getDetails, data: detailsDtat, sortOrder, dispatch })}
                dataSource={showZj ? [{ ...statistical, id: 1 }] : dataSource}
                scroll={scroll ? isFell ? { ...scroll, y: document.body.clientHeight - 300 } : scroll : {}}
                onChange={(pagination: any, filters: any, sorter: any) => tableSubmut({ pagination, filters, sortData: sorter })}
                rowClassName={(record: { color: string }) => style[record['color']]}
                expandedRowRender={expandedRowRender ? expandedRowRender : undefined}
                size={size}
                isShowTotal={isShowTotal}
                total={showZj ? 1 : total}
                loading={ajax?.loading}
                defaultPageSize={100}
                summary={pageData => {
                    if (isSummaryHis) {
                        return <Table.Summary fixed>
                            <Table.Summary.Row>
                                <Table.Summary.Cell index={0}><div style={{ fontSize: 18, fontWeight: 600, textAlign: 'center' }}>总计</div></Table.Summary.Cell>
                                <Table.Summary.Cell index={1}><div style={{ fontWeight: 600, textAlign: 'center', color: '#000000d9' }}>消耗</div></Table.Summary.Cell>
                                <Table.Summary.Cell index={2}><div style={{ textAlign: 'center' }}>{Object.keys(statistical)?.length > 0 ? <Statistic value={statistical?.cost ? (statistical?.cost as number).toFixed(2) : statistical?.cost === 0 ? 0 : '--'} /> : '--'}</div> </Table.Summary.Cell>
                                <Table.Summary.Cell index={3}><div style={{ fontWeight: 600, textAlign: 'center', color: '#000000d9' }}>充值</div></Table.Summary.Cell>
                                <Table.Summary.Cell index={4}><div style={{ textAlign: 'center' }}>{Object.keys(statistical)?.length > 0 ? <Statistic value={statistical?.amount ? (statistical?.amount as number).toFixed(2) : statistical?.amount === 0 ? 0 : '--'} /> : '--'}</div></Table.Summary.Cell>
                                <Table.Summary.Cell index={5}><div style={{ fontWeight: 600, textAlign: 'center', color: '#000000d9' }}>回收率</div></Table.Summary.Cell>
                                <Table.Summary.Cell index={6}><div style={{ textAlign: 'center' }}>{Object.keys(statistical)?.length > 0 && statistical?.roi ? <div style={statistical?.roi >= 0.5 ? { color: '#0f990f' } : { color: 'red' }}>{(statistical?.roi * 100).toFixed(2) + '%'}</div> : '--'}</div></Table.Summary.Cell>
                            </Table.Summary.Row>
                        </Table.Summary>
                    }
                    return null
                }}
            />
        </div>
    </Col >
}, (a, b) => {
    if (JSON.stringify(a) === JSON.stringify(b)) {
        return true
    } else {
        return false
    }
})
export default Page
