

/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-12-16 09:42:52
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-06-12 16:46:28
 * @FilePath: /BudgetManaSystem/src/pages/budgetMana/monthlySet/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */



import BMSPagecontainer from '@/components/BMSPageContainer';

import { useEffect, useImperativeHandle, useRef, useState } from 'react';
import './style.less';

import { TreeProps, Input, Modal, Transfer, Popconfirm, Table, message } from 'antd';
import { DataNode } from 'antd/es/tree';

import expandedIcon from '../../../../../static/treenode_open.png';
import closeIcon from '../../../../../static/treenode_collapse.png';
import { BMSTable } from '@/components/BMSTable';
import { ActionType, ProColumns} from '@ant-design/pro-components';
import { createFromIconfontCN } from '@ant-design/icons';
import { CheckUnitEmpMapTableDataType, delTableData,addMapEmp,getCheckUnitEmpMapTableDataByUnitClass,getMapEmpList, getTreeData, getTreeDataRespType } from './service';
import { TransferItem, TransferProps } from 'antd/es/transfer';

import difference from 'lodash/difference';



import 'dayjs/locale/zh-cn';

import React from 'react';
import DirectoryTree from 'antd/es/tree/DirectoryTree';
import { getDeepestTreeData } from '@/utils/tooljs';

import { ColumnsType, TableRowSelection } from 'antd/es/table/interface';

import '../../../../utils/zhongtaiB';
import '../../../../utils/zhongtaiC';

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

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




export type TableListItem = {
    key: number;
    name: string;
};


