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

const { TabPane } = Tabs;

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

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

export interface NavSelecterProps {
  onVisibleChange?: (t: boolean) => void;
  onChecked?: (t: NavSelecterItemType[]) => void;
  value?: NavSelecterItemType[] | Key[];
  data?: NavSelecterData[];
  title?: string;
  type?: number; // 1 默认 2 限制最多可选个数
  resetHandleType?: 'default' | 'request';
}

const NavSelecter: React.FC<NavSelecterProps> = ({ onVisibleChange, data, value = [], onChecked, title, type = 1, resetHandleType = 'default' }) => {
  const [checkedIds, setCheckedIds] = useState<(string | number)[]>([]);

  const onChange = (tab: NavSelecterData) => {
    let updatedCheckedIds = [...checkedIds];

    if (updatedCheckedIds.includes(tab.menuId)) {
      updatedCheckedIds = updatedCheckedIds.filter((id) => id !== tab.menuId);
    } else {
      if (type === 2 && updatedCheckedIds.length >= 6) {
        message.warn('快速入口最多展示6项');
        return;
      }
      updatedCheckedIds.push(tab.menuId);
    }

    setCheckedIds(updatedCheckedIds);
  };

  const onMaskClick = () => {
    onVisibleChange && onVisibleChange(false);
  };

  const onCommit = () => {
    if (data) {
      const selectedItems: any[] = [];
      data.forEach((tree) => {
        const nodes = findNodesBySomes(tree, new Set(checkedIds), 'menuId');
        if (nodes) {
          nodes.forEach((node) => {
            selectedItems.push({
              name: node.name,
              menuId: node.menuId,
              path: node.path,
              type: node.type,
              contentType: node.contentType,
              systemId: node.systemId || `${node.menuId}`,
            });
          });
        }
      });
      onChecked && onChecked(selectedItems);
    }
    onVisibleChange && onVisibleChange(false);
  };

  const onReset = async () => {
    if (data && resetHandleType != 'default') {
      const needDelItemIds: string[] = (value as NavSelecterItemType[]).map((a) => a.id);
      const resp = await removeFastEntrance(needDelItemIds);
      if (resp) {
        setCheckedIds([]);
      }
    } else {
      setCheckedIds([]);
    }
  };

  const checkAllHandle = (e: CheckboxChangeEvent) => {
    if (e.target.checked && data) {
      const allIds: (string | number)[] = [];
      data.forEach((item) => {
        const leafNodes = getLeafNodes({ child: item.child });
        leafNodes.forEach((leaf) => allIds.push(leaf.menuId));
      });
      if (type === 2 && allIds.length > 6) {
        message.warn('快速入口最多展示6项');
        return;
      }
      setCheckedIds(allIds);
    } else {
      setCheckedIds([]);
    }
  };

  useEffect(() => {
    if (resetHandleType == 'request') {
      setCheckedIds((value as NavSelecterItemType[]).map((a) => a.menuId));
    } else {
      setCheckedIds(value as Key[]);
    }
  }, [value]);

  const getCheckedItems = (): NavSelecterItemType[] => {
    const selectedItems: NavSelecterItemType[] = [];
    if (data) {
      data.forEach((tree) => {
        const nodes = findNodesBySomes(tree, new Set(checkedIds), 'menuId');
        if (nodes) {
          nodes.forEach((node) => {
            selectedItems.push({
              id: node.id,
              name: node.name,
              menuId: node.menuId,
              path: node.path,
              type: node.type,
              contentType: node.contentType,
              systemId: node.systemId || `${node.menuId}`,
            });
          });
        }
      });
    }
    return selectedItems;
  };

  const checkedItems = getCheckedItems();

  return (
    <div className="navSelecter" onClick={onMaskClick}>
      <div className="container">
        <div className="selecterTitle">{title}</div>
        <div className="closeBtn" onClick={onMaskClick}>
          <img src={require('./images/close.png')} alt="Close" />
        </div>
        <div className="content" onClick={(e) => e.stopPropagation()}>
          <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,
                                      contentType: a.contentType,
                                      systemId: a.systemId,
                                    })
                                  }
                                  checked={checkedIds.includes(a.menuId)}
                                />
                                <span
                                  style={{
                                    display: 'inline-block',
                                    width: '75%',
                                    marginLeft: 8,
                                    whiteSpace: 'nowrap',
                                    textOverflow: 'ellipsis',
                                    overflow: 'hidden',
                                  }}
                                >
                                  {a.name}
                                </span>
                              </div>
                            );
                          }
                          return null;
                        })}
                      </div>
                    </div>
                  ))}
                </div>
              </TabPane>
            ))}
          </Tabs>
        </div>
        <div className="footer" onClick={(e) => e.stopPropagation()}>
          <span className="count">
            {type === 1 && <Checkbox onChange={checkAllHandle}>全部开启</Checkbox>}
            {type === 1 && <span className="count">{`已选中${checkedIds.length}项`}</span>}
            {type === 2 && `当前快速入口已展示${checkedItems.length}/6项`}
          </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;
