/* 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 { connect } from 'react-redux';
import classnames from 'classnames';

import { appService } from '@/api';
import { useHistory } from '@wisdom-utils/runtime';
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 = props => {
  const history = useHistory();
  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 searchBox = 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 };
    });
  };

  const linkToMenu = menu => {
    const { menuUrl } = menu;
    console.log(props);
    history.push(`civweb4/${menuUrl}`);
  };

  const focusOutSearchInfo = e => {
    e.stopPropagation();
    let element = e.target;
    // 事件对象逐层网上找，只要不是菜单搜索信息内的就隐藏起来
    while (element && element !== page.current) {
      if (element === searchBox.current) return;
      element = element.parentNode;
    }
    setShowMenuInfo(false);
  };

  return (
    <div className={styles.commonMenu} ref={page} onClick={focusOutSearchInfo}>
      <Spin spinning={loading}>
        <div className={styles.searchWrapper}>
          <div className={styles.searchBox} ref={searchBox}>
            <div className={styles.searchTitle}>
              <i className="iconfont">&#xe611;</i>
              <span>我的常用菜单</span>
              <span>（{menus.length}）</span>
            </div>
            <div className={styles.searchInput}>
              <Input
                maxLength={50}
                width={400}
                placeholder="搜索功能菜单"
                onChange={e => {
                  setShowMenuInfo(true);
                  setSearchInfo(e.target.value);
                }}
                onFocus={() => setShowMenuInfo(true)}
              />
            </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} linkToMenu={linkToMenu} />
          ))}
        </div>
        <div className={styles.pageLogo}>
          <img src={pageLogo} alt="" />
        </div>
      </Spin>
    </div>
  );
};

const MenuCard = ({ menu, linkToMenu }) => {
  const { menuIcon, menuName, menuGroup, menuID, menuUrl, menuPic } = menu;
  return (
    <div className={styles.menuCard} onClick={() => linkToMenu(menu)}>
      {/* <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>
  );
};

const mapStateToProps = state => ({
  menu: state.getIn(['global', 'menu']),
});
export default connect(
  mapStateToProps,
  null,
)(CommonMenu);
