import CustomListModel from '@/components/CustomList'
import Tables from '@/components/Tables'
import { quanpin } from '@/utils/fullScreen'
import { FullscreenExitOutlined, FullscreenOutlined, RedoOutlined, SettingOutlined } from '@ant-design/icons'
import { Button, Card, Col, Row, Space, Spin, Tooltip, } from 'antd'
import { ColumnsType } from 'antd/lib/table'
import React, { useEffect, useRef, useState, useCallback } from 'react'
import { useModel } from 'umi'
import style from './index.less'
interface Prosp {
    // sortArr?: { label: string, value: string ,key:any}[],//排序参数名列表
    isZj?: boolean,//是否查总计
    tableTotal?: { [key: string]: string },//是个开启总计
    scroll?: { x?: number, y?: number },//开启行滑动并设置容器最大宽度
    columns: () => ColumnsType<any>,//table列表配置
    title?: string,//tabel的标题
    tooltip?: JSX.Element,//是否在标题后加问号展示说明
    dataSource: any[],//table的数据
    expandedRowRender?: (data: any) => JSX.Element,
    className?: string,//自定义class
    isdownload?: boolean,
    leftChild?: JSX.Element,
    config?: any,
    configName?: any,
    page?: number,
    pageSize?: number,
    size?: 'small' | 'middle' | 'large',
    total?: number,
    loading?: boolean,
    onChange?: (props: {
        pagination?: { current?: number, pageSize?: number, gzh?: string },
        filters?: any,
        sortData?: {
            column: { dataIndex: string },
            order?: "ascend" | "descend"
        }
    }) => void,
    ajax?: any,//接口刷新
}

