/*
 * @Author: your name
 * @Date: 2021-12-24 09:43:04
 * @LastEditTime: 2022-04-29 16:48:03
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /MedicalWisdomCheckSys/src/components/MccsLightTable/index.tsx
 */

import React, { useEffect, useState } from 'react';
import type { MccsLightTableTypes } from './typings';
import { Empty, Tooltip, Pagination } from 'antd';

import './style.less';



const MccsLightTable: React.FC<{
    columns: MccsLightTableTypes.MccsLightTableColumn[],
    data?: [],
    request?: (current: number, pageSize: number) => Promise<{
        current: number,
        list: any[],
        pageSize: number,
        totalCount: number,
    }>,
    renderRow?: (data: any) => React.Component<any>,
}> = props => {

    const {
        columns,
        renderRow,
        request
    } = props

    const [dataList, setDataList] = useState<any[]>([]);
    const [renderColumns, seRenderColumns] = useState<MccsLightTableTypes.MccsLightTableColumn[]>([]);
    const [pageData, setPageData] = useState<{ pageSize: number, current: number }>({ pageSize: 10, current: 1 });
    const [total, setTotal] = useState(0);  // 数据总数

    const getData = async (current: number, size: number) => {
        if (!request) return [];
        const data = await request(current, size);
        if (data) {
            const { list = [], totalCount } = data;
            setTotal(totalCount);
            setDataList(list);
        } else {
            return []
        }

    }

    const onShowSizeChangeHandle = (current: number, size: number) => {

        setPageData({ ...pageData, current: current + 1, pageSize: size });
        getData(current + 1, size); // current 默认从0开始
    }

    const pageChangeHandle = (page: number, pageSize: number | undefined) => {
        // 分页页码变化时
        // console.log({page,pageSize});
        getData(page, pageSize || 10);
    }

    useEffect(() => {
        const hasSetWidColumns = columns.filter(item => item.width);
        const needCountWidCloumnsNum = columns.length - hasSetWidColumns.length;
        const widArray = hasSetWidColumns.map(item => item.width)
        const CountableWid = widArray.reduce((prev, curr) => (prev || 0) + (curr || 0), 0);
        // 初始化cell长度
        const a = columns.map((item, index) => {

            if (index == 0) {
                // console.log({...item,width:(100-(CountableWid?CountableWid:0))/needCountWidCloumnsNum});
                return item.width ? item : { ...item, width: (100 - (CountableWid || 0)) / needCountWidCloumnsNum }
            }


            const beichushu = 100 - (CountableWid || 0);
            const chushu = needCountWidCloumnsNum;

            return item.width ? item : { ...item, width: (beichushu / chushu) }
        });

        seRenderColumns(a);

    }, [columns]);

    useEffect(() => {
        getData(pageData.current, pageData.pageSize);
        // setDataList([
        //     {
        //         gradeLevel:'A',
        //         pfmDataDirectoryList:[
        //             {
        //                 id:0,
        //                 numStr:'1.1.1.1',
        //                 directory:'directory',
        //                 accountType:'accountType',
        //                 accountStatus:0
        //             },
        //             {
        //                 id:3,
        //                 numStr:'1.1.1.1',
        //                 directory:'directory',
        //                 accountType:'accountType',
        //                 accountStatus:0
        //             }
        //         ]
        //     },
        //     {
        //         gradeLevel:'B',
        //         pfmDataDirectoryList:[
        //             {
        //                 id:2,
        //                 numStr:'1.1.1.1',
        //                 directory:'directory',
        //                 accountType:'accountType',
        //                 accountStatus:0
        //             }
        //         ]
        //     }
        // ]);
    }, []);

    // 自定义渲染表格内容
    const renderTableRow = (data: any) => {
        const { pfmDataDirectoryList: list, gradeLevel: grade } = data;
        const _cpcolumns = Object.assign([], renderColumns);
        _cpcolumns.splice(0, 1);  // 剔除第一个

        const headWid = renderColumns[0] && renderColumns[0].width ? renderColumns[0].width : 0;

        return (
            <div className='list' >
                <div className='head' style={{ width: `${headWid}%` }}>{grade}</div>
                <div className='headRelaData' style={{ position: 'relative', left: `${headWid}%` }}>
                    {
                        (list).map((item: any, index: number) => {
                            return (
                                <div className='subList' key={index}>
                                    {
                                        _cpcolumns.map((v: any, k: any) => {
                                            let cellValue = item[v.key];
                                            // 自定义value结果
                                            if (v.render) {
                                                cellValue = v.render(item)
                                            }
                                            return (
                                                <div className='cell' key={k} style={{ width: `${v.width}%` }}>
                                                    {
                                                        item.valueType != 'option' ? (
                                                            <Tooltip title={cellValue}>
                                                                {cellValue}
                                                            </Tooltip>
                                                        ) : cellValue
                                                    }

                                                </div>
                                            )
                                        })
                                    }
                                </div>
                            )
                        })
                    }
                </div>
            </div>
        )
    }


    return (
        <>
            <div className='mccsLighttable'>
                <div className='columns'>
                    {
                        renderColumns.map((item, index) => {
                            return (
                                <div key={index} className='columnBlock' style={{ width: `${item.width}%` }}>{item.title}</div>
                            )
                        })
                    }
                </div>
                <div className='listWrap'>

                    {dataList.length == 0 && <div className='empty'><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /></div>}

                    {
                        dataList.length > 0 && (
                            <div className='listRow'>
                                {
                                    dataList.map((item, index) => {
                                        return <React.Fragment key={index}>{renderTableRow(item)}</React.Fragment>
                                    })
                                }
                            </div>
                        )
                    }
                </div>
            </div>
            {
                request && (
                    <div className='pagination'>
                        <Pagination size="small"
                            total={total}
                            pageSize={pageData?.pageSize}
                            showSizeChanger
                            showQuickJumper
                            onChange={(page, pageSize) => pageChangeHandle(page, pageSize)}
                            onShowSizeChange={onShowSizeChangeHandle}
                        />
                    </div>
                )
            }
        </>
    )

}

export default MccsLightTable;