index.jsx 13.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
import React, { useState, useMemo, useRef, createContext } from "react";
import {
  Tree,
  Input,
  Popconfirm,
  Tooltip,
  Divider,
  Modal,
  message,
} from "antd";
import {
  MinusSquareOutlined,
  FormOutlined,
  PlusSquareOutlined,
  ArrowDownOutlined,
  ArrowRightOutlined,
} from "@ant-design/icons";
import getPrem from "@/utils/getPrem";
import { useRequest } from "ahooks";
import { doFetch } from "@/utils/doFetch";
import { useEffect } from "react";
import Login from "@/pages/user/Login";
wuhao's avatar
wuhao committed
23 24 25

const ReachableContext = createContext(null);
let { Search } = Input,
wuhao's avatar
wuhao committed
26
  { TreeNode } = Tree;
左玲玲's avatar
左玲玲 committed
27
const getParentKey = (key, tree) => {
wuhao's avatar
wuhao committed
28 29 30 31 32 33 34 35 36 37 38 39 40
  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);
      }
左玲玲's avatar
左玲玲 committed
41
    }
wuhao's avatar
wuhao committed
42 43
  }
  return parentKey;
左玲玲's avatar
左玲玲 committed
44
};
wuhao's avatar
wuhao committed
45

wuhao's avatar
wuhao committed
46 47 48 49 50 51 52 53
function TreeRender({
  url,
  deleteurl,
  saveurl,
  onselected,
  params,
  noaction,
  maxWidth,
krysent's avatar
krysent committed
54
  hasTool = false,
wuhao's avatar
wuhao committed
55 56 57 58 59 60 61 62 63 64 65 66
}) {
  const [search, setsearch] = useState("");
  const [savetitle, setsavetitle] = useState(null);
  const [modal, setModal] = useState({
    visible: false,
  });
  const [expandall, setexpandall] = useState(false);
  const [expandedKeys, onExpand] = useState();
  const { data, loading, refresh } = useRequest(() => {
    return doFetch({ url, params: params ?? {} });
  });
  const [autoExpandParent, setAutoExpandParent] = useState(true);
wuhao's avatar
wuhao committed
67

wuhao's avatar
wuhao committed
68 69 70 71 72 73 74
  const allkeys = useMemo(() => {
    let res = [];
    const fn = (source) => {
      source.map((el) => {
        res.push(el);
        el.children && el.children.length > 0 ? fn(el.children) : ""; // 子级递归
      });
左玲玲's avatar
左玲玲 committed
75
    };
wuhao's avatar
wuhao committed
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
    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 [
      {
        title: "全部",
        key: "00000000",
        children: res,
      },
    ];
  }, [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="bottom">
            <span
              style={{
                display: "inline-block",
                maxWidth: maxWidth ?? 88,
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              }}
            >
              {beforeStr}
              <span style={{ color: "#f50" }}>{search}</span>
              {afterStr}
            </span>
          </Tooltip>
        ) : (
          <Tooltip title={item.title} placement="bottom">
            <span
              style={{
                display: "inline-block",
                maxWidth: maxWidth ?? 88,
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              }}
            >
              {item.title}
            </span>
          </Tooltip>
        );
wuhao's avatar
wuhao committed
158

wuhao's avatar
wuhao committed
159 160 161 162 163 164 165 166 167
      const actiontitle = (
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          {title}
krysent's avatar
krysent committed
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
          {hasTool && (
            <div>
              {item.key && item.key != "00000000" && (
                <Tooltip
                  title="编辑"
                  onClick={(e) => {
                    e.stopPropagation();
                    setsavetitle(null);
                    if (getPrem("enElectricityMeterType_save", "ifs")) {
                      setModal({
                        visible: true,
                        closable: true,
                        title: "修改节点名称",
                        okText: "修改",
                        cancelText: "取消",
                        placeholder: item.title,
                        key: item.key,
                      });
                    }
                  }}
                >
                  <FormOutlined style={{ color: "#1890ff" }} />
                </Tooltip>
              )}
              {item.key && item.key != "00000000" && (
                <Divider type="vertical" style={{ margin: "0 6px" }}></Divider>
              )}
              <Tooltip title="新增">
                <PlusSquareOutlined
                  disabled={!getPrem("enElectricityMeterType_save", "ifs")}
                  onClick={(e) => {
                    e.stopPropagation();
                    setsavetitle(null);
                    if (getPrem("enElectricityMeterType_save", "ifs")) {
                      setModal({
                        visible: true,
                        closable: true,
                        title: "新增子结构",
                        okText: "新增",
                        cancelText: "取消",
                        placeholder: item.title,
                        key: item.key,
                      });
wuhao's avatar
wuhao committed
211
                    }
krysent's avatar
krysent committed
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
                  }}
                  style={{
                    color: `${
                      getPrem("enElectricityMeterType_save", "ifs")
                        ? "green"
                        : ""
                    }`,
                  }}
                />
              </Tooltip>
              {(!item.children || item.children.length == 0) && (
                <Divider type="vertical" style={{ margin: "0 6px" }}></Divider>
              )}
              {(!item.children || item.children.length == 0) &&
                item.key != "0" && (
                  <Popconfirm
                    placement="bottom"
                    title="是否删除该节点?"
                    okText="删除"
                    cancelText="取消"
                    onConfirm={() => {
                      doFetch({
                        url: deleteurl,
                        params: { id: item.key },
                      }).then((res) => {
                        if (res.code == "0000") {
                          message.success("操作成功");
                          refresh();
                        }
                      });
wuhao's avatar
wuhao committed
242
                    }}
krysent's avatar
krysent committed
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
                    disabled={
                      !getPrem("enElectricityMeterType_deleteById", "ifs")
                    }
                  >
                    <Tooltip title="删除">
                      <MinusSquareOutlined
                        onClick={(e) => {
                          e.stopPropagation();
                        }}
                        style={{ color: "red" }}
                      />
                    </Tooltip>
                  </Popconfirm>
                )}
              {item.key === "00000000" && (
                <Divider type="vertical" style={{ margin: "0 6px" }}></Divider>
              )}
              {item.key === "00000000" && (
                <Tooltip
                  title={expandall ? "收起" : "展开"}
                  onClick={(e) => {
                    e.stopPropagation();
                    setexpandall(!expandall);
                    onExpand(expandall ? [] : allkeys);
                  }}
                >
                  {expandall ? <ArrowDownOutlined /> : <ArrowRightOutlined />}
wuhao's avatar
wuhao committed
270
                </Tooltip>
krysent's avatar
krysent committed
271 272 273
              )}
            </div>
          )}
wuhao's avatar
wuhao committed
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
        </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>
        );
      }
wuhao's avatar
wuhao committed
301

wuhao's avatar
wuhao committed
302 303 304 305 306 307 308 309 310 311 312 313 314
      // if (item.children) {
      //     return (
      //         <TreeNode key={item.key} title={actiontitle}>
      //             {loop(item.children)}
      //         </TreeNode>
      //     );
      // }
      // return <TreeNode key={item.key} title={title} />;
      // return (
      //     <TreeNode key={item.key} title={noaction ? title : actiontitle}>
      //         {item.children && loop(item.children)}
      //     </TreeNode>
      // );
wuhao's avatar
wuhao committed
315

wuhao's avatar
wuhao committed
316
      if (item.children) {
左玲玲's avatar
左玲玲 committed
317
        return {
wuhao's avatar
wuhao committed
318 319 320 321
          title: noaction ? title : actiontitle,
          key: item.key,
          children: loop(item.children),
          level: item.level,
左玲玲's avatar
左玲玲 committed
322
        };
wuhao's avatar
wuhao committed
323 324 325 326 327 328
      }
      return {
        title: noaction ? title : actiontitle,
        key: item.key,
        level: item.level,
      };
左玲玲's avatar
左玲玲 committed
329
    });
