import GroupWxTabs from '@/components/GroupWxTabs'
import { columns } from './tableConfig'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { useModel } from 'umi'
import { AdProfit } from '@/services/operating/adCensus'
import { Button, Card, Col, DatePicker, Row, Select, Space, Table, Tag, Tooltip } from 'antd'
import './index.less'
import moment from 'moment'
import { quanpin } from '@/utils/fullScreen'
import { FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons'

function DataCensus() {

    const { getAdProfit, getxcxAll } = useModel('useOperating.useAdCensus')
    const { state: userState } = useModel('useOperating.useUser')
    const { getWxGroupAll, state, getAllOfMember } = useModel('useOperating.useWxGroupList', model => ({ getWxGroupAll: model.getDataList, ...model }))

    const [xcxData, setxcxData] = useState<{ appId: string, appName: string, type: number }[]>([])  // 保存所有小程序信息
    const [queryForm, setQueryForm] = useState<AdProfit>({ page: 1, size: 20 })
    const [accData, setAccData] = useState<any[]>([])
    const { isFell } = userState
    const ref = useRef(null)

    // 获取小程序列表
    useEffect(() => {
        getxcxAll.run().then((res: any) => {
            setxcxData(res?.data)
        })
    }, [])

    // 获取表格列表
    useEffect(() => {
        if (queryForm?.userId) {
            let newQueryForm: any = {}
            let { appId, startTime, endTime, userId, page, size, mpName, type } = queryForm
            appId && (newQueryForm['appId'] = appId)
            startTime && (newQueryForm['startTime'] = startTime)
            endTime && (newQueryForm['endTime'] = endTime)
            userId && (newQueryForm['userId'] = userId)
            page && (newQueryForm['page'] = page)
            size && (newQueryForm['size'] = size)
            mpName && (newQueryForm['mpName'] = mpName)
            type && (newQueryForm['type'] = type)
            getAdProfit.run({ ...newQueryForm })
        }
    }, [queryForm])

    // 选中人员id变动
    useEffect(() => {
        setQueryForm(() => ({ ...queryForm, page: 1, userId: userState?.selectdUserId }))
    }, [userState?.selectdUserId])

    /** 表格分页onChange */
    const paginationOnChange = (page: number, pageSize?: number | undefined) => {
        setQueryForm({ ...queryForm, page, size: pageSize || 20 })
    }

    // 开始日期不可选择日期
    const disabledStartDate = useCallback((current: any) => {
        if (queryForm?.endTime) {
            return current && current > moment(queryForm?.endTime)
        }
    }, [queryForm?.endTime])
    // 结束日期不可选择日期
    const disabledEndDate = useCallback((current: any) => {
        if (queryForm?.startTime) {
            return current && current < moment(queryForm?.startTime)
        }
    }, [queryForm?.startTime])

    useEffect(() => {
        if (state?.tabsKey === '自己') {
            let newAccData: any[] = []
            getWxGroupAll?.data?.forEach((item: { mpAccounts: any[] }) => {
                if (item?.mpAccounts?.length > 0) {
                    newAccData = [...newAccData, ...item?.mpAccounts]
                }
            })
            setAccData(() => newAccData)
        } else {
            let newAccData = getAllOfMember?.data?.find((item: any) => item?.key?.userId === Number(userState?.selectdUserId))
            if (newAccData) {
                setAccData(() => newAccData?.value)
            } else {
                setAccData(() => [])
            }
        }
    }, [userState?.selectdUserId, getWxGroupAll?.data, state?.tabsKey, getAllOfMember?.data])

    return <div className="dataCensus">
        <GroupWxTabs height='calc(100vh - 180px)' allowClear={false}>
            <Row gutter={[0, 20]} ref={ref} style={isFell ? { background: '#fff' } : {}}>
                <Col span={24}>
                    <Card
                        hoverable
                        title={"小程序广告数据"}
                        headStyle={{ textAlign: 'center' }}
                    >
                        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                            <Space wrap style={{ marginBottom: 10 }}>
                                <Select style={{ width: 180 }} showSearch value={queryForm?.appId} onChange={(e) => { setQueryForm({ ...queryForm, appId: e, page: 1 }) }} placeholder="请选择小程序" allowClear>
                                    {xcxData?.map((item: { appId: string, appName: string, type: number }, index: number) => <Select.Option value={item.appId} key={index}>{item.appName}</Select.Option>)}
                                </Select>
                                <Select style={{ width: 180 }} value={queryForm?.type} onChange={(e) => { setQueryForm({ ...queryForm, type: e, page: 1 }) }} placeholder="请选择类型" allowClear>
                                    <Select.Option value={1} >运营</Select.Option>
                                    <Select.Option value={2} >投手</Select.Option>
                                </Select>
                                <DatePicker
                                    onChange={(e: moment.Moment | null) => { setQueryForm({ ...queryForm, startTime: e ? moment(e).format('YYYY-MM-DD') : "", page: 1 }) }}
                                    value={queryForm?.startTime ? moment(queryForm?.startTime) : null}
                                    placeholder="请选择开始日期"
                                    disabledDate={disabledStartDate}
                                />
                                <DatePicker
                                    onChange={(e: moment.Moment | null) => { setQueryForm({ ...queryForm, endTime: e ? moment(e).format('YYYY-MM-DD') : "", page: 1 }) }}
                                    value={queryForm?.endTime ? moment(queryForm?.endTime) : null}
                                    placeholder="请选择结束日期"
                                    disabledDate={disabledEndDate}
                                />
                                <Select
                                    style={{ width: 185 }}
                                    placeholder="请选择公众号"
                                    onChange={(value: any) => { setQueryForm({ ...queryForm, mpName: value, page: 1 }) }}
                                    allowClear
                                    showSearch
                                >
                                    {
                                        accData?.map((list: any, eq: number) => {
                                            return <Select.Option key={list?.id} value={list?.nickName}>
                                                {list?.nickName}
                                            </Select.Option>
                                        })
                                    })
                                </Select>
                                <Button type="primary" onClick={() => { getAdProfit.refresh() }}>查询</Button>
                            </Space>
                            <Button
                                type='text'
                                size='small'
                                onClick={() => {
                                    if (ref?.current) {
                                        quanpin(ref?.current)
                                    }
                                }}>
                                {
                                    <Tooltip title={!isFell ? '全屏' : '退出全屏'}>{!isFell ? <FullscreenOutlined /> : <FullscreenExitOutlined />}</Tooltip>
                                }
                            </Button>
                        </div>


                        <Table
                            size="small"
                            loading={getAdProfit.loading}
                            dataSource={getAdProfit?.data?.data?.bannerMpIncomeDtoList}
                            columns={columns()}
                            bordered
                            scroll={{ x: 1100 }}
                            rowKey={(record) => { return record?.id }}
                            pagination={{
                                current: queryForm.page,
                                pageSize: queryForm.size,
                                total: getAdProfit?.data?.data?.totalCount,
                                showSizeChanger: true,
                                pageSizeOptions: ['10', '20', '50', '70', '100'],
                                showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                                onChange: paginationOnChange
                            }}
                            summary={() => {
                                return (
                                    <Table.Summary.Row style={{ backgroundColor: '#fafafa' }}>
                                        <Table.Summary.Cell index={0}>
                                            <div style={{ textAlign: 'right', fontWeight: 600, marginRight: 30, fontSize: 14 }}>合计总收入</div>
                                        </Table.Summary.Cell>
                                        <Table.Summary.Cell index={0} colSpan={4}>
                                            <div></div>
                                        </Table.Summary.Cell>
                                        <Table.Summary.Cell index={1} >
                                            <div style={{ fontSize: 18, color: 'rgb(0 14 183', textAlign: 'center', fontWeight: 600 }}>{getAdProfit?.data?.data?.totalPv || 0.00}</div>
                                        </Table.Summary.Cell>
                                        <Table.Summary.Cell index={1} >
                                            <div style={{ fontSize: 18, color: 'rgb(0 14 183', textAlign: 'center', fontWeight: 600 }}>{getAdProfit?.data?.data?.totalNewUserCount || 0.00}</div>
                                        </Table.Summary.Cell>
                                        <Table.Summary.Cell index={1} >
                                            <div style={{ fontSize: 18, color: 'rgb(0 14 183', textAlign: 'center', fontWeight: 600 }}>{getAdProfit?.data?.data?.totalOldUserCount || 0.00}</div>
                                        </Table.Summary.Cell>
                                        <Table.Summary.Cell index={1} >
                                            <div style={{ fontSize: 18, color: 'rgb(0 14 183', textAlign: 'center', fontWeight: 600 }}>{getAdProfit?.data?.data?.totalUv || 0.00}</div>
                                        </Table.Summary.Cell>
                                        <Table.Summary.Cell index={1} >
                                            <div style={{ fontSize: 18, color: 'rgb(0 14 183', textAlign: 'center', fontWeight: 600 }}>{getAdProfit?.data?.data?.avgArpu || 0.00}</div>
                                        </Table.Summary.Cell>
                                        <Table.Summary.Cell index={1} >
                                            <div style={{ fontSize: 18, color: 'rgb(0 14 183', textAlign: 'center', fontWeight: 600 }}>{getAdProfit?.data?.data?.totalIncome || 0.00}</div>
                                        </Table.Summary.Cell>
                                    </Table.Summary.Row>
                                );
                            }}
                        />
                    </Card>
                </Col>
            </Row >
        </GroupWxTabs>
    </div>
}

export default React.memo(DataCensus)