import React, { Key, useEffect, useState } from "react";

import { KCIMTable } from "@/components/KCIMTable";
import { createFromIconfontCN } from "@ant-design/icons";


import { ModalForm, ProColumns, ProFormSelect, ProFormText } from "@ant-design/pro-components";

import { set } from "lodash";
import './style.less'

interface TableSelecterProps {
    record: any
}

const IconFont = createFromIconfontCN({
    scriptUrl: '',
});




const TableSelecter = (
    { 
        record, 
        open, 
        title, 
        columns,
        onVisibleChange,
        rowKey = 'id',
        request, 
        tableData,
        onFinish,
        defaultSelectedKeys,
    }: 
    {
        record: any,
        columns:ProColumns[],
        open: boolean,
        title: string,
        tableData?:any[],
        onVisibleChange: (bool: boolean) => void,
        defaultSelectedKeys: Key[],
        rowKey?: string,
        request?: () => Promise<any>,
        onFinish?: (selectedKeys: React.Key[], selectedRows: any[]) => void
    }
) => {


    const Table = React.forwardRef(({ }: TableSelecterProps, ref) => {

        const [datasource, set_datasource] = useState<any[]>([]);
        const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
        const [selectedRows, set_selectedRows] = useState<any[]>([]);
        const [showList, set_showList] = useState<any[]>([]);
        const [filter, set_filter] = useState<undefined | any>(undefined);
        const [code, set_code] = useState<undefined | any>(undefined);
        const [keyword, set_keyword] = useState<string | undefined>(undefined);


        const onSelectChange = (newSelectedRowKeys: React.Key[], selectedRows: any) => {
            setSelectedKeys([...newSelectedRowKeys]);
            set_selectedRows([...selectedRows]);

        };

        const saveHandle = async () => {
            const selectedRowkeys = selectedRows.map((a) => a[`${rowKey}`]);
            const rows = datasource.filter((a) => selectedRowkeys.includes(a[`${rowKey}`]));
            onFinish && onFinish(selectedKeys, rows);
        }

        const getTableData = async () => {

            const resp = !tableData&&request?await request():tableData;

            let selectedCodes: string[] = [];
            let selectedRows: any[] = [];
            if (resp) {
                console.log({defaultSelectedKeys});
                const data = resp.map((a: any) => {
                    if (defaultSelectedKeys.includes(a[`${rowKey}`])) {
                        selectedCodes.push(a[`${rowKey}`]);
                        selectedRows.push(a);
                        //const needItem = record.departList.filter((b: any) => a[`${rowKey}`] == b[`${rowKey}`]);

                        return {
                            ...a,
                            //flag: needItem[0].isManager ? true : false
                        }
                    } else {
                        return a
                    }
                });

                set_showList(data);
                set_selectedRows([...selectedRows]);
                setSelectedKeys([...selectedCodes]);
                set_datasource([...datasource, ...data]);
            }


            return Promise.resolve([]);
        }

        useEffect(() => {
            // console.log({code, keyword});
            const result = datasource.filter((a) => {
                return a.name ? a.name.indexOf(keyword) != -1 : false
            });

            set_showList([...result]);
        }, [keyword]);

        // useEffect(()=>{
        //     (record)&&getTableData(record)
        // },[record])

        useEffect(()=>{
           getTableData()
        },[])

        return (
            <div >
                <div className="filter" style={{ display: 'flex', flexDirection: 'row', marginBottom: 8 }}>
                    <ProFormText noStyle placeholder={'请输入'}
                        fieldProps={{
                            suffix: <IconFont style={{ color: '#99A6BF' }} type="iconsousuo" />,
                            onChange: (e) => {
                                if (e.target.value.length != 0) {
                                    set_keyword(e.target.value);
                                } else {
                                    set_keyword('');
                                }
                            }
                        }}
                    />
                </div>

                <KCIMTable columns={columns}
                    options={{
                        density: true,
                        setting: {
                            listsHeight: 100,
                        },
                    }}
                    rowKey={rowKey}
                    scroll={{ y: 400 }}
                    tableAlertRender={false}
                    rowSelection={{
                        // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                        // 注释该行则默认不显示下拉选项
                        // selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                        selectedRowKeys: selectedKeys,
                        onChange: onSelectChange,
                    }}
                    pagination={{ showTitle: false, showSizeChanger: false, simple: true }}
                    dataSource={showList}

                />
                <div className='footer'>
                    <span className='cancel' onClick={() => close()}>取消</span>
                    <span className='ok' onClick={() => saveHandle()}>{`确认(${selectedKeys.length > 0 && selectedKeys.length})`}</span>
                </div>
            </div>

        )
    });

    const close = () => {
        onVisibleChange && onVisibleChange(false);
    }


    return (
        <ModalForm className="TableSelecter" title={title} width={400} submitter={{
            render: false
        }} open={open} modalProps={{
            closable: false,
        }}>
            <Table
                // ref={tableSelecterRef}
                record={undefined}
            ></Table>
        </ModalForm>
    )

}




export default TableSelecter