wuhao's avatar
wuhao committed
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
  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 (
    <div>
      <Modal
        {...modal}
        onCancel={() => {
          setModal((s) => ({
            ...s,
            visible: false,
          }));
        }}
        onOk={() => {
          if (modal.okText == "修改") {
            return new Promise((resolve, reject) => {
              if (savetitle) {
                doFetch({
                  url: saveurl,
                  params: {
                    materieTypeName: savetitle,
                    id: modal.key,
                  },
                }).then((res) => {
                  if (res.code == "0000") {
                    message.success("操作成功");
wuhao's avatar
wuhao committed
372

wuhao's avatar
wuhao committed
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
                    refresh();
                    setModal({
                      visible: false,
                    });
                  }
                });
                resolve();
              } else {
                message.warn("请输入修改的名称");
                reject();
              }
            });
          } else {
            return new Promise((resolve, reject) => {
              if (savetitle) {
                doFetch({
                  url: saveurl,
                  params: {
                    materieTypeName: savetitle,
                    parentId: modal.key,
                  },
                }).then((res) => {
                  if (res.code == "0000") {
                    message.success("操作成功");
                    refresh();
                    setModal({
                      visible: false,
                    });
                  }
                });
                resolve();
              } else {
                message.warn("请输入修改的名称");
                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}
      />
wuhao's avatar
wuhao committed
444

wuhao's avatar
wuhao committed
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
      <Tree
        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>
  );
wuhao's avatar
wuhao committed
467 468
}

wuhao's avatar
wuhao committed
469
export default TreeRender;