const CheckUnitDepMap: React.FC = () => {

    const [treeData, set_treeData] = useState<getTreeDataRespType[]>([]);
    const [tableColumn, set_tableColumn] = useState<ProColumns[]>([]);
    const [currentSelectedTreeNode, set_currentSelectedTreeNode] = useState<any | undefined>();

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

    const [tableData,set_tableData] = useState<CheckUnitEmpMapTableDataType[]>([]);

    const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
    const [searchValue, setSearchValue] = useState('');
    const [autoExpandParent, setAutoExpandParent] = useState(true);

    const tableRef = useRef<ActionType>();

    const column = [
        {
            title: '工号',
            dataIndex: 'account'
        },
        {
            title: '姓名',
            dataIndex: 'name',
        },
        {
            title: '人员类别',
            dataIndex: 'userCateName',
        },
        {
            title: '职务',
            dataIndex: 'jobTitleName',
        },
        {
            title: '职称',
            dataIndex: 'titleName',
        },
        {
            title: '岗位',
            dataIndex: 'positionName',
        },
        {
            title: '学历',
            dataIndex: 'degreeName',
        },
        // {
        //     title: '入职时间',
        //     dataIndex: 'entryTime',
        // },
        // {
        //     title: '在职',
        //     dataIndex: 'isOnServiceName',
        // },
        {
            title: '操作',
            key: 'option',
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableDataHandle(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },
    ];


    const delTableDataHandle = async (record: any) => {
        const resp: any = await delTableData(record.id);
        if (resp) {
            getTreeReqFunc();
            tableRef.current?.reload()
        }
    }



    const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
        // console.log('selected', selectedKeys, info);
        const { node } = info;
        set_currentSelectedTreeNode(node);
    };



    const getTableData = async (type: 'PERSON' | 'DEP' | 'CHARGE', params: any, sort: any, filter: any) => {
        // console.log({ currentSelectedTreeNode });
        // console.log({ params, sort, filter });

        if (currentSelectedTreeNode) {
            const resp = await getCheckUnitEmpMapTableDataByUnitClass({
                ...params,
                unitCode: currentSelectedTreeNode.code,

            });
            if (resp) {
                set_tableData(resp.list);
                return {
                    data: resp.list,
                    success: true,
                    total: resp.totalCount,
                    pageSize: resp.pageSize,
                    totalPage: resp.totalPage,
                }
            }
            return {
                data: [],
                success: true
            }

        }

        return []
    }


    const transferTableColumn: any[] = [
        {
            title: '工号',
            dataIndex: 'account',
            with: 100,
            ellipsis: true,
        },
        {
            title: '姓名',
            width: 120,
            dataIndex: 'name',
            ellipsis: true
        },
    ];

    const addHandle = () => {

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

        Modal.confirm({
            title: `添加单元对照科室(${currentSelectedTreeNode.name})`,
            icon: <></>,
            width: 750,
            okText: '确定',
            cancelText: '取消',
            centered: true,
            content: <TableTransfer
                ref={ref}
                record={currentSelectedTreeNode}
                leftColumns={transferTableColumn}
                rightColumns={transferTableColumn} dataSource={[]}
            ></TableTransfer>,
            onOk: () => {
                return ref.current && ref.current.save();
            }
        })
    }

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


        const [targetKeys, setTargetKeys] = useState<string[]>([]);
        const [datasource, set_datasource] = useState<any[]>([]);
        const [selectedKeys, setSelectedKeys] = useState<string[]>([]);

        //获取对照科室
        const getFuncList = async () => {
            const resp = await getMapEmpList();
            if (resp) {
                
                const defaultSelctedkeys = tableData.map((item: any) => item.userId);
        
                set_datasource([...resp,...tableData]);

                setTargetKeys(defaultSelctedkeys);

            }
        }

        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.userId));

                const result = {
                    unitCode:record.code,
                    unitType:record.unitType,
                    employee:needData
                };

                const resp = await addMapEmp(result);

                if (resp) {
                    message.success('添加成功！');
                    getTreeReqFunc();
                    tableRef.current?.reload();
                   
                }
            }
        }));

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

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

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


    const dataList: any[] = [];

    const getParentKey = (key: React.Key, tree: any[]): React.Key => {
        let parentKey: React.Key;
        for (let i = 0; i < tree.length; i++) {
            const node = tree[i];
            if (node.child) {
                if (node.child.some((item: { code: React.Key; }) => item.code === key)) {
                    parentKey = node.code;
                } else if (getParentKey(key, node.child)) {
                    parentKey = getParentKey(key, node.child);
                }
            }
        }
        return parentKey!;
    };


    const onTreeSearchKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {

        const { value } = e.target;
        const newExpandedKeys = dataList
            .map((item) => {
                if (item.name.indexOf(value) > -1) {
                    return getParentKey(item.code, treeData);
                }
                return null;
            });

        const b = newExpandedKeys.filter((item, i, self) => item && self.indexOf(item) === i);

        setExpandedKeys(newExpandedKeys as React.Key[]);
        setSearchValue(value);
        setAutoExpandParent(true);
    }


    const onExpand = (newExpandedKeys: React.Key[]) => {
        setExpandedKeys(newExpandedKeys);
        setAutoExpandParent(false);
    };

    const generateList = (data: any[]) => {
        for (let i = 0; i < data.length; i++) {
            const node = data[i];
            const { code, name } = node;
            dataList.push({ code, name });
            if (node.child) {
                generateList(node.child);
            }
        }
    };
    generateList(treeData as any);


    const getTreeReqFunc = async () => {
        const resp = await getTreeData();
        set_treeData(resp);
    }

    const tableDataSearchHandle = (paramName: string) => {

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

    }


    useEffect(() => {
        if(currentSelectedTreeNode&&currentSelectedTreeNode.unitType){
            tableRef.current?.reload();
        }
    }, [currentSelectedTreeNode]);




    useEffect(() => {
        //初始化左侧树结构数据后
        if(currentSelectedTreeNode) return;
        if (treeData?.length > 0) {

            if (treeData[0].child && treeData[0].child.length > 0) {
                const [node, nodeParent] = getDeepestTreeData(treeData[0], 'child');

                set_currentSelectedTreeNode(node);
                setExpandedKeys([nodeParent.code]);
            }
        }
    }, [treeData]);




    useEffect(() => {
        set_tableColumn(column as ProColumns[]);

        getTreeReqFunc();


    }, []);


    return (
        <div className='CheckUnitDepMap'>
            <div className='leftTree'>
                <div className='search'>
                    <Input
                        className='searchInput'
                        placeholder="请输入类目名称"
                        size='small'
                        allowClear

                        style={{ marginBottom: 16 }}
                        onChange={onTreeSearchKeyChange}
                        suffix={
                            <SearchIcon type='iconsousuo' />
                        }
                    />
                </div>
                {
                    treeData && treeData.length > 0 && currentSelectedTreeNode && (
                        <DirectoryTree
                            fieldNames={{ title: 'name', key: 'code',children:'child' }}
                            rootStyle={{ height: '100%', paddingBottom: 50, overflowY: 'scroll', overflowX: 'hidden' }}
                            onSelect={onSelect}
                            onExpand={onExpand}
                            expandedKeys={expandedKeys}
                            autoExpandParent={autoExpandParent}
                            selectedKeys={[currentSelectedTreeNode.code]}
                            blockNode={true}
                            icon={() => null}
                            titleRender={
                                (nodeData: any) => {
                                    const strTitle = nodeData.name as string;
                                    const index = strTitle.indexOf(searchValue);
                                    const beforeStr = strTitle.substring(0, index);
                                    const afterStr = strTitle.slice(index + searchValue.length);
                                    const title =
                                        index > -1 ? (
                                            <span style={{display:'flex',flexDirection:'row',justifyContent:'center',alignItems:'center'}}>
                                                {beforeStr}
                                                <span className={'site-tree-search-value'} style={{ color: 'red', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{searchValue}</span>
                                                {afterStr}
                                            </span>
                                        ) : (
                                            <span className={'strTitle'}>{strTitle}</span>
                                        );
                                    return <div style={{
                                        display: 'flex', flexDirection: 'row',
                                        width: '100%',
                                        justifyContent:'space-between', alignItems: 'center', height: 32,
                                        borderRadius: '4px',
                                        overflow: 'hidden',
                                        color: '#17181A',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'

                                    }}>
                                        {title}
                                        {!nodeData.map&&<span className={nodeData.unitType?'point lastChild':'point'}></span>}
                                    </div>
                                }
                            }
                            defaultSelectedKeys={[treeData[0].child[0].code]}
                            treeData={treeData as unknown as DataNode[]}
                            // treeData={treeDataNew}
                            switcherIcon={(props: any) => {
                                const { expanded } = props;
                                return !expanded ? <img style={{ width: 20, height: 20, position: 'relative', top: 5 }} src={expandedIcon} /> : <img style={{ width: 20, height: 20, position: 'relative', top: 5 }} src={closeIcon} />
                            }}
                        />
                    )
                }
            </div>
            {/* <div style={{width:16,height:'92vh',background:'#F5F7FA'}}></div> */}
            <div className='rightContent'>
                <BMSPagecontainer title={false} ghost>

                    <div className='content'>
                        <div className='tableToolbar'>
                            <div className='search'>
                                <span>检索：</span><Input className='searchInput' allowClear placeholder="请输入工号/姓名" onChange={(e) => {
                                    set_tableDataSearchKeywords(e.target.value);
                                    if (e.target.value.length == 0) {
                                          set_tableDataFilterParams({...tableDataFilterParams,empName:''});
                                    }
                                }} suffix={
                                    <IconFont type="iconsousuo" onClick={() => tableDataSearchHandle('empName')} />
                                } 

                                onPressEnter={(e) => {

                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        empName: (e.target as HTMLInputElement).value
                                    });
                                }}
                                />
                            </div>
                            <div className='btnGroup'>
                                <span className='add' onClick={()=>addHandle()}>添加</span>
                            </div>
                        </div>
                        {currentSelectedTreeNode && <BMSTable actionRef={tableRef} params={tableDataFilterParams} rowKey='id' columns={tableColumn} request={(params, sort, filter) => getTableData('CHARGE', params, sort, filter)} />}
                    </div>


                </BMSPagecontainer>
            </div>
        </div>
    );

};

export default CheckUnitDepMap;