

/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-12-16 09:42:52
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-06-27 10:00:04
 * @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,useRef, useState } from 'react';
import './style.less';

import { TreeProps, Input,Popconfirm, 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, ModalForm, ProColumns, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { createFromIconfontCN } from '@ant-design/icons';
import { addCheckUnit, delTableData, editCheckUnit, getCheckUnitTableDataByUnitClass, getTreeData } from './service';




import 'dayjs/locale/zh-cn';

import React from 'react';
import DirectoryTree from 'antd/es/tree/DirectoryTree';
import { getDeepestTreeData } from '@/utils/tooljs';
import { CheckUnitClassTableDataType } from '../checkUnitClassMana/service';
import { getDataByKeyFromDic, getPubDicData } from '@/services/getDic';

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

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

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




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


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

    const [treeData, set_treeData] = useState<CheckUnitClassTableDataType[]>([]);
    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 [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
    const [searchValue, setSearchValue] = useState('');
    const [autoExpandParent, setAutoExpandParent] = useState(true);



    const tableRef = useRef<ActionType>();


    const column = [
        {
            title: '核算单元名称',
            dataIndex: 'unitName'
        },
        {
            title: '核算单元代码',
            dataIndex: 'code',
        },
        {
            title: '职类',
            dataIndex: 'unitTypeName',
        },
        {
            title: '特殊单元',
            dataIndex: 'specialUnit',
            render: (_: any, record: any) => {
                return record.specialUnit == 1 ? '是' : '否'
            }
        },
        {
            title: '单元分级',
            dataIndex: 'unitLevelName',
            // render: (_: any, record: any) => {
            //     return record.specialUnit == 1 ? '是' : '否'
            // }
        },
        {
            title: '系数',
            dataIndex: 'rate',
        },
        {
            title: '说明',
            dataIndex: 'description',
        },
        {
            title: '操作',
            key: 'option',
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <UpDataActBtn key={'act'} record={record} type='EDIT' />,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableDataHanfle(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },
    ];


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



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


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

        let flag = false;
        if (type == 'ADD') {
            const resp = await addCheckUnit({
                ...formVal,
                classCode: currentSelectedTreeNode.code,
                unitType: currentSelectedTreeNode.unitType
            });
            if (resp) {
                flag = true;
                tableRef.current?.reload();
                message.success('操作成功！');
            }

        }
        if (type == 'EDIT') {

            const resp = await editCheckUnit({
                ...formVal
            });
            if (resp) {
                flag = true;
                tableRef.current?.reload();
                message.success('操作成功！');
            }
        }
        return flag;

    }


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

        const [dicData, set_dicData] = useState<any[]>([]);

        const getDirecData = async (key?: string) => {

            const data = await getPubDicData();
            if (data) {
                set_dicData(data);
            }
        }

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

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}核算单元`}
                width={400}
                initialValues={type == 'EDIT' ? {
                    ...record,

                } : {}}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <span className='add'>新增</span>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val } : { ...val }, type);
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >
                <ProFormText
                    name="unitName"
                    label="核算单元名称："
                    placeholder="请输入"
                    rules={[{ required: true, message: '名称不能为空!' }]}
                />
                 <ProFormText
                    name="code"
                    label="核算单元代码："
                    placeholder="请输入"
                    rules={[{ required: true, message: '代码不能为空!' }]}
                />
                <ProFormRadio.Group
                    label="特殊单元"
                    name="specialUnit"
                    options={[{ label: '是', value: 1 }, { label: '否', value: 0 }]}
                    rules={[{ required: true, message: '特殊单元不能为空!' }]}
                />

                <ProFormSelect label="单元分级："
                    name='unitLevel'
                    options={(getDataByKeyFromDic(dicData, '4')).list}
                    rules={[{ required: true, message: '职类不能为空!' }]}
                />

                <ProFormTextArea
                    name="description"
                    label="说明："
                    placeholder="请输入"

                />
            </ModalForm>
        )
    }




    const getTableData = async (params: any, sort: any, filter: any) => {
        // console.log({ currentSelectedTreeNode });
        // console.log({ params, sort, filter });

        if (currentSelectedTreeNode) {
            const resp = await getCheckUnitTableDataByUnitClass({
                ...params,
                classCode: currentSelectedTreeNode.code,

            });
            if (resp) {

                return {
                    data: resp.list,
                    success: true,
                    total: resp.totalCount,
                    pageSize: resp.pageSize,
                    totalPage: resp.totalPage,
                }
            }
            return {
                data: [],
                success: true
            }

        }

        return []
    }



    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.children) {
                if (node.children.some((item: { code: React.Key; }) => item.code === key)) {
                    parentKey = node.code;
                } else if (getParentKey(key, node.children)) {
                    parentKey = getParentKey(key, node.children);
                }
            }
        }
        return parentKey!;
    };


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

        const { value } = e.target;
        const newExpandedKeys = dataList
            .map((item) => {
                if (item.className.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, className } = node;
            dataList.push({ code, className });
            if (node.children) {
                generateList(node.children);
            }
        }
    };
    generateList(treeData as any);


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

    const tableDataSearchHandle = (paramName: string) => {

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

    }


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




    useEffect(() => {
        //初始化左侧树结构数据后

        if (treeData?.length > 0) {

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

                set_currentSelectedTreeNode(node);
                setExpandedKeys([nodeParent.code]);
            }
            // else{
            //     set_currentSelectedTreeNode(treeData[0]);
            //     setExpandedKeys([treeData[0].code]);
            // }
        }
    }, [treeData]);




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

        getTreeReqFunc();

    }, []);


    return (
        <div className='CheckUnitMana'>
            <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: 'className', key: 'code' }}
                            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.className 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: 'flex-start', alignItems: 'center', height: 32,
                                        borderRadius: '4px',
                                        overflow: 'hidden',
                                        color: '#17181A',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'

                                    }}>{title}</div>
                                }
                            }
                            defaultSelectedKeys={[treeData[0].children[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, unitName: '' });
                                    }
                                }} suffix={
                                    <IconFont type="iconsousuo" onClick={() => tableDataSearchHandle('unitName')} />
                                }
                                    onPressEnter={(e) => {

                                        set_tableDataFilterParams({
                                            ...tableDataFilterParams,
                                            unitName: (e.target as HTMLInputElement).value
                                        });
                                    }}
                                />
                            </div>
                            <div className='btnGroup'>
                                <UpDataActBtn record type='ADD' />
                            </div>
                        </div>
                        {currentSelectedTreeNode && <BMSTable actionRef={tableRef} params={tableDataFilterParams} rowKey='id' columns={tableColumn} request={(params, sort, filter) => getTableData(params, sort, filter)} />}
                    </div>


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

};

export default CheckUnitMana;