/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-06-29 11:05:04
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-08-25 15:43:54
 * @FilePath: /KC-MiddlePlatform/src/components/NavSelecter/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */




import { Tabs, Checkbox, Button } from 'antd';
import React, { Key, useEffect, useState } from 'react';
import './style.less';
import { findNodesBySomes, getLeafNodes } from '@/utils';

const { TabPane } = Tabs;



export type NavSelecterItemType = {
    name: string;
    menuId: number | string;
    path: string;
    type: number;
    systemId: string;
}


export type NavSelecterData = {
    name: string;
    menuId: number | string;
    path: string;
    systemId: string;
    type: number;
    child?: NavSelecterData[]
}

export interface NavSelecter {
    onVisibleChange?: (t: boolean) => void;
    onChecked?: (t: NavSelecterItemType[]) => void;
    value?: Key[];
    data?: NavSelecterData[];
    title?: string,
}

const NavSelecter = (props: NavSelecter) => {

    const { onVisibleChange, data, value = [], onChecked, title } = props;
    const [checkedIds, set_checkedIds] = useState<(string | number)[]>([]);
    const [checkedItems, set_checkedItems] = useState<NavSelecterItemType[]>([]);


    const onChange = (tab: NavSelecterItemType) => {
        
        let _checkedIds = [...checkedIds];
        let _checkedItems = [...checkedItems];

        if (_checkedIds.includes(tab.menuId)) {

            _checkedIds.splice(checkedIds.indexOf(tab.menuId), 1);
            _checkedItems.splice(_checkedItems.findIndex(t => t.menuId == tab.menuId), 1);
            set_checkedIds([..._checkedIds]);
            set_checkedItems([..._checkedItems]);
        } else {

            _checkedIds.push(tab.menuId);
            _checkedItems.push(tab);
            set_checkedItems([..._checkedItems]);
            set_checkedIds([..._checkedIds]);
        }
    };

    const onMaskClick = (e: React.MouseEvent) => {
        onVisibleChange && onVisibleChange(false);
    }

    const onCommit = () => {
        onChecked && onChecked(checkedItems);
        onVisibleChange && onVisibleChange(false);
    }

    const onReset = () => {
        set_checkedItems([]);
        set_checkedIds([]);
    }

    const checkAllHandle = (e: any) => {

        let all: any[] = [];

        if (e.target.checked) {
            data?.forEach((item) => {
                const _result = getLeafNodes({ child: item.child });
                all = [...all, ..._result]
            });
            set_checkedItems([...all]);
            set_checkedIds(all.map(a => a.menuId));
        } else {
            set_checkedItems([]);
            set_checkedIds([]);
        }

    }

    useEffect(() => {
        if (data) {
          
            let result: any[] = [];

            for (let tree of data) {
                const node = findNodesBySomes(tree,new Set(checkedIds),'menuId');
                if (node) {
                    result = result.concat([...node]);
                }
            }
            set_checkedItems(result);
    
        }
    }, [checkedIds]);

    useEffect(() => {

        set_checkedIds(value);
        
    }, [value]);



    return (
        <div className="navSelecter" onClick={(e) => onMaskClick(e)}>
            <div className='container'>
                <div className='selecterTitle'>{title}</div>
                <div className='closeBtn' onClick={(e) => onMaskClick(e)}>
                    <img src={require('./images/close.png')} />
                </div>
                <div className='content' onClick={(e) => e.stopPropagation()}>
                    <div>
                        <Tabs defaultActiveKey="1" >

                            {
                                data?.map((val) => (

                                    <TabPane tab={`${val.name}(${(getLeafNodes({ child: val.child })).length})`} key={val.menuId}>
                                        <div className='contentInner'>
                                            {
                                                val.child?.map((item) => (
                                                    <div className='row' key={item.menuId}>
                                                        <div className='rowName'>{item.name}</div>
                                                        <div className='rowWrap'>
                                                            {
                                                                item.child?.map(a => {
                                                                    if (a.type == 3||a.type == 1) {
                                                                        return (
                                                                            <div className='tab' key={a.menuId}>
                                                                                <Checkbox onChange={() => onChange({
                                                                                    name: a.name,
                                                                                    menuId: a.menuId,
                                                                                    path: a.path,
                                                                                    type: a.type,
                                                                                    systemId: a.systemId
                                                                                })} checked={checkedIds.includes(a.menuId)} ></Checkbox>
                                                                                <span style={{ display:'inline-block',width:'75%',marginLeft: 8,whiteSpace:'nowrap',textOverflow:'ellipsis',overflow:'hidden' }}>{a.name}</span>
                                                                            </div>
                                                                        )
                                                                    }
                                                                })
                                                            }
                                                        </div>
                                                    </div>
                                                ))
                                            }
                                        </div>
                                    </TabPane>

                                ))
                            }

                        </Tabs>
                    </div>
                </div>
                <div className='footer' onClick={e => e.stopPropagation()}>
                    <span className='count'>
                        <Checkbox onChange={(e) => checkAllHandle(e)}>全部开启 </Checkbox>
                        {`已选中${checkedItems.length}项`}
                    </span>
                    <div className='btnGroup'>
                        <Button className='resetBtn btn' style={{ marginRight: 8 }} onClick={onReset}>重置</Button>
                        <Button className='confirmBtn btn' type="primary" onClick={onCommit}>确定</Button>
                    </div>
                </div>
            </div>
        </div>
    )
}


export default NavSelecter;