

/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-12-16 09:42:52
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-05-09 14:06:33
 * @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 { CheckUnitDepMapTableDataType, delTableData, addMapDep, getCheckUnitDepMapTableDataByUnitClass, getMapDepList, 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<CheckUnitDepMapTableDataType[]>([]);

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



    const tableRef = useRef<ActionType>();


    const column = [
        {
            title: '科室代码',
            dataIndex: 'deptCode'
        },
        {
            title: '科室名称',
            dataIndex: 'deptName',
        },
        {
            title: '类型',
            dataIndex: 'deptTypeName',
        },
        {
            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 getCheckUnitDepMapTableDataByUnitClass({
                ...params,
                unitCode: currentSelectedTreeNode.code,
                current:1,
                pageSize:500

            });
            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 []
    }



    interface DataType {
        key: string;
        title: string;
        description: string;
        disabled: boolean;
        tag: string;
    }


    const transferTableColumn: any[] = [
        {
            title: '科室名称',
            dataIndex: 'deptName',
            with: 100,
            ellipsis: true,
        },
        {
            title: '科室类型',
            width: 120,
            dataIndex: 'deptTypeName',
            ellipsis: true
        },
    ];

    const addHandle = () => {

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

        Modal.confirm({
            title: `添加单元对照科室(${currentSelectedTreeNode.name})`,
            icon: <></>,
            width: 750,
            centered: true,
            okText:'确定',
            cancelText:'取消',
            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 getMapDepList();
            if (resp) {


                const defaultSelctedkeys = tableData.map((item: any) => item.deptCode);
                const hasSelectedData = tableData.map((a: any) => ({ deptCode: a.deptCode, deptName: a.deptName, deptType: a.deptType, deptTypeName: a.deptTypeName }))

                set_datasource([...resp, ...hasSelectedData]);

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

                let uniqueArr = Array.from(new Set(needData.map(e => JSON.stringify(e)))).map(e => JSON.parse(e));

                const result = {
                    unitCode: record.code,
                    unitType: record.unitType,
                    department: uniqueArr
                };

                const resp = await addMapDep(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.deptCode}
                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(({ deptCode }) => deptCode);
                            const diffKeys = selected
                                ? difference(treeSelectedKeys, listSelectedKeys)
                                : difference(listSelectedKeys, treeSelectedKeys);
                            onItemSelectAll(diffKeys as string[], selected);
                        },
                        onSelect({ deptCode }, selected) {
                            onItemSelect(deptCode as string, selected);
                        },
                        selectedRowKeys: listSelectedKeys,
                    };

                    return (
                        <BMSTable
                            rowSelection={rowSelection}
                            columns={columns as TransferItem[]}
                            dataSource={filteredItems}
                            size="small"
                            rowKey={'deptCode'}
                            tableAlertRender={false}
                            pagination={{showLessItems:true,showSizeChanger:false,simple:true,pageSize:9,showTotal:()=>false}}
                            style={{ pointerEvents: listDisabled ? 'none' : undefined }}
                            onRow={({ deptCode, disabled: itemDisabled }) => ({
                                onClick: () => {
                                    if (itemDisabled || listDisabled) return;
                                    onItemSelect(deptCode as string, !listSelectedKeys.includes(deptCode 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();

        // function checkMap(node:any) {
        //     if (!node.child || node.child.length === 0) {
        //         // 如果当前节点没有子节点，说明是最里层的节点
        //         return node.map === false;
        //     } else {
        //         // 如果当前节点有子节点，递归遍历所有子节点
        //         let flag = false;  //子节点是否存在false
        //         for (let i = 0; i < node.child.length; i++) {
        //             if (checkMap(node.child[i])) {
        //                 // 如果子节点存在 map 为 false，设置当前节点的 map 为 false
        //                 flag = true;
        //                 break;
        //             }
        //         }
        //         return flag;
        //     }
        // }


        // function setParentMapVal(node:any,val:boolean) {
        //     if (!node.child) {
        //       // 如果当前节点没有子节点，则直接返回
        //       return;
        //     }
        
        //     for (let item of node.child) {
        //       // 递归处理子节点，将子节点的 map 属性改为 false
        //       node.map = val,
        //       setParentMapVal(item,val);
              
        //     }
        // }
          



        // const newData = resp.map((item: any) => {
        //        const flag = checkMap(item);
        //        console.log({flag});
        //        if(flag){
        //             //将所有父级map改为false
        //             setParentMapVal(item,false);
        //        }else{
        //             setParentMapVal(item,true);
        //        }
        //        return item;
        // });


        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');

                console.log({currentSelectedTreeNode});

                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>
                                                {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, deptName: '' });
                                    }
                                }} suffix={
                                    <IconFont type="iconsousuo" onClick={() => tableDataSearchHandle('deptName')} />
                                }
                                    onPressEnter={(e) => {

                                        set_tableDataFilterParams({
                                            ...tableDataFilterParams,
                                            deptName: (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;