webMenu.jsx 18.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
/* eslint-disable array-callback-return */
/* eslint-disable no-plusplus */
/* eslint-disable consistent-return */
import React, { useEffect, useState } from 'react';
import { notification, Tooltip, Modal, Spin, Empty } from 'antd';
import Tree from '@/components/ExpendableTree';
import {
  FileAddTwoTone,
  FolderAddTwoTone,
  FolderFilled,
  FileOutlined,
  DeleteTwoTone,
  DeliveredProcedureOutlined,
} from '@ant-design/icons';
import classnames from 'classnames';
import styles from './webMenu.less';
import AddForm from './AddForm';
import EditForm from './editForm';
import CheckList from './checkBox';
import ImportOrExport from './ImportOrExport';
import {
  addWebMenu, // 增
  deleteWebMenu, // 删
  editWebMenu, // 改
  getWebMenuInfo, // 查
  dragMenu, // 菜单拖拽
  getWebModuleTree,
  pEditWebMenu,
} from '@/services/webConfig/api';

const MiniMenu = props => {
  const { menu, configFiles, subSystemValue, updateMenuTree, userMode, webid, productList } = props;
  const [flag, setFlag] = useState(1); // 刷新标志
  const [loading, setLoading] = useState(false); // 加载
  const [menuID, setMenuID] = useState(''); // 选中的树ID
  const [nodeType, setNodeType] = useState(''); // 选中的节点类型
  const [info, setInfo] = useState({});
  const [importOrExportVisible, setImportOrExportVisible] = useState(false); // 导入导出弹窗
  const [addVisible, setAddVisible] = useState(false); // 新增弹窗
  const [addTwoVisible, setAddTwoVisible] = useState(false); // 编辑弹窗
  const [delVisible, setDelVisible] = useState(false); // 删除弹窗
  const [nodeObj, setNodeObj] = useState({});
  const [addType, setAddType] = useState(''); // 添加下级类型
  const [modalTitle, setModalTitle] = useState('');
  const [roleList, setRoleList] = useState([]); // 复选框选中的值
  const [modalLoading, setModalLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [newTreeList, setNewTreeList] = useState([]);

  const [menuList, setMenuList] = useState([]); // 菜单树

  /* *****************************************************  */
  const [curMenuType, setCurMenuType] = useState('');

  // 获取菜单信息
  useEffect(() => {
    getInfo();
  }, [menuID, webid]);
  useEffect(() => {
    getTree();
  }, []);
  useEffect(() => {
    getTree();
    return () => {
      setLoading(false);
    };
  }, [webid]);

  // 处理数据
  const mapTree = val => {
    const obj = { ...val };
    const hasChild = obj.children.length > 0;
    return {
      title: (
        <div className={styles.title}>
          <div>{obj.text}</div>
          <div className={styles.tip}>
            {obj.menuType === 'Web4MenuGroup' && (
              <Tooltip title="导入导出菜单组" className={styles.fs}>
                <DeliveredProcedureOutlined
                  style={{ color: '#178BF7' }}
                  onClick={e => importAndExport(obj, e)}
                />
              </Tooltip>
            )}
            {obj.menuType === 'Web4MenuGroup' && (
              <Tooltip title="新增菜单组" className={styles.fs}>
                <FolderAddTwoTone onClick={e => addMenuGroupTip(obj, e)} />
              </Tooltip>
            )}
            {obj.menuType === 'Web4MenuGroup' && (
              <Tooltip title="新增功能菜单" className={styles.fs}>
                <FileAddTwoTone onClick={e => addMenuTip(obj, e)} />
              </Tooltip>
            )}

            <Tooltip title="删除菜单" className={styles.fs}>
              <DeleteTwoTone onClick={e => deleteMenuTip(obj, e)} />
            </Tooltip>
          </div>
        </div>
      ),
      key: obj.menuID,
      icon: obj.menuType === 'Web4MenuGroup' ? <FolderFilled /> : <FileOutlined />,
      menuType: obj.menuType,
      children: hasChild ? obj.children.map(i => mapTree(i)) : [],
    };
  };
  // 树的点击事件
  const handleSelect = (prop, treeNode) => {
    if (treeNode) {
      const {
        node: { menuType },
      } = treeNode;
      setCurMenuType(menuType);
      switch (menuType) {
        case 'Web4MenuGroup':
          setNodeType(2);
          setAddType(2);
          break;
        default:
          setNodeType(1);
          setAddType(1);
          break;
      }
    }
    if (prop[0]) {
      setMenuID(prop[0]);
    }
  };

  const getInfo = id => {
    if (!menuID) {
      return;
    }
    setLoading(true);
    getWebMenuInfo({
      menuID,
      _dc: Date.now(),
    })
      .then(res => {
        setLoading(false);
        if (res.code === 0) {
          setInfo({ ...res.data });
        } else {
          notification.error({
            message: '提示',
            duration: 10,
            description: res.message || '获取失败',
          });
        }
      })
      .catch(err => {
        setLoading(false);
        console.error(err);
      });
  };
  // 删除的回调
  const deleteMenuTip = (val, e) => {
    e.stopPropagation();
    setModalTitle(val.text);
    setNodeObj(val);
    setDelVisible(true);
  };
  const delMenu = () => {
    setModalLoading(true);
    deleteWebMenu({
      menuID: nodeObj.menuID,
      _dc: Date.now(),
    })
      .then(res => {
        setModalLoading(false);
        if (res.code === 0) {
          setDelVisible(false);
          // setFlag(flag + 1);
          getTree();
          setNodeType('');
          setNodeObj('');
          // updateMenuTree('delete', nodeObj);
          notification.success({
            message: '提示',
            duration: 3,
            description: '删除成功',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 10,
            description: res.message || '删除失败',
          });
        }
      })
      .catch(err => {
        setModalLoading(false);
        console.error(err);
      });
  };
  // 导入导出菜单组
  const importAndExport = (val, e) => {
    e.stopPropagation();
    setNodeObj(val);
    setImportOrExportVisible(true);
  };
  // 新增菜单组
  const addMenuGroupTip = (val, e) => {
    e.stopPropagation();
    setModalTitle(`在${val.text}下新增菜单组`);
    setNodeObj(val);
    setAddType(2);
    setAddVisible(true);
  };
  const rootAddGroup = () => {
    setNodeObj('');
    setModalTitle('新增最上级菜单组');
    setAddType(2);
    setAddVisible(true);
  };
  // 新增功能菜单
  const addMenuTip = (val, e) => {
    e.stopPropagation();
    setNodeObj(val);
    setModalTitle(`在${val.text}下新增功能菜单`);
    setAddType(1);
    setAddTwoVisible(true);
  };
  const rootAdd = () => {
    setModalTitle('新增最上级功能菜单');
    setNodeObj('');
    setAddType(1);
    setAddTwoVisible(true);
  };
  const handleGeturl = val => {
    let url;
    const isSite = val.includes('CityTemp');
    if (isSite) {
      url = val;
    } else {
      url = localStorage.getItem('pd2-baseUrl') ? localStorage.getItem('pd2-baseUrl') + val : val;
    }
    return url;
  };
  // 导入或导出弹窗回调
  const onFinishCallBack = () => {};
  // 新增提交的回调
  const submitCallback = (prop, item) => {
    console.log(subSystemValue, 'subSystemValue');
    setSubmitLoading(true);
    let baseUrl = handleGeturl(prop.imageUrl);
    let obj = { ...prop, baseUrl };
    const parentID = item.menuID ? Number(item.menuID) : -1;
    addWebMenu({
      _dc: Date.now(),
      parentID,
      subSystemValue,
      ...obj,
    })
      .then(res => {
        setSubmitLoading(false);
        if (res.code === 0) {
          setAddVisible(false);
          setAddTwoVisible(false);
          // setFlag(flag + 1);
          getTree();
          // updateMenuTree('add', item);
          notification.success({
            message: '提示',
            description: '新增成功',
            duration: 3,
          });
        } else {
          notification.error({
            message: '提示',
            description: res.message || '新增失败',
            duration: 10,
          });
        }
      })
      .catch(err => {
        setSubmitLoading(false);
        console.error(err);
      });
  };
  // 编辑的回调
  const editSubmitCallback = prop => {
    setLoading(true);
    let baseUrl = handleGeturl(prop.imageUrl);
    let obj = { ...prop, baseUrl };
    if (nodeType === 1) {
      obj.relatedRoleList = String(roleList) || '';
      editWebMenu({
        _dc: Date.now(),
        menuID: Number(menuID),
        // subSystemValue,
        ...obj,
      })
        .then(res => {
          setLoading(false);

          if (res.code === 0) {
            // setFlag(flag + 1);
            getTree();
            // updateMenuTree('edit');
            notification.success({
              message: '提示',
              duration: 3,
              description: '编辑成功',
            });
          } else {
            notification.error({
              message: '提示',
              duration: 3,
              description: res.message || '编辑失败',
            });
          }
        })
        .catch(err => {
          // eslint-disable-next-line no-console
          console.error(err);
          setLoading(false);
        });
    } else {
      // 新接口改为editWebMenu 原来为pEditWebMenu
      editWebMenu({
        _dc: Date.now(),
        menuID: Number(menuID),
        // subSystemValue,
        ...obj,
        product: null,
        baseUrl: null,
        hideInMenu: false,
      })
        .then(res => {
          setLoading(false);

          if (res.code === 0) {
            // setFlag(flag + 1);
            getTree();
            // updateMenuTree('edit');
            notification.success({
              message: '提示',
              duration: 3,
              description: '编辑成功',
            });
          } else {
            notification.error({
              message: '提示',
              duration: 3,
              description: res.msg || '编辑失败',
            });
          }
        })
        .catch(err => {
          // eslint-disable-next-line no-console
          console.error(err);
          setLoading(false);
        });
    }
  };
  const valueCallback = val => {
    let arr = [...val];
    let arr2 = [];
    arr.map(item => {
      if (item.related) {
        arr2.push(item.relatedRoleCode);
      }
    });
    setRoleList(arr2);
  };
  // 返回拖拽完毕后的信息
  const loop = (data, key, parentID, callback) => {
    for (let i = 0; i < data.length; i++) {
      if (data[i].menuID === key) {
        return callback(data[i], i, data, parentID);
      }
      if (data[i].children) {
        loop(data[i].children, key, data[i].menuID, callback);
      }
    }
  };
  const getTree = () => {
    getWebModuleTree(userMode || 'super')
      .then(res => {
        setLoading(false);
        const { code, data } = res;
        if (code === 0) {
          let arr = data
            .filter(item => item.id === 'Web4SingleStation')
            .map(r => r.children.filter(i => i.id === webid))
            .flat(2);
          let arr2 = arr[0].children.find(item => item.text === '菜单管理').children || [];
          setMenuList(arr2 || []);
        }
      })
      .catch(err => {
        setLoading(false);
      });
  };
  // 树的拖动
  const handleDrop = infos => {
    const dropKey = infos.node.key;
    const dragKey = infos.dragNode.key;
    const dropPos = infos.node.pos.split('-');
    const dropPosition = infos.dropPosition - Number(dropPos[dropPos.length - 1]);

    const data = [...menuList];
    // 找到拖拽的元素
    let dragObj;
    let dropObj;
    let id;
    let dragList;
    loop(data, dropKey, -1, item => {
      dropObj = item;
    });
    loop(data, dragKey, -1, (item, index, arr) => {
      if (infos.dropToGap || dropObj.menuType !== 'Web4Menu') {
        arr.splice(index, 1);
        dragObj = item;
      }
    });
    if (!infos.dropToGap) {
      // Drop on the content
      loop(data, dropKey, -1, item => {
        item.children = item.children || [];
        if (item.menuType !== 'Web4Menu') {
          // where to insert 示例添加到头部,可以是随意位置
          item.children.unshift(dragObj);
          id = item.menuID;
          dragList = item.children.map(val => val.menuID);
        }
      });
    } else if (
      (infos.node.props.children || []).length > 0 && // Has children
      infos.node.props.expanded && // Is expanded
      dropPosition === 1 // On the bottom gap
    ) {
      loop(data, dropKey, -1, item => {
        item.children = item.children || [];
        // where to insert 示例添加到头部,可以是随意位置
        item.children.unshift(dragObj);
        id = item.menuID;
        dragList = item.children.map(val => val.menuID);
      });
    } else {
      let ar;
      let i;
      loop(data, dropKey, -1, (item, index, arr, parentID) => {
        ar = arr;
        i = index;
        id = parentID;
      });
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj);
      } else {
        ar.splice(i + 1, 0, dragObj);
      }
      dragList = ar.map(val => val.menuID);
    }
    // 如果拖拽到菜单下不做任何处理
    if (!dragList) {
      return;
    }
    console.log(dragList, 'dragList');
    dragMenu({
      menuID: dragKey,
      newParentID: id || -1,
      menuList: String(dragList) || '',
      _version: 9999,
      _dc: Date.now(),
    }).then(res => {
      if (res.code === 0) {
        // updateMenuTree();
        console.log(11111111);
        getTree();
        // setFlag(flag + 1);
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.message || '操作失败',
        });
      }
    });
  };
  return (
    <Spin spinning={loading} tip="loading...">
      <div
        className={classnames({
          [styles.box]: true,
        })}
      >
        <div
          className={classnames({
            [styles.left]: true,
          })}
        >
          <div
            className={classnames({
              [styles.leftTop]: true,
            })}
          >
            菜单列表
            <div className={classnames(styles.tRight)}>
              <Tooltip title="导入导出菜单组" className={styles.fs}>
                <DeliveredProcedureOutlined
                  style={{ color: '#178BF7', marginRight: '10px' }}
                  onClick={() => {
                    setNodeObj('');
                    setImportOrExportVisible(true);
                  }}
                />
              </Tooltip>
              <Tooltip title="新增最上级菜单组">
                <FolderAddTwoTone
                  className={`${styles.icon1} ${styles.icon}`}
                  onClick={() => rootAddGroup()}
                />
              </Tooltip>
              <Tooltip title="新增最上级功能菜单">
                <FileAddTwoTone
                  onClick={() => rootAdd()}
                  className={`${styles.icon2} ${styles.icon}`}
                />
              </Tooltip>
            </div>
          </div>
          {menuList.length > 0 && (
            <div style={{ height: 'calc(100vh - 240px)', overflowY: 'scroll' }}>
              <Tree
                showIcon
                onSelect={handleSelect}
                treeData={menuList.map(item => mapTree(item))}
                blockNode
                draggable
                autoExpandParent
                selectedKeys={[menuID]}
                onDrop={handleDrop}
                // expandedKeys={[menuID]}
              />
            </div>
          )}
        </div>
        <Modal
          visible={addVisible}
          title={modalTitle}
          bodyStyle={{ width: '100%', minHeight: '100px' }}
          style={{ top: 80 }}
          width="600px"
          destroyOnClose
          footer={null}
          cancelText="取消"
          okText="确认"
          maskClosable={false}
          onCancel={() => setAddVisible(false)}
          onConfirm={() => {
            submitCallback();
          }}
        >
          <AddForm
            nodeObj={nodeObj}
            addType={addType}
            configFiles={configFiles}
            submitCallback={submitCallback}
            submitLoading={submitLoading}
            productList={productList}
          />
        </Modal>
        <Modal
          visible={addTwoVisible}
          title={modalTitle}
          bodyStyle={{ width: '100%', minHeight: '100px' }}
          style={{ top: 80 }}
          width="600px"
          destroyOnClose
          footer={null}
          maskClosable={false}
          cancelText="取消"
          okText="确认"
          onCancel={() => setAddTwoVisible(false)}
        >
          <AddForm
            submitLoading={submitLoading}
            nodeObj={nodeObj}
            configFiles={configFiles}
            addType={addType}
            productList={productList}
            submitCallback={submitCallback}
          />
        </Modal>
        <Modal
          visible={delVisible}
          title="请确认"
          bodyStyle={{ width: '100%', minHeight: '100px' }}
          style={{ top: 80 }}
          width="400px"
          destroyOnClose
          cancelText="取消"
          okText="确认"
          maskClosable={false}
          onCancel={() => setDelVisible(false)}
          onOk={() => delMenu()}
          confirmLoading={modalLoading}
        >
          是否删除<span style={{ color: 'red' }}>{modalTitle}</span>?
        </Modal>
        <div
          className={classnames({
            [styles.middle]: true,
          })}
        >
          菜单配置
          {nodeType ? (
            <EditForm
              nodeType={nodeType}
              info={info}
              configFiles={configFiles}
              productList={productList}
              submitCallback={editSubmitCallback}
              valueCallback={valueCallback}
            />
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前未选中菜单" />
          )}
        </div>
        <ImportOrExport
          visible={importOrExportVisible}
          onFinish={onFinishCallBack}
          onCancel={() => {
            setImportOrExportVisible(false);
            getTree();
          }}
          subSystemValue={subSystemValue}
          nodeObj={nodeObj}
        />
        {/* <div
          className={classnames({
            [styles.rightBox]: true,
          })}
        >
          关联角色
          <CheckList
            info={info}
            nodeType={nodeType}
            valueCallback={valueCallback}
          />
        </div> */}
      </div>
    </Spin>
  );
};

export default MiniMenu;