import React, { Key, useEffect, useImperativeHandle, useState } from "react";
import { Transfer } from 'antd'
import { TransferItem, TransferProps } from 'antd/es/transfer';
import { ColumnsType } from 'antd/es/table';
import { difference } from "lodash";
import { TableRowSelection } from 'antd/es/table/interface';
import { KCIMTable } from "@/components/KCIMTable";
import { ProColumns } from "@ant-design/pro-components";

import { log } from "mathjs";
import { getHasConnectedHisItemDicListReq, getHisItemDicListReq } from "./service";



interface TableTransferProps extends TransferProps<TransferItem> {
    leftColumns: ProColumns[];
    rightColumns: ProColumns[];
    record: any,
    onSave: (selectedKeys: Key[], selectedRowKeys: any[]) => void;
}

const TableTransfer = React.forwardRef(({ leftColumns, rightColumns, record, onSave, ...restProps }: TableTransferProps, ref) => {

    const [_data, _set_data] = useState<any>();
    const [targetKeys, setTargetKeys] = useState<string[]>([]);
    const [datasource, set_datasource] = useState<any[]>([]);
    const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
    const [queryCondition,set_queryCondition] = useState('');
    
    //获取列表
    const getFuncList = async (params:any) => {
        let resp = await getHisItemDicListReq({pageSize:500,current:1,...params});
        if (resp) {
            set_datasource([...resp.list]);
            
        }

    }

    const getDefaultData = async ()=>{
          const resp = await getHasConnectedHisItemDicListReq({qualificationId:record.id});
          if(resp){
               const defaultkeys = resp.list.map((a:any)=>`${a.id}`);
               setTargetKeys([...targetKeys,...defaultkeys]);
          }
    }

    const onChange = (nextTargetKeys: string[]) => {
        setTargetKeys(nextTargetKeys);
    };

    const onSelectChange = (sourceSelectedKeys: string[], targetSelectedKeys: string[]) => {
        //console.log('sourceSelectedKeys:', sourceSelectedKeys,'targetSelectedKeys:',targetSelectedKeys);
        setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
    };

    useImperativeHandle(ref, () => ({
        save: async () => {
            const items = datasource.filter(a => targetKeys.includes(a.hisItemId));
            onSave(targetKeys, items);
        }
    }));

    useEffect(() => {
        getFuncList({});
        getDefaultData();
    }, [])

    return (
        <Transfer className='TableTransfer' showSearch
            titles={['待选项', '已选项']}
            locale={{
                itemUnit: '项',
                itemsUnit: '项',
                searchPlaceholder: '医嘱编码、医嘱名称',
            }}
            oneWay={false}
            onChange={onChange}
            onSelectChange={onSelectChange}
            dataSource={datasource}
            rowKey={record => record.hisItemId}
            targetKeys={targetKeys}
            selectedKeys={selectedKeys}
            filterOption={(inputValue, item) => {
                return (item.hisItemName!.indexOf(inputValue) !== -1)||(item.hisItemId!.indexOf(inputValue) !== -1)

            }}
        >
            {({
                direction,
                filteredItems,
                onItemSelectAll,
                onItemSelect,
                selectedKeys: listSelectedKeys,
                disabled: listDisabled,
            }) => {

                // console.log({ filteredItems, listSelectedKeys,direction });
                const columns = direction === 'left' ? leftColumns : rightColumns;

                const rowSelection: TableRowSelection<TransferItem> = {
                    getCheckboxProps: (item) => ({ disabled: listDisabled || item.disabled }),
                    onSelectAll(selected, selectedRows) {
                        const treeSelectedKeys = selectedRows.map(({ hisItemId }) => hisItemId);
                        const diffKeys = selected
                            ? difference(treeSelectedKeys, listSelectedKeys)
                            : difference(listSelectedKeys, treeSelectedKeys);
                        onItemSelectAll(diffKeys as string[], selected);
                    },
                    onSelect({ hisItemId }, selected) {
                        onItemSelect(hisItemId as string, selected);
                    },
                    selectedRowKeys: listSelectedKeys,
                };

                return (
                    <KCIMTable
                        rowSelection={rowSelection}
                        columns={columns as TransferItem[]}
                        dataSource={filteredItems}
                        size="small"
                        tableStyle={{border:'none'}}
                        bordered={false}
                        rowKey={'hisItemId'}
                        pagination={{ showTitle: false, pageSize: 9, showLessItems: false, simple: true, showTotal: () => false }}
                        tableAlertRender={false}
                        style={{ pointerEvents: listDisabled ? 'none' : undefined }}
                        onRow={({ code, disabled: itemDisabled }) => ({
                            onClick: () => {
                                if (itemDisabled || listDisabled) return;
                                onItemSelect(code as string, !listSelectedKeys.includes(code as string));
                            },
                        })}
                    />
                );
            }}
        </Transfer>
    )
});

export default TableTransfer


