/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-01-15 16:08:08
 * @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 { getPubDicData } from '@/services/getDic';
import { createFromIconfontCN, MenuOutlined } from '@ant-design/icons';

import { ActionType, useRefFunction } from '@ant-design/pro-components';

import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Modal, Popconfirm, Table, Tabs, Transfer } from 'antd';
import { ColumnsType, TableRowSelection } from 'antd/es/table/interface';
import { TransferItem, TransferProps } from 'antd/es/transfer';
import { difference } from 'lodash';
import React, { useImperativeHandle } from 'react';
import { useEffect, useRef, useState } from 'react'

import {arrayMoveImmutable} from 'array-move';



import { addData, delData, getData, getTransferTableData, saveScoreData, TableItemDataType } from './service';

import './style.less';

import {
    SortableContainer,
    SortableElement,
    SortableHandle,
} from 'react-sortable-hoc';

import '../../../../utils/zhongtaiB';
const IconFont = createFromIconfontCN({
    scriptUrl: '',
});




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




export default function OccupationsSecondaryDistriSet() {

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const tableRef = useRef<ActionType>();

    const [ifAdjustment, set_ifAdjustment] = useState(false);

    const [data, set_data] = useState<TableItemDataType[]>([]);

    const [tabs, set_tabs] = useState<{ label: string, key: string }[]>([]);

    const [currentTab, set_currentTab] = useState<{ key: string, label: string } | undefined>(undefined);

    const [dataSource, set_dataSource] = useState<any[]>([]);

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

    const [columns, set_columns] = useState<ProColumns[]>([]);


    const static_columns: ProColumns[] = [

        {
            title: '项目名称',
            width: 160,
            dataIndex: 'secondItemName',
        },
        {
            title: '评价方式',
            width: 160,
            dataIndex: 'evaluationName',
        },
        {
            title: '来源',
            width: 160,
            dataIndex: 'sourceName',
        },
        {
            title: '操作',
            key: 'option',
            width: 200,
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    // <UpDataActBtn key={'SCORE'} record={record} type='SCORE' />,
                    // <UpDataActBtn key={'act'} record={record} type='EDIT' />,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableData(record)}
                    >
                        <a>移除</a>
                    </Popconfirm>
                ]
            },
        },

    ]


    const getTableData = async () => {
        const resp = await getData();
        if (resp) {
            set_data(resp);
        }
        return []
    }

    const delTableData = async (record: any) => {
        const resp = await delData([record.id]);
        if (resp) {
            message.success('操作成功！');
            getTableData();
            // message.success('操作成功!');
        }
    }

    const saveTableData = async () => {
        let newDataSource = dataSource.map((a: any, index: number) => {
            //更新排序
            return { ...a, sort: index + 1 }
        });

        const resp = await addData({
            unitTypeCode: currentTab?.key,
            unitTypeName: currentTab?.label,
            secondItemMap: newDataSource
        });

        if (resp) {
            message.success('操作成功！');
            set_ifAdjustment(false);
            getTableData();
        }

    }


    interface TableTransferProps extends TransferProps<TransferItem> {
        leftColumns: ColumnsType<any>;
        rightColumns: ColumnsType<any>;
    }


    const transferTableColumn = [
        {
            title: '项目名称',
            dataIndex: 'name',
        },
        {
            title: '评价方式',
            dataIndex: 'evaluationName',

        },
    ]


    const addFuncHandle = () => {

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

        Modal.confirm({
            title: `选择二次分配`,
            icon: <></>,
            width: 640,
            okText: '确定',
            cancelText: '取消',
            centered:true,
            content: <TableTransfer
                ref={ref}
                leftColumns={transferTableColumn}
                rightColumns={transferTableColumn}
            ></TableTransfer>,
            onOk: () => {
                return ref.current && ref.current.save();
            }
        })
    }

    const TableTransfer = React.forwardRef(({ leftColumns, rightColumns, ...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 getFuncList = async () => {
            const resp = await getTransferTableData(currentTab ? currentTab.key : '');
            if (resp) {
                
                if(dataSource){
                    const defaultSelctedkeys = dataSource.map((item: any) => item.secondItemCode);
                    set_datasource([...resp, ...(dataSource.map((a: any) => ({ ...a, name: a.secondItemName, code: a.secondItemCode })))]);
                    setTargetKeys(defaultSelctedkeys);
                }else{
                    set_datasource([...resp]);
                }
                
            }
        }

        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 needData = datasource.filter(item => targetKeys.includes(item.code));
                needData.reverse();
                const result = needData.map((a, index) => ({
                    secondItemCode: a.code,
                    secondItemName: a.name,
                    evaluation: a.evaluation,
                    source: a.source,
                    sort: a.sort ? a.sort : index
                }))

                const resp = await addData({
                    unitTypeCode: currentTab?.key,
                    unitTypeName: currentTab?.label,
                    secondItemMap: result
                });
                if (resp) {
                    message.success('操作成功！');
                    getTableData();
                }
            }
        }));

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

        return (
            <Transfer className='TableTransfer' showSearch
                titles={['待选项', '已选项']}
                locale={{
                    itemUnit: '项',
                    itemsUnit: '项',
                    searchPlaceholder: '请输入',
                }}
                oneWay={true}
                onChange={onChange}
                onSelectChange={onSelectChange}
                dataSource={datasource}
                rowKey={record => record.code}
                targetKeys={targetKeys}
                selectedKeys={selectedKeys}
                filterOption={(inputValue, item) => {
                    return item.unitName!.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(({ code }) => code);
                            const diffKeys = selected
                                ? difference(treeSelectedKeys, listSelectedKeys)
                                : difference(listSelectedKeys, treeSelectedKeys);
                            onItemSelectAll(diffKeys as string[], selected);
                        },
                        onSelect({ code }, selected) {
                            onItemSelect(code as string, selected);
                        },
                        selectedRowKeys: listSelectedKeys,
                    };

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


    const tableDataSearchHandle = (paramName: string) => {

        set_tableDataFilterParams({
            ...tableDataFilterParams,
            [`${paramName}`]: tableDataSearchKeywords
        })
    }


    const onTabChange = (activeKey: string) => {
        const need = tabs.filter(a => a.key == activeKey);

        need.length > 0 && set_currentTab(need[0]);
    }

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

    const delTableDataHanfle = async (record?: { id: number; }) => {
        const resp = await delData(tableSelectedKeys);
        if (resp) {
            message.success('操作成功！');
            set_tableSelectedKeys([]);
            getTableData();
        }
    }

    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 }))
                set_dataSource([...updatedSortArr])
            }
        },
    );

    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(()=>{
        //搜索
       
        if(tableDataFilterParams){
              const {name} = tableDataFilterParams;
              if(name.length>0){
                const results = dataSource.filter(a=>a.secondItemName.indexOf(name) != -1 );
                set_dataSource([...results]);
              }else{
                getTableData();
              }
        }
    },[tableDataFilterParams]);


    useEffect(() => {
        if (currentTab) {
            const result = data.filter((a: any) => a.unitTypeCode == currentTab.key);
            if (result.length > 0) {
                set_dataSource(result[0].secondItemMap)
            }
        }
    }, [currentTab])

    useEffect(() => {
        if (data) {
            const tabs = data.map((a: any) => ({ key: a.unitTypeCode, label: a.unitTypeName }));
            set_tabs(tabs);
            if (tabs.length > 0 && !currentTab) {
                //已选择了，保留当前选择的tab
                set_currentTab({ label: tabs[0].label, key: tabs[0].key });
            } else {
                const result = data.filter((a: any) => a.unitTypeCode == currentTab?.key);
                if (result.length > 0) {
                    set_dataSource(result[0].secondItemMap)
                }
            }

        }
    }, [data]);

    useEffect(() => {
        if (ifAdjustment) {
            set_columns([{
                title: '排序',
                dataIndex: 'sort',
                width: 60,
                className: 'drag-visible',
                render: () => <DragHandle />,
            }, ...columns])
        }else{
            set_columns([...(columns.filter((a)=>a.title != '排序'))]);
        }
    }, [ifAdjustment]);

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

    return (
        <BMSPagecontainer className='OccupationsSecondaryDistriSet' title={false}>
            <Tabs
                defaultActiveKey="1"
                onChange={onTabChange}
                items={tabs}
            />
            <div className='toolBar'>
                <div className='filter'>
                    <div className='filterItem'>
                        <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                        <Input placeholder={'请输入项目名称'} allowClear
                            suffix={
                                <IconFont style={{color:'#99A6BF'}} type="iconsousuo" onClick={() => tableDataSearchHandle('name')} />
                            }
                            onChange={(e) => {
                                set_tableDataSearchKeywords(e.target.value);
                                if (e.target.value.length == 0) {
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        name: ''
                                    });
                                }
                            }}
                            onPressEnter={(e) => {

                                set_tableDataFilterParams({
                                    ...tableDataFilterParams,
                                    name: (e.target as HTMLInputElement).value
                                });
                            }}

                        />
                    </div>
                </div>
                <div className='btnGroup'>
                    {!ifAdjustment && <span className='set' onClick={() => set_ifAdjustment(true)}>调整</span>}
                    {ifAdjustment && <>
                        <span className='set' onClick={() => set_ifAdjustment(false)}>取消</span>
                        <span className='save' onClick={() => saveTableData()}>保存</span>
                    </>
                    }
                </div>
            </div>
            <div style={{ marginTop: 16 }}>
                <BMSTable columns={columns as ProColumns[]} actionRef={tableRef} rowKey='id'
                    params={tableDataFilterParams} dataSource={dataSource}
                    tableAlertRender={false}
                    pagination={false}
                    rowSelection={ifAdjustment ? false : {
                        // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                        // 注释该行则默认不显示下拉选项
                        //selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                        onChange: onTableSelectChange,
                    }}

                    components={ifAdjustment ? {
                        body: {
                            wrapper: DraggableContainer,
                            row: DraggableBodyRow,
                        },
                    } : undefined}
                />
                {!ifAdjustment && <div className='bottomAddBtn' onClick={() => addFuncHandle()}>新增</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>
    )
}


