/* eslint-disable no-useless-constructor */
import React, { useState, useEffect, useRef } from 'react';
import { Link } from 'react-router-dom';
import { Input, Button, Tree, notification, Spin, message } from 'antd';
import classnames from 'classnames';

import { appService } from '@/api';
import { savePagePartInfo } from '@/api/service/base';
import styles from './index.less';
import thumbnail from '../../assets/images/commonMenu/常用菜单.png';
import pageLogo from '../../assets/images/commonMenu/page-logo.png';

// 是否是灰色的图标（灰色图标在白色背景中看不见，添加滤镜变色）
const isNeedFilterIcon = (icon = '') => {
  return !icon.includes('一级') && !icon.includes('ios/');
};

const CommonMenu = () => {
  const [menus, setMenus] = useState([]); // 常用菜单信息
  const [widgets, setWidgets] = useState([]); // 菜单列表信息
  const [showMenuInfo, setShowMenuInfo] = useState(false); // 菜单列表显示隐藏
  const [loading, setLoading] = useState(true); // loading显示隐藏
  const [searchInfo, setSearchInfo] = useState('');
  const page = useRef(null);

  const defaultSubmitMenu = () => {
    let submitData = [];
    submitData = menus.map(item => ({
      PartID: item.menuID,
      PartName: item.menuName,
      PartUrl: item.menuUrl,
      icon: item.menuIcon,
    }));
    return submitData;
  };

  /**
   * 添加、删除菜单
   * @param {string} opr add/delete，添加/删除
   * @param {object} extData { groupName, label, icon, url, product }，操作的菜单信息widget
   */
  const updateCommonMenu = (opr, extData) => {
    const { groupName, label, icon, url, product } = extData;
    setLoading(true);
    let submitData = defaultSubmitMenu();
    if (opr === 'add') {
      submitData.push({
        PartID: `${groupName}_${label}`,
        PartName: label,
        PartUrl: url,
        icon,
      });
    } else if (opr === 'delete') {
      submitData = submitData.filter(
        item => item.PartID !== `${groupName}_${label}`,
      );
    }
    savePagePartInfo({
      query: {
        UserID: window.globalConfig?.userInfo?.OID ?? '',
      },
      data: submitData,
    }).then(res => {
      if (res.statusCode === '0000') {
        message.success('修改常用菜单成功!');
        fetchMenus();
      } else {
        message.error('修改常用菜单失败!');
      }
    });
  };

  /**
   * 渲染自定义树节点
   * @param {object} node 树节点信息，至少包含key, title, extData, children
   * @returns {ReactDOM} 返回自定义节点DOM
   */
  const renderTitle = node => {
    const { key, title, extData = {}, children } = node;
    const { icon, isMenu, isAdded } = extData;
    return (
      <div className={styles.customTitle}>
        <div
          className={classnames(
            styles.titleInfo,
            isNeedFilterIcon(icon) ? styles.filterIconBox : '',
          )}
        >
          <span className={styles.iconBox}>
            <img src={icon} alt="" />
          </span>
          <span>{title}</span>
        </div>
        {isMenu && (
          <div className={styles.titleControl}>
            {isAdded ? (
              <div>
                <p className={styles.chooseLabel}>已添加</p>
                <div
                  className={styles.chooseBtn}
                  onClick={e => {
                    e.stopPropagation();
                    updateCommonMenu('delete', extData);
                  }}
                >
                  取消添加
                </div>
              </div>
            ) : (
              <div>
                <div
                  className={styles.chooseBtn}
                  onClick={e => {
                    e.stopPropagation();
                    updateCommonMenu('add', extData);
                  }}
                >
                  添加
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    );
  };

  const getWidgets = addedmenus => {
    const isAddedMenu = widget => {
      const menuTmp = addedmenus.find(
        item =>
          item.menuGroup === widget.extData.groupName ||
          item.menuName === widget.extData.label,
      );
      return !!menuTmp;
    };
    const deepWidgets = (allWidgets, newWidgets, deep, groupName) => {
      allWidgets &&
        allWidgets.forEach((item, index) => {
          const newWidget = {
            title: item.label,
            key:
              item.url === undefined
                ? `${groupName}_${item.label}`
                : `${groupName}_${item.url}`,
            // icon: <MehOutlined />,
            children: [],
            extData: {
              ...item,
              icon: `https://panda-water.cn/web4/${item.icon}`,
              isMenu: item.url !== undefined,
              groupName:
                item.url === undefined
                  ? `${groupName}_${item.label}`
                  : groupName,
            },
          };
          newWidget.extData.isAdded = isAddedMenu(newWidget);
          newWidgets.push(newWidget);
          deepWidgets(
            item.widgets,
            newWidget.children,
            deep + 1,
            item.url === undefined ? `${groupName}_${item.label}` : groupName,
          );
        });
    };
    // 所有的可选菜单
    const { allWidgets = [] } = window.globalConfig;
    const newWidgets = [];
    deepWidgets(
      allWidgets,
      newWidgets,
      1,
      `widget_${window.globalConfig.client}`,
    );
    return newWidgets;
  };

  const fetchMenus = () => {
    appService
      .getPagePartInfo({
        UserID: window?.globalConfig?.userInfo?.OID ?? '',
      })
      .then(res => {
        setLoading(false);
        if (res.say.statusCode !== '0000')
          return notification.error({
            message: '服务错误',
            description: res.say.errMsg,
          });
        const newMenus = [];
        // 过滤出当前client的菜单
        const data = res.getMe.filter(item => {
          const client = item.PartID.split('_')[1] ?? '';
          return client === window.globalConfig.client;
        });
        data.forEach(item => {
          const newMenu = {
            menuIcon: '',
            menuName: '',
            menuGroup: '',
            menuID: '',
            menuUrl: '',
            menuPic: '',
          };
          newMenu.menuIcon = item.icon;
          newMenu.menuName = item.PartName;
          const PartIDArr = item.PartID.split('_');
          newMenu.menuGroup = PartIDArr.splice(2, PartIDArr.length - 3).join(
            '_',
          );
          newMenu.menuID = item.PartID;
          newMenu.menuUrl = item.PartUrl;
          newMenu.menuPic = item.BgPicUrl;
          newMenus.push(newMenu);
        });
        setMenus(newMenus);
        const w = getWidgets(newMenus);
        setWidgets(w);
      })
      .catch(error => {
        notification.error({
          message: '服务错误',
          description: error,
        });
      });
  };

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

  const loop = data => {
    return data.map(item => {
      const index = item.title.indexOf(searchInfo);
      const beforeStr = item.title.substr(0, index);
      const afterStr = item.title.substr(index + searchInfo.length);
      const title =
        index > -1 ? (
          <span>
            {beforeStr}
            <span className={styles.treeSearchInfo}>{searchInfo}</span>
            {afterStr}
          </span>
        ) : (
          <span>{item.title}</span>
        );
      if (item.children) {
        return { ...item, title, children: loop(item.children) };
      }
      return { ...item, title };
    });
  };

  return (
    <div
      className={styles.commonMenu}
      ref={page}
      onClick={e => {
        e.stopPropagation();
        if (e.target === page.current) setShowMenuInfo(false);
      }}
    >
      <Spin spinning={loading}>
        <div className={styles.searchWrapper}>
          <div className={styles.searchBox}>
            <div className={styles.searchTitle}>
              <i className="iconfont">&#xe611;</i>
              <span>我的常用菜单</span>
              <span>（{menus.length}）</span>
            </div>
            <div>
              <div className={styles.searchInput}>
                <Input.Search
                  placeholder="搜索功能菜单"
                  // onFocus={() => setShowMenuInfo(true)}
                  onSearch={info => {
                    setShowMenuInfo(true);
                    setSearchInfo(info);
                  }}
                />
              </div>
            </div>
            <div
              className={classnames(
                styles.searchInfoBox,
                showMenuInfo ? '' : styles.searchInfoBox_hide,
              )}
            >
              <Tree
                height={400}
                showIcon
                defaultExpandAll
                defaultSelectedKeys={['0-0-0']}
                // switcherIcon={<DownOutlined />}
                treeData={loop(widgets)}
                titleRender={renderTitle}
                selectable={false}
              />
            </div>
          </div>
          {/* <Button className={styles.searchBtn}>添加菜单</Button> */}
        </div>
        <div className={styles.menuCardWrapper}>
          {menus.map(item => (
            <MenuCard menu={item} />
          ))}
        </div>
        <div className={styles.pageLogo}>
          <img src={pageLogo} alt="" />
        </div>
      </Spin>
    </div>
  );
};

const MenuCard = ({ menu }) => {
  const { menuIcon, menuName, menuGroup, menuID, menuUrl, menuPic } = menu;
  return (
    <div className={styles.menuCard}>
      <Link to={menuUrl} title={menuName}>
        <img
          className={styles.cardThumbnail}
          src={menuPic || thumbnail}
          alt=""
        />
        <div className={styles.cardLabel}>
          <div
            className={classnames(
              styles.cardTitle,
              isNeedFilterIcon(menuIcon) ? styles.filterIconBox : '',
            )}
          >
            <span className={styles.iconBox}>
              <img className={styles.cardIcon} src={menuIcon} alt="" />
            </span>
            <span className={styles.cardName}>{menuName}</span>
          </div>
          <div className={styles.cardGroup}>{menuGroup}</div>
        </div>
      </Link>
    </div>
  );
};

export default CommonMenu;
