import { QuestionCircleOutlined } from "@ant-design/icons";
import { useFullscreen, useLocalStorageState, useMount, useSetState } from "ahooks";
import { Card, Col, Row, Space, Tooltip } from "antd";
import React, { useRef, useState } from "react"
import style from './index.less'
import Settings from "../Settings";

const log = (text?: any, key?: string) => {
    console.log(`pro_${key || ''}----->`, text)
}
export const DispatchContext = React.createContext<PROAPI.TableContentProps | null>(null);
export const DispatchHeader = React.createContext<PROAPI.HeaderContentProps | null>(null);
export const version = '1.0.0'
/**
 * 升级版表格
 * @returns 
 */
const TablePro: React.FC<PROAPI.TableProProps> = ({
    configName,
    config,
    fixed = { left: 0, right: 0 },
    title,
    tips,
    ajax,
    czChild,
    leftChild,
    size = 'small',
    className,
    total
}) => {

    /*********************************************/
    const [lsDataSource, setLsDataSource] = useLocalStorageState(`myAdMonitorConfig${version}_` + configName);
    const [lsFixed, setLsFixed] = useLocalStorageState<{ left: 0, right: 0 }>(`myAdMonitorConfigFixed${version}_` + configName);
    const [state, setState] = useSetState<PROAPI.State>({
        // 所有配置用key转Object
        configObj: {},
        columns: [],
        // 默认配置
        defaultColumns: []
    });
    const ref = useRef(null)
    const [isFull, { toggleFull }] = useFullscreen(ref);
    const [isFullscreen, setIsFullscreen] = useState<boolean>(true);
    const [visible, setVisible] = useState<boolean>(false)
    // const { configObj, columns, defaultColumns } = state
    /*********************************************/

    // 首次渲染
    useMount(() => {
        log('----mount-----')
        handleConfig()
    });

    /**
     * 处理config成对象 减少后期轮询
     * 拿到默认Columns
     */
    const handleConfig = () => {
        // log(config)
        let newColumns: any[] = []
        let newConfigObj: { [key: string]: any; } = {}
        config?.forEach((item: { data: { default: any; dataIndex: string }[] }) => {
            item?.data?.forEach((d: { default: any, dataIndex: string }) => {
                newConfigObj[d.dataIndex] = d
                if (d.default) {
                    newColumns[d.default - 1] = d
                }
            })
        })
        setState({ defaultColumns: newColumns, configObj: newConfigObj })
        handleColumns(newColumns, newConfigObj)
    }


    // 处理columns
    const handleColumns = (defaultColumns: any[], configObj: { [key: string]: string; }) => {
        log(defaultColumns, 'defaultColumns')
        log(configObj, 'configObj')
        // 使用默认配置
        let newColumns = defaultColumns
        let newFixed = fixed
        log(lsFixed, 'lsFixed')
        if (lsFixed) {
            newFixed = lsFixed
        }
        if (lsDataSource) { // 找到了设置的配置

        }
        newColumns = newColumns.map(item => ({ ...item, key: item.dataIndex }))
        if (newFixed.left && newFixed.right) {
            for (let i = 0; i < Math.min(newFixed.left, newColumns.length); i++) {
                newColumns[i] = { ...newColumns[i], fixed: 'left' };
            }
            const arrayLength = newColumns.length;
            for (let i = Math.max(0, arrayLength - newFixed.right); i < arrayLength; i++) {
                newColumns[i] = { ...newColumns[i], fixed: 'right' };
            }
        }
        log(newColumns, 'newColumns')
        setState({ columns: newColumns })
    }


    return <Row gutter={[0, 20]} ref={ref} style={isFull ? { background: '#fff' } : {}}>
        <Col span={24}>
            <Card
                style={{ borderRadius: 8 }}
                headStyle={{ textAlign: 'left' }}
                bodyStyle={{ padding: '5px 10px' }}
            >
                {title && <div className={style.title}>
                    <Space><span>{title}</span>{tips && <Tooltip title={tips}><span><QuestionCircleOutlined /></span></Tooltip>}</Space>
                </div>}
                <Row gutter={[0, 16]}>
                    <DispatchHeader.Provider value={{ setIsFullscreen, isFullscreen, isFull, toggleFull, setVisible, ajax, czChild, leftChild }}>
                        <Settings />
                    </DispatchHeader.Provider>
                    <DispatchContext.Provider value={{total}}>
                        <Col span={24}>
                            <div className={`${style[size]} ${className ? style[className] : ''} `}>
                                
                            </div>
                        </Col>
                    </DispatchContext.Provider>
                </Row>
            </Card>
        </Col>
    </Row>
}

export default React.memo(TablePro)