sxtree.jsx 15.6 KB
Newer Older
wuhao's avatar
wuhao committed
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
import { doFetch } from "@/utils/doFetch";
import { ArrowDownOutlined, ArrowRightOutlined } from "@ant-design/icons";
import AddIcon from "@mui/icons-material/Add";
import BorderColorIcon from "@mui/icons-material/BorderColor";
import HorizontalRuleIcon from "@mui/icons-material/HorizontalRule";
import { Box, colors, IconButton, Typography } from "@mui/material";
import { useRequest } from "ahooks";
import { Input, message, Modal, Popconfirm, Tooltip, Tree } from "antd";
import { useEffect, useMemo, useState } from "react";
import "./index.less";

{
  /* <TreeRender
        url="/ngic-workmanship/pmMaterieType/queryTreeList"
        deleteurl="/ngic-workmanship/pmMaterieType/deleteById"
        saveurl="/ngic-workmanship/pmMaterieType/save"
        onselected={(vals) => {
          setmaterieTypeId(vals[0] ?? "");
        }}
      /> */
}

let { Search } = Input;

const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (
        node.children.some((item) => {
          return item.key === key;
        })
      ) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};

function TreeRender({
  url,
  deleteurl,
  saveurl,
  onselected,
  params,
  noaction,
  maxWidth,
  style,
  submitKey,
wuhao's avatar
wuhao committed
54
  disabled,
wuhao's avatar
wuhao committed
55
  hidden,
wuhao's avatar
wuhao committed
56 57 58 59 60 61 62 63 64 65 66 67
}) {
  const [search, setsearch] = useState("");
  const [savetitle, setsavetitle] = useState(null);
  const [modal, setModal] = useState({
      visible: false,
    }),
    [drawer, setDrawer] = useState({
      item: null,
      open: false,
    });
  const [expandall, setexpandall] = useState(false);
  const [expandedKeys, onExpand] = useState();
wuhao's avatar
wuhao committed
68
  const { data, refresh, loading } = useRequest(() => {
wuhao's avatar
wuhao committed
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
    return doFetch({ url, params: params ?? {} });
  });
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  const allkeys = useMemo(() => {
    let res = [];
    const fn = (source) => {
      source?.map((el) => {
        res.push(el);
        el.children && el.children.length > 0 ? fn(el.children) : ""; // 子级递归
      });
    };
    fn(data?.data?.dataList ?? []);
    return res.filter((it) => it.children).map((it) => it.key);
  }, [data]);
  const alldata = useMemo(() => {
    let res = [];
    const fn = (source) => {
      source?.map((el) => {
        res.push(el);
        el.children && el.children.length > 0 ? fn(el.children) : ""; // 子级递归
      });
    };
    fn(data?.data?.dataList ?? []);
    return res;
  }, [data]);
  const treeData = useMemo(() => {
    let res = data?.data?.dataList ?? [];
    return [
      ...res,
      // {
      //   title: "查看实验",
      //   key: "cksy",
      // },
      // {
      //   title: "常见问题",
      //   key: "cjwt",
      // },
    ];
  }, [data]);
  const onChange = (e) => {
    const { value } = e.target;
    const dataLists = getAllList();
    const newExpandedKeys = dataLists
      .map((item) => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, treeData);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    setsearch(value);
    if (newExpandedKeys.length > 0) {
      setexpandall(true);
      setAutoExpandParent(true);
    } else {
      setexpandall(false);
      setAutoExpandParent(false);
    }
    onExpand(newExpandedKeys);
  };
  const loop = (data) =>
    data.map((item) => {
      const index = item.title.indexOf(search);
      const beforeStr = item.title.substr(0, index);
      const afterStr = item.title.substr(index + search.length);
      let title =
        index > -1 ? (
          <Tooltip title={item.title} placement="topRight">
            <span
              style={{
                display: "block",
                maxWidth: maxWidth ?? 88,
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
                marginRight: 6,
              }}
            >
              {beforeStr}
              <span style={{ color: "#f50" }}>{search}</span>
              {afterStr}
            </span>
          </Tooltip>
        ) : (
          <Tooltip title={item.title} placement="topRight">
            <span
              style={{
                display: "block",
                maxWidth: maxWidth ?? 100,
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
                marginRight: 6,
              }}
            >
              {item.title}
            </span>
          </Tooltip>
        );

      const actiontitle = (
        <div
          className="tree-item"
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            padding: "4px 6px",
          }}
        >
          <span style={{ marginRight: 6 }}>{title}</span>
          <div className="center" style={{ gap: 8 }}>
wuhao's avatar
wuhao committed
182
            {item.key && item.key != "00000000" && !hidden && (
wuhao's avatar
wuhao committed
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
              <Tooltip title="编辑">
                <div
                  className="bgs"
                  onClick={(e) => {
                    if (disabled) return;
                    e.stopPropagation();
                    setsavetitle(null);
                    if (true) {
                      setModal({
                        visible: true,
                        closable: true,
                        title: "修改节点名称",
                        okText: "修改",
                        cancelText: "取消",
                        placeholder: item.title,
                        key: item.key,
                      });
                    }
                  }}
                >
                  <BorderColorIcon
                    style={{
                      color: disabled ? "grey" : "#1890ff",
                      fontSize: 14,
                    }}
                  />
wuhao's avatar
wuhao committed
209 210 211
                </div>
              </Tooltip>
            )}
wuhao's avatar
wuhao committed
212
            {item.key && item.key != "00000000" && item.children && !hidden && (
wuhao's avatar
wuhao committed
213
              <Tooltip title="新增">
wuhao's avatar
wuhao committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
                <div
                  className="bgs"
                  onClick={(e) => {
                    if (disabled) return;
                    e.stopPropagation();
                    setsavetitle(null);
                    if (true) {
                      setModal({
                        visible: true,
                        closable: true,
                        title: "新增子结构",
                        okText: "新增",
                        cancelText: "取消",
                        placeholder: item.title,
                        key: item.key,
                      });
                    }
                  }}
                >
wuhao's avatar
wuhao committed
233 234 235
                  <AddIcon
                    disabled={false}
                    style={{
wuhao's avatar
wuhao committed
236
                      color: disabled ? "grey" : "green",
wuhao's avatar
wuhao committed
237 238 239 240 241 242 243
                      fontSize: 20,
                    }}
                  />
                </div>
              </Tooltip>
            )}

wuhao's avatar
wuhao committed
244
            {item.key != "0" && !hidden && (
wuhao's avatar
wuhao committed
245 246 247 248 249
              <Popconfirm
                placement="top"
                title="是否删除该节点?"
                okText="删除"
                cancelText="取消"
wuhao's avatar
wuhao committed
250 251
                disabled={disabled}
                onConfirm={(e) => {
wuhao's avatar
wuhao committed
252 253 254 255 256 257 258 259 260 261 262 263 264
                  doFetch({ url: deleteurl, params: { id: item.key } }).then(
                    (res) => {
                      if (res.code == "0000") {
                        message.success("操作成功");
                        refresh();
                      }
                    }
                  );
                }}
              >
                <Tooltip title="删除" placement="bottom">
                  <div className="bgs">
                    <HorizontalRuleIcon
wuhao's avatar
wuhao committed
265
                      style={{ color: disabled ? "grey" : "red", fontSize: 16 }}
wuhao's avatar
wuhao committed
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
                    />
                  </div>
                </Tooltip>
              </Popconfirm>
            )}
          </div>
        </div>
      );
      if (item.key === "00000000") {
        title = (
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              flex: 1,
            }}
          >
            {title}
            <Tooltip
              title={expandall ? "收起" : "展开"}
              onClick={(e) => {
                e.stopPropagation();
                setexpandall(!expandall);
                onExpand(expandall ? [] : allkeys);
                setAutoExpandParent(!expandall);
              }}
            >
              {expandall ? <ArrowDownOutlined /> : <ArrowRightOutlined />}
            </Tooltip>
          </div>
        );
      }

      if (item.children) {
        return {
          title: noaction ? title : actiontitle,
          key: item.key,
          children: loop(item.children),
          level: item.level,
          type: item.type,
        };
      }
      return {
        title: noaction ? title : actiontitle,
        key: item.key,
        level: item.level,
        type: item.type,
        icon: item.icon ?? null,
      };
    });

  useEffect(() => {
    setexpandall(true);
    onExpand(allkeys);
  }, [allkeys]);

  function getAllList() {
    const dataLists = [];
    const generateLists = (data) => {
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const key = node.key;
        dataLists.push({ key, title: node.title, level: node.level });
        if (node.children) {
          generateLists(node.children, node.key);
        }
      }
    };
    generateLists(treeData);
    return dataLists;
  }
  return (
    <>
      <Box
        flexDirection={"row"}
        display={"flex"}
        justifyContent={"space-between"}
        alignItems={"center"}
        mt={0}
      >
        <Typography variant="h6">课程目录</Typography>
wuhao's avatar
wuhao committed
348 349 350 351 352
        {!hidden && (
          <IconButton
            disabled={disabled}
            onClick={() => {
              setDrawer({ open: true });
wuhao's avatar
wuhao committed
353
            }}
wuhao's avatar
wuhao committed
354 355 356 357 358 359 360 361 362
          >
            <AddIcon
              style={{
                fontSize: 20,
                color: disabled ? colors.grey[600] : colors.blue[600],
              }}
            ></AddIcon>
          </IconButton>
        )}
wuhao's avatar
wuhao committed
363

wuhao's avatar
wuhao committed
364 365 366 367 368 369 370 371 372 373 374 375 376
        <Modal
          {...drawer}
          closable={false}
          maskClosable={true}
          title="新增章标题"
          okText="新增"
          cancelText="取消"
          onCancel={() => {
            setDrawer(() => ({
              item: null,
              open: false,
            }));
          }}
wuhao's avatar
wuhao committed
377 378 379
          okButtonProps={{
            loading,
          }}
wuhao's avatar
wuhao committed
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
          onOk={() => {
            return new Promise((resolve, reject) => {
              if (drawer?.item) {
                doFetch({
                  url: "/busTrainCatalogue/saveOrUpdateCatalogue",
                  params: {
                    ...params,
                    catalogue: drawer.item,
                  },
                }).then((res) => {
                  if (res.code == "0000") {
                    message.success("操作成功");
                    refresh();
                    setDrawer({
                      item: null,
                      open: false,
                    });
                  }
                });
                refresh();
                resolve();
              } else {
                message.warning("请输入修改的名称");
                reject();
              }
            });
          }}
        >
          <div>
            <Input
              placeholder="请输入章标题"
              allowClear
              value={drawer?.item}
              onChange={(e) => {
                setDrawer((v) => ({
                  ...v,
                  item: e.target.value,
                }));
              }}
            ></Input>
          </div>
        </Modal>
      </Box>
      <div style={{ ...style }}>
        <Modal
          {...modal}
          onCancel={() => {
            setModal((s) => ({
              ...s,
              visible: false,
            }));
          }}
wuhao's avatar
wuhao committed
432 433 434
          okButtonProps={{
            loading,
          }}
wuhao's avatar
wuhao committed
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
          onOk={() => {
            if (modal.okText == "修改") {
              return new Promise((resolve, reject) => {
                if (savetitle) {
                  doFetch({
                    url: saveurl,
                    params: {
                      [submitKey]: savetitle,
                      id: modal.key,
                      ...params,
                    },
                  }).then((res) => {
                    if (res.code == "0000") {
                      message.success("操作成功");
                      refresh();
                      setModal({
                        visible: false,
                      });
                    }
                  });
                  resolve();
                } else {
                  message.warning("请输入修改的名称");
                  reject();
                }
              });
            } else {
              return new Promise((resolve, reject) => {
                if (savetitle) {
                  doFetch({
                    url: saveurl,
                    params: {
                      [submitKey]: savetitle,
                      parentId: modal.key,
                      ...params,
                    },
                  }).then((res) => {
                    if (res.code == "0000") {
                      message.success("操作成功");
                      refresh();
                      setModal({
                        visible: false,
                      });
                    }
                  });
                  resolve();
                } else {
                  message.warning("请输入修改的名称");
                  reject();
                }
              });
            }
          }}
        >
          {modal.okText == "修改" ? (
            <div>
              <Input
                placeholder={modal.placeholder}
                allowClear
                value={savetitle}
                onChange={(e) => {
                  setsavetitle(e.target.value);
                }}
              ></Input>
            </div>
          ) : (
            <div>
              <div style={{ marginBottom: 15, color: "#f50", fontSize: 16 }}>
                当前结构:{modal.placeholder}
              </div>
              <Input
                placeholder="子结构"
                allowClear
                onChange={(e) => {
                  setsavetitle(e.target.value);
                }}
              ></Input>
            </div>
          )}
        </Modal>
        <Search
          value={search}
          style={{ margin: "16px 0 8px 0" }}
          placeholder="搜索"
          onChange={onChange}
        />
        <Tree
          showIcon
          showLine
          onSelect={(selectedKeys, e) => {
            onselected?.(selectedKeys, e, alldata);
          }}
          autoExpandParent={autoExpandParent}
          defaultExpandAll={true}
          expandedKeys={expandedKeys}
          onExpand={(expandedKeys, { expanded: bool, node }) => {
            onExpand(expandedKeys);
            setAutoExpandParent(false);
            if (!bool && node.key == "00000000") {
              setexpandall(false);
            } else {
              setexpandall(true);
            }
          }}
          treeData={loop(treeData ?? [])}
        >
          {/* {loop(treeData ? treeData : [])} */}
        </Tree>
      </div>
    </>
  );
}

export default TreeRender;