/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-06-20 15:41:00
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */




import BMSPagecontainer from '@/components/BMSPageContainer';
import { BMSTable } from '@/components/BMSTable';

import { createFromIconfontCN, MenuOutlined } from '@ant-design/icons';
import { ActionType, ProFormInstance, ProFormSelect, useRefFunction } from '@ant-design/pro-components';
import { ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { InputNumber, Dropdown, Input, MenuProps, message, Modal, Popconfirm, Space, Form, Table, Tabs } from 'antd';

import { TransferItem, TransferProps } from 'antd/es/transfer';
import React, { Key } from 'react';
import { useEffect, useImperativeHandle, useRef, useState } from 'react';

import { getMedicalGroup, getEmpTableDataFromMedicalGroup, addMedicalGroup, editMedicalGroup, delLeftReportData, addMedicalGroupEmp, updateMedicalGroupEmpInfo, delTableData, getAllUnitList, addGroupItemList, editGroupItemList, batchDelItemList } from './service';

import './style.less';
import '../../../../utils/zhongtaiB';
import '../../../../utils/zhongtaiA'
import editIcon from '../../../../../static/editIcon.png';
import conformIcon from '../../../../../static/confirmIcon.png';

import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import { getSecondaryProjectDistriData } from '../secondaryProjectDistribute/service';
import { arrayMoveImmutable } from 'array-move';

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

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



const DragHandle = SortableHandle(() => (
    <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />
));

let _currentSelectedType: { groupCode: any; } | undefined = undefined;
let updatedDataSource: any[] = [];

let _currentTabKey: string | undefined = '1';


const SecondaryDistriGroupSet = () => {

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();

    const [typeList, set_typeList] = useState<any[]>([]);
    const [showTypeListArr, set_showTypeListArr] = useState<any[]>([]);
    const [currentSelectedType, set_currentSelectedType] = useState<any | undefined>(undefined);

    const [tableSelectedKeys, set_tableSelectedKeys] = useState<any[]>([]);
    const [tableSelectedRows, set_tableSelectedRows] = useState<any[]>([]);

    const [selectedAddKeys, set_selectedAddKeys] = useState<Key[]>([]);

    const [ifShowModal, set_ifShowModal] = useState(false);

    const [currentEditLeftData, set_currentEditLeftData] = useState<any | undefined>(undefined);
    const [currentEditRecord, set_currentEditRecord] = useState<any | undefined>(undefined);

    const [ifEditTable, set_ifEditTable] = useState(false);

    const [currentTabKey, set_currentTabKey] = useState('1');

    const tableRef = useRef<ActionType>();

    const [dataSource, set_dataSource] = useState<any[]>([]);
    const ref = React.createRef<{ save: any; getSelectedKeys: any }>();

    const [tableColumns, set_tableColumns] = useState<ProColumns[]>([]);

    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState('');
    const [totalWeight, set_totalWeight] = useState(0);


    const columnOne: ProColumns[] = [

        {
            title: '核算单元名称',
            ellipsis: true,
            dataIndex: 'unitName',

        },
        {
            title: '核算单元代码',
            dataIndex: 'unitCode',

        },
        {
            title: '职类',
            dataIndex: 'unitTypeName',

        },
        {
            title: '操作',
            key: 'option',
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableDataHanfle(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },
    ];
    const columnTwo: ProColumns[] = [
        {
            title: '排序',
            dataIndex: 'sort',
            width: 60,
            className: 'drag-visible',
            render: () => <DragHandle />,
        },
        {
            title: '项目名称',
            ellipsis: true,
            dataIndex: 'itemName',

        },
        {
            title: '占比',
            dataIndex: 'weight',
            render: (text: any, record: any) => {
                const {evaluation} = record;
                return ( 
                    <div style={{ display: 'flex', flexDirection: 'row', width: '100%', justifyContent: 'flex-start', alignItems: 'center' }}>

                        <div style={{ width: '80px', height: 16, display: 'flex', flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center' }}>
                            {
                                (currentEditRecord ? currentEditRecord.id : -1) == record.id ? <InputNumber size='small' defaultValue={record.weight} placeholder='请输入' onChange={(value) => {

                                    updatedDataSource = dataSource.map((a) => {
                                        if (a.id == currentEditRecord.id) {
                                            return { ...a, weight: value }
                                        }
                                        return a
                                    });
                                    set_dataSource([...updatedDataSource]);

                                }} style={{ width: '80px' }} /> : <span>{text}</span>
                            }
                        </div>
                        {evaluation != 3 && <img onClick={() => editHandleTwo(record)} style={{ width: 16, height: 16, cursor: 'pointer', marginLeft: 8 }} src={(currentEditRecord ? currentEditRecord.id : -1) == record.id ? conformIcon : editIcon} alt="" />}
                    </div>
                )
            }

        },
        {
            title: '评价方式',
            dataIndex: 'evaluationName',

        },
        {
            title: '来源',
            dataIndex: 'sourceName',

        },
        {
            title: '操作',
            key: 'option',
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableDataHanfle(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },
    ]


    //编辑单元格占比
    const editHandleTwo = async (record: any) => {
        const { id } = record;

        if (currentEditRecord && id == currentEditRecord.id) {
            const resp = await editGroupItemList([...updatedDataSource]);

            if (resp) {
                getTableData();
            }
            set_currentEditRecord(undefined);
        } else {
            set_currentEditRecord(record);
        }

    }




    const getTableData = async (params?: any) => {
        if (!_currentSelectedType) return false;
        const { groupCode: secondGroupCode } = _currentSelectedType;
        let keywords = params ? params.keywords : ''

        if (secondGroupCode) {
            const resp = await getEmpTableDataFromMedicalGroup(_currentTabKey == '1' ? { secondGroupCode, unitName: keywords } : { secondGroupCode, itemName: keywords }, _currentTabKey == '1' ? 1 : 2);
            if (resp) {
                set_dataSource(resp);
            }
        }
    }

    const switchChangeHandle = async (checked: boolean, record: any, key: string) => {
        const result = { ...record, medicalGroupManager: checked ? 1 : 0 }
        const resp = await updateMedicalGroupEmpInfo(result);
        if (resp) {
            tableRef.current?.reload();
        }
    }

    const delTableDataHanfle = async (record?: { id: number; }) => {
        if (_currentTabKey == '1') {
            const resp = await delTableData(record ? [record.id] : [...tableSelectedKeys]);
            if (resp) {
                set_tableSelectedKeys([]);
                getTableData();
            }
        }
        if (_currentTabKey == '2') {
            const resp = await batchDelItemList(record ? [record.id] : [...tableSelectedKeys]);
            if (resp) {
                set_tableSelectedKeys([]);
                getTableData();
            }
        }
    }

    //获取左侧数据
    const getPageLeftData = async () => {
        const resp = await getMedicalGroup();

        if (resp) {

            set_typeList(resp);
            set_showTypeListArr(resp);
        }
    }


    const updateTable = async (formVal: any, type: 'EDIT' | "ADD" | 'ADD_LEFTDATA' | 'EDIT_LEFTDATA') => {

        // console.log({formVal,type});

        if (type == 'ADD_LEFTDATA') {
            const resp = await addMedicalGroup({
                groupName: formVal.groupName,
                description: formVal.description,
            });
            if (resp) {
                getPageLeftData();
            }
        }



        if (type == 'EDIT_LEFTDATA') {
            const resp = await editMedicalGroup({
                id: formVal.id,
                groupName: formVal.groupName,
                description: formVal.description
            });
            if (resp) {
                getPageLeftData();
            }
        }

        return true;

    }

    const UpDataActBtn = ({ record, type }: { record: any, type: 'EDIT' | 'ADD' | 'ADD_LEFTDATA' | 'EDIT_LEFTDATA' }) => {

        const getTrriger = () => {
            if (type == 'ADD') {
                return <span className='add'>添加</span>
            }
            if (type == 'EDIT') {
                return <a key="edit" >编辑</a>
            }
            if (type == 'ADD_LEFTDATA') {
                return (
                    <div className='add'>
                        <img src={require('../../../../../static/addIcon_black.png')} alt="" />
                    </div>
                )
            }
            if (type == 'EDIT_LEFTDATA') {
                return <a key="edit" >编辑</a>
            }
        }

        return (
            <ModalForm
                title={type == 'ADD_LEFTDATA' ? `新增分组` : `编辑分组`}
                width={352}
                initialValues={type == 'EDIT_LEFTDATA' ? { ...record } : {}}
                trigger={
                    getTrriger()
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT_LEFTDATA' ? { ...record, ...val } : val, type);
                }}
            >

                <ProFormText
                    label='分组名称：'
                    name='groupName'
                    rules={[{ required: true, message: '名称不能为空!' }]}
                />
                <ProFormTextArea
                    label='说明：'
                    name='description'
                />
            </ModalForm>
        )
    }


    interface TableSelecterProps extends TransferProps<TransferItem> {
        tableSelecterColumn: any[];
        record: any
    }


    const tableSelecterUnitColumn: any[] = [
        {
            title: '核算单元名称',
            dataIndex: 'unitName',
        },
        {
            title: '职类',
            dataIndex: 'unitTypeName',
        },
    ];
    const tableSelecterItemColumn: any[] = [
        {
            title: '项目代码',
            dataIndex: 'code',
        },
        {
            title: '项目名称',
            dataIndex: 'name',
        },
    ];

    const addGroupEmpHandle = () => {

        const ref = React.createRef<{ save: any; getSelectedKeys: any }>();

        set_ifShowModal(true);
    }

    const TableSelecter = React.forwardRef(({ tableSelecterColumn, record }: 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 getFuncList = async () => {
            if (currentTabKey == '1') {
                const resp = await getAllUnitList({ secondGroupCode: currentSelectedType.groupCode });
                if (resp) {
                    set_datasource(resp);
                    set_showList(resp);
                }
            }
            if (currentTabKey == '2') {
                const resp = await getSecondaryProjectDistriData({ pageSize: 1000, current: 1 });
                const currentSelectedIds = dataSource.map((a) => a.itemCode);
                if (resp) {
                    const needItems = resp.list.filter((a) => !(currentSelectedIds.includes(a.code)))
                    set_datasource(needItems);
                    set_showList(needItems);
                }
            }

        }


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

        const save = async () => {
            if (currentTabKey == '1') {
                const result = {
                    secondGroupCode: currentSelectedType.groupCode as string,
                    unitCodeList: selectedKeys
                };

                const resp = await addMedicalGroupEmp(result);

                if (resp) {
                    message.success('添加成功！');
                    set_ifShowModal(false);
                    getTableData();

                }
            }

            if (currentTabKey == '2') {
                const newData = selectedRows.map((a: any) => ({
                    secondItemCode: a.code,
                    weight: 0
                }));
                const current = dataSource.map((a: any) => ({
                    secondItemCode: a.itemCode,
                    weight: a.weight
                }));
                const result = {
                    secondGroupCode: currentSelectedType.groupCode,
                    itemList: [...current, ...newData]
                }
                const resp = await addGroupItemList(result);
                if (resp) {
                    getTableData();

                }
            }

            set_ifShowModal(false);

        }

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

        return (
            <div className='TableSelecter'>
                <Input placeholder={'请输入'} allowClear
                    suffix={
                        <IconFont style={{ color: '#99A6BF' }} type="iconsousuo" />
                    }
                    style={{ marginBottom: 8 }}
                    onChange={(e) => {
                        if (e.target.value.length != 0) {
                            const result = datasource.filter(item => (currentTabKey == '1' ? item.unitName : item.name).indexOf(e.target.value) != -1);
                            set_showList(result);
                        } else {
                            set_showList(datasource);
                        }

                    }}

                />
                <BMSTable columns={tableSelecterColumn}
                    options={{
                        density: true,
                        setting: {
                            listsHeight: 100,
                        },
                    }}
                    rowKey='code'
                    // scroll={{y:300}}
                    tableAlertRender={false}
                    rowSelection={{
                        // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                        // 注释该行则默认不显示下拉选项
                        selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                        onChange: onSelectChange,
                    }}
                    pagination={{ showSizeChanger: false, pageSize: 9, simple: true, showTitle: false }}
                    dataSource={showList}
                />
                <div className='footer'>
                    <span className='cancel' onClick={() => set_ifShowModal(false)}>取消</span>
                    <span className='ok' onClick={() => save()}>{`确认(${selectedKeys.length > 0 && selectedKeys.length})`}</span>
                </div>
            </div>

        )
    });

    const moreItems: MenuProps['items'] = [
        {
            key: '1',
            label: <UpDataActBtn key={'act'} record={currentEditLeftData} type='EDIT_LEFTDATA' />,
        },
        {
            key: '2',
            label: (
                <a onClick={async (e) => {
                    e.preventDefault();
                    const resp = await delLeftReportData(currentEditLeftData.id);
                    if (resp) {
                        getPageLeftData();
                    }
                }}>
                    删除
                </a>
            ),
        }
    ];


    const onTableSelectChange = (newSelectedRowKeys: React.Key[], selectedRows: any[]) => {
        set_tableSelectedKeys([...newSelectedRowKeys]);
        set_tableSelectedRows([...selectedRows]);
    };

    const updateSecondaryDistriItemSet = async (itemList: any[], type: 'ADD' | 'EDIT') => {

        if (type == 'ADD') {
            const totalWeight = itemList.reduce((prev, cur) => {
                console.log({ 'prev': prev, 'cur.weight': cur.weight })
                return (prev) + cur.weight
            }, 0);

            if (totalWeight.toFixed(2) != 1) {
                message.error('占比总和必须等于1！');
                return false
            }
            const result = {
                secondGroupCode: currentSelectedType.groupCode,
                itemList: itemList.map((a: any) => ({
                    secondItemCode: a.secondItemCode ? a.secondItemCode : a.itemCode,
                    weight: a.weight
                }))
            }
            const resp = await addGroupItemList(result);
            if (resp) {
                getTableData();
                return true;
            }
            return false
        }

        if (type == 'EDIT') {
            const resp = await editGroupItemList(itemList);
            if (resp) {
                getTableData();
            }
        }

    }

    // const AddItemComponent = () => {


    //     const [scoreList, set_scoreList] = useState<any[]>([]);
    //     const [scoreInitList, set_scoreInitList] = useState({});
    //     const [evaluationIs3Codes, set_evaluationIs3Codes] = useState<string[]>([]);
    //     const formRef = useRef<ProFormInstance>();

    //     const addIndicator = () => {

    //         const key = Math.random();

    //         const temp = [...scoreList, { tempId: key, id: key, [`secondItemCode${key}`]: '', [`weight${key}`]: '' }];

    //         set_scoreInitList({ ...scoreInitList, [`secondItemCode${key}`]: '', [`weight${key}`]: '' });

    //         set_scoreList([...temp]);

    //     }

    //     const delGroupIndic = (data: any, index: number) => {
    //         let temp = [...scoreList];
    //         let defaultFormData: { [key: string]: any } = {};
    //         const result = temp.filter((a: any) => a.id != data.id);
    //         result.forEach((a: any) => {
    //             defaultFormData[`secondItemCode${a.id}`] = a.secondItemCode;
    //             defaultFormData[`weight${a.id}`] = a.weight;
    //             defaultFormData[`evaluation${a.id}`] = a.evaluation;
    //         });

    //         set_scoreInitList({ ...defaultFormData });
    //         set_scoreList([...result]);
    //     }


    //     useEffect(() => {
    //         let defaultFormData: { [key: string]: any } = {};
    //         if (true) {
    //             const defaultVal = dataSource.map((a: any) => {
    //                 defaultFormData[`secondItemCode${a.id}`] = a.itemCode;
    //                 defaultFormData[`weight${a.id}`] = a.weight;
    //                 defaultFormData[`evaluation${a.id}`] = a.evaluation;

    //                 return { ...a, tempId: Math.random() }
    //             });

    //             set_scoreInitList({ ...defaultFormData });

    //             set_scoreList([...defaultVal]);
    //         }
    //     }, []);

    //     return (
    //         <ModalForm
    //             title={`二次分配项目设置(${currentSelectedType.groupName})`}
    //             className='SecondaryDistriGroupSet-ModalForm'
    //             width={355}
    //             formRef={formRef}
    //             initialValues={{ ...scoreInitList }}
    //             trigger={
    //                 <a className='score'>添加</a>
    //             }
    //             onFinish={(val) => {
    //                 return updateSecondaryDistriItemSet(scoreList, 'ADD');
    //             }}
    //             modalProps={{ destroyOnClose: true }}
    //         >
    //             {
    //                 (
    //                     <div>
    //                         {
    //                             scoreList.map((item: any, index: number) => {

    //                                 return (
    //                                     <div className='item' key={index}>
    //                                         <ProFormSelect label="二次分配项目：" width={160}
    //                                             name={`secondItemCode${item.id}`}
    //                                             request={async () => {
    //                                                 const resp = await getSecondaryProjectDistriData({ pageSize: 1000, current: 1 });
    //                                                 if (resp) {
    //                                                     return resp.list.map((a: any) => ({
    //                                                         label: a.name,
    //                                                         value: a.code,
    //                                                         evaluation: a.evaluation
    //                                                     }))
    //                                                 }
    //                                                 return []

    //                                             }}
    //                                             fieldProps={{
    //                                                 //   labelInValue:true,
    //                                                 onChange(value, option: any) {
    //                                                     const temp = [...scoreList];
    //                                                     const newArr = temp.map((a: any) => {
    //                                                         if (a.id == item.id) {

    //                                                             return {
    //                                                                 ...a, secondItemCode: value, secondItemName: option.label,
    //                                                                 weight: option.evaluation == 3 ? 0 : a.weight
    //                                                             }
    //                                                         }
    //                                                         return a
    //                                                     });

    //                                                     if (option.evaluation == 3) {
    //                                                         formRef?.current?.setFieldValue([`weight${item.id}`], 0);
    //                                                         formRef?.current?.setFieldValue([`evaluation${item.id}`], 3);
    //                                                     } else {
    //                                                         formRef?.current?.setFieldValue([`evaluation${item.id}`], option.evaluation);
    //                                                     }

    //                                                     set_scoreList([...newArr]);
    //                                                 },
    //                                             }}
    //                                         />
    //                                         <Form.Item name={`weight${item.id}`} label='占比：'>
    //                                             <InputNumber
    //                                                 disabled={(formRef?.current?.getFieldValue(`evaluation${item.id}`) != item.evaluation && formRef?.current?.getFieldValue(`evaluation${item.id}`) != undefined) ? formRef?.current?.getFieldValue(`evaluation${item.id}`) == 3 : item.evaluation == 3}
    //                                                 style={{ width: 120, height: 24, position: 'relative', top: 0 }}
    //                                                 onChange={(value) => {
    //                                                     //console.log({value,index,indicatorData});
    //                                                     const temp = [...scoreList];
    //                                                     const newArr = temp.map((a: any) => {
    //                                                         if (a.id == item.id) {
    //                                                             return { ...a, weight: value }
    //                                                         }
    //                                                         return a
    //                                                     });

    //                                                     set_scoreList([...newArr]);
    //                                                 }}
    //                                             />
    //                                         </Form.Item>
    //                                         <span className='delIcon' onClick={() => delGroupIndic(item, index)}><IconFont type="iconshanchu" /></span>
    //                                     </div>
    //                                 )
    //                             })
    //                         }
    //                         <div className='addBtn' onClick={() => addIndicator()}>
    //                             <AddIconFont type="icon-zengjia" style={{ color: '#3376FE' }} /><span>增加一行</span>
    //                         </div>
    //                     </div>
    //                 )
    //             }
    //         </ModalForm>
    //     )
    // }

    const onTabChange = (activeKey: string) => {
        set_currentTabKey(activeKey);
        activeKey == '1' ? set_tableColumns(columnOne) : set_tableColumns(columnTwo);
        _currentTabKey = activeKey
    }



    const SortableItem = SortableElement((props: any) => <tr {...props} />);
    const SortContainer = SortableContainer((props: any) => <tbody {...props} />);

    const onSortEnd = useRefFunction(
        ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => {
            if (oldIndex !== newIndex) {
                const newData = arrayMoveImmutable([...dataSource], oldIndex, newIndex).filter((el) => !!el);
                const updatedSortArr = newData.map((item: any, index: number) => ({ ...item, sort: index + 1 }))
                set_dataSource([...updatedSortArr]);
                updateSecondaryDistriItemSet(updatedSortArr, 'EDIT');
            }
        },
    );

    const DraggableContainer = (props: any) => (
        <SortContainer
            useDragHandle
            disableAutoscroll
            helperClass="row-dragging"
            onSortEnd={onSortEnd}
            {...props}
        />
    );

    const DraggableBodyRow = (props: any) => {
        const { className, style, ...restProps } = props;
        // function findIndex base on Table rowKey props and should always be a right array index
        const index = dataSource.findIndex(
            (x) => x.id === restProps['data-row-key'],
        );

        return <SortableItem index={index} {...restProps} />;
    };

    useEffect(() => {
        _currentSelectedType = currentSelectedType;
        if (currentSelectedType) {
            set_tableDataFilterParams({ ...tableDataFilterParams, secondGroupCode: currentSelectedType.groupCode });
            getTableData();

        }
    }, [currentSelectedType]);

    useEffect(() => {
        if (currentTabKey == '2') {
            set_tableColumns([...columnTwo]);
        }
    }, [currentEditRecord])

    useEffect(() => {
        if (showTypeListArr.length > 0) {
            set_currentSelectedType(showTypeListArr[0]);
            //set_tableDataFilterParams({ ...tableDataFilterParams, medicalGroupCode: showTypeListArr[0].code });
        }
    }, [showTypeListArr]);

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

    useEffect(() => {
        if (currentTabKey == '2') {
            const total = dataSource.reduce((prev, cur) => prev + cur.weight, 0);
            set_totalWeight(total.toFixed(4));
        }
    }, [dataSource]);

    useEffect(() => {

    }, [tableDataFilterParams])


    useEffect(() => {
        getPageLeftData();
        set_tableColumns(columnOne);
    }, [])



    return (
        <BMSPagecontainer title={false} className='SecondaryDistriGroupSet'>

            <ModalForm title={'新增分组核算单元'} width={400}
                submitter={{
                    render: (props, defaultDoms) => []
                }}
                open={ifShowModal} modalProps={{
                    closable: false,
                }}>
                <TableSelecter
                    ref={ref}
                    record={undefined}
                    tableSelecterColumn={currentTabKey == '1' ? tableSelecterUnitColumn : tableSelecterItemColumn}
                ></TableSelecter>
            </ModalForm>

            <div className='left'>
                <div className='toolbar'>
                    <Input placeholder={'请输入分组名称'} allowClear
                        suffix={
                            <IconFont style={{ color: '#99A6BF' }} type="iconsousuo" />
                        }
                        style={{ width: 156 }}
                        onChange={(e) => {
                            const result = typeList.filter(item => item.groupName.indexOf(e.target.value) != -1);
                            set_showTypeListArr(result);
                        }}
                    />

                    <UpDataActBtn key={'act'} record={undefined} type='ADD_LEFTDATA' />

                </div>

                <div className='wrap'>
                    {
                        showTypeListArr.map((item, index) => {
                            return (
                                <div className={currentSelectedType ? currentSelectedType.id == item.id ? 'type on' : 'type' : 'type'}
                                    key={index}
                                    onClick={() => {
                                        if (ifEditTable) {
                                            //编辑状态还未保存
                                            Modal.confirm({
                                                title: '当前存在编辑未保存，请保存后再操作！',
                                                okText: '放弃编辑',
                                                cancelText: '继续编辑',
                                                onOk(...args) {
                                                    set_ifEditTable(false);
                                                    set_currentSelectedType(item);

                                                },
                                            })
                                        } else {
                                            set_currentSelectedType(item)
                                        }
                                    }}
                                >
                                    <div className='content'>
                                        <div className='name'>{item.groupName}</div>
                                    </div>

                                    <Dropdown menu={{ items: moreItems }} placement="bottom" onOpenChange={(bool) => { bool && set_currentEditLeftData(item) }}>
                                        <div className='more'>
                                            <img src={require('../../../../../static/more_point_gray.png')} alt="" />
                                        </div>
                                    </Dropdown>
                                </div>
                            )
                        })
                    }
                </div>
            </div>
            <div className='right'>
                <Tabs
                    defaultActiveKey="1"
                    onChange={onTabChange}
                    items={[
                        {
                            label: `核算单元`,
                            key: '1',
                        },
                        {
                            label: `二次分配项目`,
                            key: '2',
                        },
                    ]}
                />
                <div className='toolBar'>
                    <div className='filter'>
                        <div className='filterItem'>
                            <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                            <Input placeholder={currentTabKey == '1' ? '核算单元名称' : '请输入项目名称'} allowClear
                                suffix={
                                    <IconFont style={{ color: '#99A6BF' }} type="iconsousuo" onClick={() => getTableData({ keywords: tableDataSearchKeywords })} />
                                }
                                onChange={(e) => {
                                    set_tableDataSearchKeywords(e.target.value);
                                    if (e.target.value.length == 0) {
                                        getTableData({ keywords: '' });
                                    }
                                }}
                                onPressEnter={(e) => {
                                    getTableData({ keywords: tableDataSearchKeywords });
                                }}

                            />
                        </div>
                    </div>
                    <div className='btnGroup'>
                        {/* {currentTabKey == '1' ? <span className='manaBtn' onClick={() => addGroupEmpHandle()}>添加</span> : <AddItemComponent />} */}

                        <span className='manaBtn' onClick={() => addGroupEmpHandle()}>添加</span>
                    </div>
                </div>
                {currentTabKey == '2' && (
                    <div className={totalWeight != 1?'toolTip red':'toolTip'}>
                        占比总和必须为1，当前占比总和为<span style={{ color: totalWeight != 1 ? 'red' : '#00CC99', marginRight: 20 }}>{totalWeight}</span>
                    </div>
                )}

                <div style={{ marginTop: 16 }}>
                    {(currentSelectedType && currentTabKey) && <BMSTable actionRef={tableRef} columns={tableColumns}
                        rowKey='id'
                        tableAlertRender={false}
                        rowSelection={{
                            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                            // 注释该行则默认不显示下拉选项
                            //selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT, Table.SELECTION_NONE,],
                            onChange: onTableSelectChange,

                        }}
                        tableAlertOptionRender={() => {
                            return (

                                <Space size={16}>
                                    <Popconfirm
                                        title="是否确认删除？"
                                        key="del"
                                        onConfirm={() => delTableDataHanfle()}
                                    >
                                        <a>批量删除</a>
                                    </Popconfirm>
                                </Space>
                            );
                        }}
                        scroll={{y:`calc(100vh - 270px)`}}
                        params={tableDataFilterParams}
                        dataSource={dataSource}
                        //request={currentTabKey == '1'?(params, sort, filter) => getTableData(params, sort, filter):undefined}
                        components={currentTabKey == '2' ? {
                            body: {
                                wrapper: DraggableContainer,
                                row: DraggableBodyRow,
                            },
                        } : undefined}
                    />}
                </div>
            </div>
            {
                tableSelectedKeys.length > 0 && (
                    <div className='bottomToolbar'>
                        <span className='leftAccount'>已选择<a>{tableSelectedKeys.length}</a>项</span>
                        <div className='btnGroup'>
                            <span className='cancel' onClick={() => tableRef.current?.clearSelected && tableRef.current?.clearSelected()}>取消选择</span>
                            <Popconfirm
                                title="是否确认删除？"
                                key="del"
                                onConfirm={() => delTableDataHanfle()}
                            >
                                <span className='batchDel'>批量删除</span>
                            </Popconfirm>

                        </div>
                    </div>
                )
            }

        </BMSPagecontainer >
    )
}


export default SecondaryDistriGroupSet;