function TableData(props: Prosp) {
    const { isZj, scroll, columns, title, dataSource, expandedRowRender, className, leftChild, page = undefined, pageSize = undefined, size = 'small', total = 0, loading = false, onChange, config, configName, ajax } = props
    const { state: userState } = useModel('useOperating.useUser')
    const { isFell } = userState
    const [visible, setVisible] = useState<boolean>(false)
    const [oldSelectData, setoldSelectData] = useState<any[]>([])
    const [oldFixed, setoldFixed] = useState<any>({ left: '0', right: '0' })
    const [newColumns, setNewColumns] = useState<any[]>([])
    // const [oldConfigName, setOldConfigName] = useState<any>('')//上次的配置名称
    const [selectData, setSelectData] = useState<{ selectData: any[], fixed: { left: string, right: string } }>({ selectData: [], fixed: { left: '0', right: '0' } })
    const ref = useRef(null)
    const oldName = useRef(null)
    const version = '1.0.0'
    // // /**重组选中的字段 */
    useEffect(() => {
        let oldConfigName = oldName.current || ''
        if (configName) {
        // if (dataSource?.length > 0) {
            const defSelectData = localStorage.getItem(`myAdMonitorConfig${version}_` + configName)
            const defFixed = localStorage.getItem(`myAdMonitorConfigFixed${version}_` + configName)
            const newConfig = config?.map((item: { data: any }) => item.data)?.flat()
            if (defSelectData && (selectData?.selectData?.length === 0 || configName !== oldConfigName)) {//首次查找个人配置是否存在，并且selectData为空，存在用个人配置设置selectData
                console.log('首次使用个人配置赋值')
                let newDefSelectData = JSON.parse(defSelectData)
                newDefSelectData = newDefSelectData.filter((item: any) => !!item && newConfig.some((c: { dataIndex: any }) => c.dataIndex === item.dataIndex))//去除空项
                setSelectData(() => ({ selectData: newDefSelectData, fixed: defFixed ? JSON.parse(defFixed) : { left: '0', right: '0' } }))
            }
            if (!defSelectData && (selectData?.selectData?.length === 0 || configName !== oldConfigName)) {//首次查找个人配置是否存在，并且selectData为空，不存在默认配置设置selectData
                let newSelectData: any[] = []
                config?.forEach((item: { data: { default: any }[] }) => {
                    item?.data?.forEach((d: { default: any }) => {
                        if (d.default) {
                            newSelectData[d.default - 1] = d
                        }
                    })
                })
                console.log('首次使用默认配置赋值')
                setSelectData(() => ({ selectData: newSelectData, fixed: { left: '0', right: configName.includes('起量') ? '2' : '0' } }))
            }
            if ((JSON.stringify(oldSelectData) !== JSON.stringify(selectData?.selectData)) || (JSON.stringify(selectData.fixed) !== JSON.stringify(oldFixed))) {
                console.log('设置配置改变重新赋值')
                setoldSelectData(() => selectData.selectData)
                setoldFixed(() => selectData.fixed)
                let newArr: any = []
                selectData?.selectData?.forEach((data: { dataIndex: any, width: number }, index: number) => {
                    columns()?.forEach((item: any) => {
                        if (data.dataIndex === item.dataIndex) {
                            if (index < Number(selectData?.fixed?.left)) {//设置左悬浮
                                item['fixed'] = 'left'
                            } else if (index > (selectData?.selectData?.length - Number(selectData?.fixed?.right) - 1)) {//设置右悬浮
                                item['fixed'] = 'right'
                            } else {
                                item['fixed'] = false
                            }
                            if (data?.width) {
                                item['width'] = data.width
                            }
                            newArr.push(item)
                        }
                    })
                })
                setNewColumns(() => newArr)
            }
        }
        if (configName !== oldConfigName) {
            oldName.current = configName
        }
    }, [selectData, oldSelectData, dataSource, oldFixed, configName, config, columns]) // selectData, oldSelectData, dataSource, oldFixed, configName, oldConfigName, config, columns
    //拖动宽度设置设置保存
    const handelResize = useCallback((columns: any) => {
        if (configName) {
            let newSelectData = selectData?.selectData?.map((item, index) => {
                item['width'] = columns[index]['width']
                return item
            })
            localStorage.setItem(`myAdMonitorConfig${version}_` + configName, JSON.stringify(newSelectData))
        }
    }, [configName, selectData])
    const header = <Col span={24}>
        <Row gutter={[0, 10]}>
            <Col span={24}>
                <Space>
                    {leftChild}
                </Space>
                {/*紧凑*/}
                <Space style={{ float: 'right' }}>
                    {
                        ajax && <Button
                            size='small'
                            type='text'
                            onClick={() => {
                                ajax.refresh()
                            }}>
                            <span style={{ fontSize: 10, color: '#999' }}>刷新时间:{ajax?.data?.reqTime}</span>
                            <Tooltip title='刷新'><RedoOutlined /></Tooltip>
                        </Button>
                    }
                    <Button
                        size='small'
                        type='text'
                        onClick={() => {
                            setVisible(true)
                        }}>
                        <Tooltip title='设置'><SettingOutlined /></Tooltip>
                    </Button>
                    <Button
                        type='text'
                        size='small'
                        onClick={() => {
                            if (ref?.current) {
                                quanpin(ref?.current)
                            }
                        }}>
                        {
                            <Tooltip title={!isFell ? '全屏' : '退出全屏'}>{!isFell ? <FullscreenOutlined /> : <FullscreenExitOutlined />}</Tooltip>
                        }
                    </Button>
                    {visible && <CustomListModel  version={version} config={config} configName={configName} visible={visible} onClose={() => { setVisible(false) }} onChange={(arr: any) => { setSelectData(arr) }} columns={newColumns?.length > 0 ? newColumns : columns()} />}
                </Space>
            </Col>
        </Row>
    </Col>
    const content = <Row gutter={[0, 20]} ref={ref} style={isFell ? { background: '#fff' } : {}}>
        {/**table */}
        <Col span={24}>
            <Card
                hoverable
                title={title}
                headStyle={{ textAlign: 'left' }}
            >
                <Row gutter={[0, 20]}>
                    {header}
                    <Tab {...{ size, newColumns, handelResize, className, isZj, columns, loading, scroll, isFell, page, pageSize, dataSource, onChange, expandedRowRender, total, ajax }} />
                </Row>
            </Card>
        </Col>
    </Row >
    return <>
        {content}
    </>
}

/**表格 */
const Tab = React.memo((props: any) => {
    const { size, newColumns, className, handelResize, columns, scroll, loading, isFell, page, pageSize, dataSource, onChange, expandedRowRender, total, ajax } = props
    return < Col span={24} >
        <div className={`${style[size]} ${className ? style[className] : ''} `}>
            {dataSource || !ajax?.loading ? <Tables
                className={`all_table ${className ? className : ''}`}
                bordered
                sortDirections={['ascend', 'descend', null]}
                current={page}
                pageSize={pageSize}
                columns={newColumns?.length > 0 ? newColumns : columns()}
                dataSource={dataSource}
                scroll={scroll ? isFell ? { ...scroll, y: document.body.clientHeight - 300 } : scroll : {}}
                onChange={(pagination: any, filters: any, sorter: any) => onChange && onChange({ pagination, filters, sortData: sorter })}
                rowClassName={(record: { color: string }) => style[record['color']]}
                expandedRowRender={expandedRowRender ? expandedRowRender : undefined}
                size={size}
                total={total}
                loading={loading}
                defaultPageSize={20}
                handelResize={((columns: any) => handelResize(columns))}
            /> : <div className={style.example}>
                <Spin />
            </div>}
        </div>
    </Col >
})
export default React.memo(TableData)
