index.jsx 13.2 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
import React, { useState, useMemo, useRef, createContext, useEffect } from 'react';
import { Tree, Input, Popconfirm, Tooltip, Divider, Modal, message } from 'antd';
import {
  MinusSquareOutlined,
  FormOutlined,
  PlusSquareOutlined,
  ArrowDownOutlined,
  ArrowRightOutlined,
} from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { doFetch } from '@/utils/doFetch';
const ReachableContext = createContext(null);
let { Search } = Input,
  { TreeNode } = Tree;
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;
};
{
  /* <TreeRender
        url="/ngic-workmanship/pmMaterieType/queryTreeList"
        deleteurl="/ngic-workmanship/pmMaterieType/deleteById"
        saveurl="/ngic-workmanship/pmMaterieType/save"
        onselected={(vals) => {
          setmaterieTypeId(vals[0] ?? "");
        }}
      /> */
}

wuhao's avatar
wuhao committed
44 45 46 47 48 49 50 51 52 53 54
function TreeRender({
  url,
  deleteurl,
  saveurl,
  onselected,
  params,
  noaction,
  maxWidth,
  style,
  submitKey,
}) {
wuhao's avatar
wuhao committed
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
  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);

  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 [
      {
wuhao's avatar
wuhao committed
93 94
        title: '全部类型',
        key: '',
wuhao's avatar
wuhao committed
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
        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',
TZW's avatar
TZW committed
135
                marginRight: 6,
wuhao's avatar
wuhao committed
136 137 138 139 140 141 142 143
              }}
            >
              {beforeStr}
              <span style={{ color: '#f50' }}>{search}</span>
              {afterStr}
            </span>
          </Tooltip>
        ) : (
TZW's avatar
TZW committed
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
          <Tooltip title={item.title} placement="bottom">
            <span
              style={{
                display: 'inline-block',
                maxWidth: maxWidth ?? 88,
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                marginRight: 6,
              }}
            >
              {item.title}
            </span>
          </Tooltip>
        );
wuhao's avatar
wuhao committed
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

      const actiontitle = (
        <div
          style={{
            display: 'flex',
            alignItems: 'start',
            justifyContent: 'space-between',
          }}
        >
          <span style={{ merginRight: 6 }}>{title}</span>
          <div>
            {item.key && item.key != '00000000' && (
              <Tooltip
                title="编辑"
                onClick={(e) => {
                  e.stopPropagation();
                  setsavetitle(null);
                  if (true) {
                    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={false}
                onClick={(e) => {
                  e.stopPropagation();
                  setsavetitle(null);
                  if (true) {
                    setModal({
                      visible: true,
                      closable: true,
                      title: '新增子结构',
                      okText: '新增',
                      cancelText: '取消',
                      placeholder: item.title,
                      key: item.key,
                    });
                  }
                }}
                style={{
                  color: `${true ? '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
TZW's avatar
TZW committed
223
                placement="top"
wuhao's avatar
wuhao committed
224 225 226
                title="是否删除该节点?"
                okText="删除"
                cancelText="取消"
TZW's avatar
TZW committed
227 228
                onConfirm={(e) => {
                  console.log(111);
wuhao's avatar
wuhao committed
229 230 231 232 233 234 235 236 237 238 239 240
                  doFetch({ url: deleteurl, params: { id: item.key } }).then((res) => {
                    if (res.code == '0000') {
                      message.success('操作成功');
                      refresh();
                    }
                  });
                }}
                disabled={true}
              >
                <Tooltip title="删除">
                  <MinusSquareOutlined
                    onClick={(e) => {
TZW's avatar
TZW committed
241
                      // console.log(e);
wuhao's avatar
wuhao committed
242
                      e.stopPropagation();
TZW's avatar
TZW committed
243 244 245 246 247 248
                      doFetch({ url: deleteurl, params: { id: item.key } }).then((res) => {
                        if (res.code == '0000') {
                          message.success('操作成功');
                          refresh();
                        }
                      });
wuhao's avatar
wuhao committed
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
                    }}
                    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 />}
                        </Tooltip>
                    } */}
          </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,
TZW's avatar
TZW committed
302
          type: item.type,
wuhao's avatar
wuhao committed
303 304 305 306 307 308
        };
      }
      return {
        title: noaction ? title : actiontitle,
        key: item.key,
        level: item.level,
TZW's avatar
TZW committed
309
        type: item.type,
wuhao's avatar
wuhao committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
      };
    });
  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 (
左玲玲's avatar
左玲玲 committed
332
    <div style={{ ...style }} className='treenode'>
wuhao's avatar
wuhao committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
      <Modal
        {...modal}
        onCancel={() => {
          setModal((s) => ({
            ...s,
            visible: false,
          }));
        }}
        onOk={() => {
          if (modal.okText == '修改') {
            return new Promise((resolve, reject) => {
              if (savetitle) {
                doFetch({
                  url: saveurl,
                  params: {
wuhao's avatar
wuhao committed
348
                    [submitKey]: savetitle,
wuhao's avatar
wuhao committed
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
                    id: modal.key,
                  },
                }).then((res) => {
                  if (res.code == '0000') {
                    message.success('操作成功');

                    refresh();
                    setModal({
                      visible: false,
                    });
                  }
                });
                resolve();
              } else {
                message.warn('请输入修改的名称');
                reject();
              }
            });
          } else {
            return new Promise((resolve, reject) => {
              if (savetitle) {
                doFetch({
                  url: saveurl,
                  params: {
wuhao's avatar
wuhao committed
373
                    [submitKey]: savetitle,
wuhao's avatar
wuhao committed
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
                    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>
        ) : (
TZW's avatar
TZW committed
406 407 408
          <div>
            <div style={{ marginBottom: 15, color: '#f50', fontSize: 16 }}>
              当前结构:{modal.placeholder}
wuhao's avatar
wuhao committed
409
            </div>
TZW's avatar
TZW committed
410 411 412 413 414 415 416 417 418
            <Input
              placeholder="子结构"
              allowClear
              onChange={(e) => {
                setsavetitle(e.target.value);
              }}
            ></Input>
          </div>
        )}
wuhao's avatar
wuhao committed
419 420 421 422 423 424 425 426 427 428
      </Modal>
      <Search
        value={search}
        style={{ margin: '16px 0 8px 0' }}
        placeholder="搜索"
        onChange={onChange}
      />

      <Tree
        onSelect={(selectedKeys, e) => {
TZW's avatar
TZW committed
429
          // //console.log(selectedKeys);
wuhao's avatar
wuhao committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
          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;