index.js 15.8 KB
Newer Older
涂茜's avatar
涂茜 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import React, { useContext, useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {
  Button,
  Input,
  Radio,
  Modal,
  Checkbox,
  Row,
  Col,
  Tree,
  ConfigProvider,
  message,
程恺文's avatar
程恺文 committed
15
  Tooltip,
涂茜's avatar
涂茜 committed
16 17 18 19 20 21 22
} from 'antd';
import Empty from '@wisdom-components/empty';
import {
  UnorderedListOutlined,
  ExclamationCircleFilled,
  SearchOutlined,
  CloseOutlined,
程恺文's avatar
程恺文 committed
23
  InfoCircleOutlined,
李纪文's avatar
李纪文 committed
24
  CaretDownOutlined
涂茜's avatar
涂茜 committed
25 26
} from '@ant-design/icons';
import './index.less';
27
import { getQuataList, updateMonitorConf } from './apis';
涂茜's avatar
涂茜 committed
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

const { TreeNode } = Tree;

const QuotaSelect = ({
  buttonProps,
  deviceList,
  confList,
  onSelect,
  pointType,
  width,
  title,
  cancelText,
  okText,
  onModalOk,
  onModalClose,
  onModalCancel,
  searchPrefix,
  placeholder,
  maximum,
  user,
  treeProps,
李纪文's avatar
李纪文 committed
49
  defaultSelect,
50
  disabledList,
51
  isCommonTag,
52
  showQuotaName,
53
  filterNoStatistical = false
涂茜's avatar
涂茜 committed
54 55 56 57
}) => {
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('ec-quota-select');
  const [visible, setVisible] = useState(false);
李纪文's avatar
李纪文 committed
58
  const [targetValue, setTargetValue] = useState(defaultSelect);
涂茜's avatar
涂茜 committed
59 60
  const [allQuotaList, setAllQuotaList] = useState([]);
  const [quotaList, setQuotaList] = useState([]);
61
  const [groupQuotaList, setGroupQuotaList] = useState([]);
涂茜's avatar
涂茜 committed
62 63 64
  const [selectDevice, setSelectDevice] = useState({}); // 选中的设备
  const [selectData, setSelectData] = useState([]); // 选中的指标数据
  const [confParams, setConfParams] = useState({});
徐乐's avatar
徐乐 committed
65
  const [search, setSearch] = useState('');
涂茜's avatar
涂茜 committed
66 67
  const fetchData = (item = {}) => {
    // 请求指标列表
68 69
    getQuataList({
      accountName: item.deviceType,
70 71
      // addrSchemeID: item.pointAddressID,
      isCommonTag: isCommonTag,
72
      flag:filterNoStatistical
73
    }).then((res) => {
涂茜's avatar
涂茜 committed
74 75 76 77
      if (res.code === 0) {
        const data =
          res.data.length > 0
            ? res.data.map((child) => ({
程恺文's avatar
程恺文 committed
78 79 80 81 82
                ...child,
                checked: item.confList.includes(child.sensorName),
                title: child.sensorName,
                key: child.sensorName,
              }))
涂茜's avatar
涂茜 committed
83
            : [];
程恺文's avatar
程恺文 committed
84 85 86
        let k = data.find(function (a) {
          return a.isShow == 1;
        });
徐乐's avatar
徐乐 committed
87
        setTargetValue(k ? 'emphasis' : 'all');
涂茜's avatar
涂茜 committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
        setAllQuotaList(data);
        setSelectData(data.filter((child) => child.checked));
      } else {
        message.error(res.msg);
      }
    });
  };

  // 更新设备配置
  const updateDeviceConf = () => {
    const params = {
      ...confParams,
      loginName: user,
      type: '用户',
    };
    const curSelectList = JSON.parse(JSON.stringify(selectData));
    const curSelectKey = curSelectList.map((child) => child.key);
    params[pointType] = curSelectKey.join(',');
106
    updateMonitorConf(params).then((response) => {
涂茜's avatar
涂茜 committed
107 108 109 110 111 112 113 114
      if (response.code === 0) {
        message.success('保存成功');
      } else {
        message.error(response.msg);
      }
    });
  };

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
  // 处理指标分组
  const handleGroupData = (data) => {
    const groupData = [];
    const groupQuotaData = [];
    data.forEach((item) => {
      if (!groupData.includes(item.groupName)) {
        groupData.push(item.groupName);
      }
    });
    groupData.forEach((group) => {
      const list = [];
      data.forEach((child) => {
        if (child.groupName === group) {
          list.push(child);
        }
      });
      groupQuotaData.push({
        groupName: group || '未分组指标',
        quotaList: list,
      });
    });
    setGroupQuotaList(groupQuotaData);
  };

  useEffect(() => {
    handleGroupData(quotaList);
  }, [quotaList]);

涂茜's avatar
涂茜 committed
143 144 145 146
  useEffect(() => {
    if (targetValue === 'emphasis') {
      filterEmphasisQuota();
    } else {
徐乐's avatar
徐乐 committed
147 148
      let newQuotaList = allQuotaList.filter((item) => item.sensorName.indexOf(search) >= 0);
      setQuotaList(newQuotaList);
涂茜's avatar
涂茜 committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    }
  }, [allQuotaList]);

  useEffect(() => {
    let data = JSON.parse(JSON.stringify(allQuotaList));
    data.forEach((item) => {
      item.checked = false;
      if (selectData.length > 0) {
        selectData.forEach((child) => {
          if (child.key === item.key) {
            item.checked = true;
          }
        });
      }
    });
    setAllQuotaList(data);
  }, [selectData]);

  // 过滤重点指标
  const filterEmphasisQuota = () => {
    let newQuotaList = [...allQuotaList];
程恺文's avatar
程恺文 committed
170 171 172
    newQuotaList = newQuotaList.filter(
      (item) => item.isShow === 1 && item.sensorName.indexOf(search) >= 0,
    );
涂茜's avatar
涂茜 committed
173 174 175 176 177 178 179 180 181 182 183
    setQuotaList(newQuotaList);
  };

  // 展示模态框
  const showModal = (item) => {
    setVisible(true);
    setSelectDevice(item);
    fetchData(item);
  };

  useEffect(() => {
184
    let param = confList.filter((child) => child.deviceType === selectDevice.deviceType)[0];
185 186 187 188
    if (!param)
      param = {
        deviceType: selectDevice.deviceType,
      };
涂茜's avatar
涂茜 committed
189 190 191 192 193 194 195 196 197 198
    setConfParams({ ...param });
  }, [selectDevice]);

  // 关闭模态框
  const handleCancel = (e) => {
    if (e.target.innerHTML === cancelText) {
      setSelectData([]);
      onModalCancel && onModalCancel();
    } else {
      onModalClose && onModalClose();
199 200
      setQuotaList([]);
      setGroupQuotaList([]);
涂茜's avatar
涂茜 committed
201
      setVisible(false);
202
      setSearch('');
涂茜's avatar
涂茜 committed
203 204 205 206 207 208
    }
  };

  const onOk = () => {
    onModalOk && onModalOk();
    handleOk();
209 210
    setQuotaList([]);
    setGroupQuotaList([]);
涂茜's avatar
涂茜 committed
211
    setVisible(false);
212
    setSearch('');
涂茜's avatar
涂茜 committed
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
  };

  const handleOk = () => {
    const curSelectList = JSON.parse(JSON.stringify(selectData));
    const curSelectKey = curSelectList.map((child) => child.key);
    onSelect({
      device: selectDevice,
      selectKey: curSelectKey,
      selectList: curSelectList,
    });
  };

  // 切换重点与全部
  const onRadioChange = (e) => {
    if (e.target.value === 'all') {
徐乐's avatar
徐乐 committed
228 229
      let newQuotaList = allQuotaList.filter((item) => item.sensorName.indexOf(search) >= 0);
      setQuotaList(newQuotaList);
涂茜's avatar
涂茜 committed
230 231 232 233 234 235 236 237 238
    } else {
      filterEmphasisQuota();
    }
    setTargetValue(e.target.value);
  };

  // 搜索指标
  const onSearch = (e) => {
    if (e.type === 'keydown' || e.target.value === '') {
徐乐's avatar
徐乐 committed
239
      setSearch(e.target.value);
涂茜's avatar
涂茜 committed
240 241
      if (e.target.value !== '') {
        let newQuotaList = [];
李纪文's avatar
李纪文 committed
242
        allQuotaList.forEach((item) => {
243
          if (!item.sensorName) return;
李纪文's avatar
李纪文 committed
244 245 246 247 248 249 250 251
          if (item.sensorName.indexOf(e.target.value) > -1) {
            if (targetValue === 'all') {
              newQuotaList.push(item);
            } else {
              if (item.isShow === 1 && item.sensorName.indexOf(search) >= 0)
                newQuotaList.push(item);
            }
          }
涂茜's avatar
涂茜 committed
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
        });
        setQuotaList(newQuotaList);
      } else {
        if (targetValue === 'all') {
          setQuotaList(allQuotaList);
        } else {
          filterEmphasisQuota();
        }
      }
    }
  };

  // 处理复选框点击事件
  const handleCheckboxChange = (e, item) => {
    let curSelectList = JSON.parse(JSON.stringify(selectData));
    if (item.checked) {
      curSelectList = curSelectList.filter((child) => child.title !== item.title);
    } else {
      curSelectList.push({ ...item, checked: !item.checked });
    }
    setSelectData(curSelectList);
  };

  // 处理取消选择按钮点击事件
  const handleCancelSelect = ({ title }) => {
    let data = [...selectData];
    data = data.filter((item) => item.title !== title);
    setSelectData(data);
  };

  // 拖动选中树节点
  const handleDrop = (info) => {
    const dropKey = info.node.key;
    const dragKey = info.dragNode.key;
    const dropPos = info.node.pos.split('-');
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);

    const loop = (data, key, callback) => {
      for (let i = 0; i < data.length; i++) {
        if (data[i].key === key) {
          return callback(data[i], i, data);
        }
        if (data[i].children) {
          loop(data[i].children, key, callback);
        }
      }
    };

    const data = [...selectData];

    let dragObj;
    loop(data, dragKey, (item, index, arr) => {
      arr.splice(index, 1);
      dragObj = item;
    });

    if (!info.dropToGap) {
      loop(data, dropKey, (item) => {
        item.children = item.children || [];
        item.children.unshift(dragObj);
      });
    } else if (
      (info.node.props.children || []).length > 0 && // Has children
      info.node.props.expanded && // Is expanded
      dropPosition === 1 // On the bottom gap
    ) {
      loop(data, dropKey, (item) => {
        item.children = item.children || [];
        item.children.unshift(dragObj);
      });
    } else {
      let ar;
      let i;
      loop(data, dropKey, (item, index, arr) => {
        ar = arr;
        i = index;
      });
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj);
      } else {
        ar.splice(i + 1, 0, dragObj);
      }
    }

    setSelectData(data);
  };

  return (
    <div className={classNames(prefixCls)}>
      <div className={classNames(`${prefixCls}-btn-wrap`)}>
涂茜's avatar
涂茜 committed
342
        {!!deviceList.length &&
涂茜's avatar
涂茜 committed
343 344 345 346 347 348 349 350 351
          deviceList.map((item, index) => (
            <Button
              key={index}
              icon={<UnorderedListOutlined />}
              {...buttonProps}
              onClick={() => showModal(item)}
            >
              {buttonProps.children
                ? buttonProps.children
352
                : `${item.deviceName}(${item.confList ?showQuotaName?item.confList.join(','): item.confList.length : 0})`}
李纪文's avatar
李纪文 committed
353
              {!buttonProps.children && <CaretDownOutlined />}
涂茜's avatar
涂茜 committed
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
            </Button>
          ))}
      </div>
      {visible && (
        <Modal
          centered
          width={width}
          title={title}
          cancelText={cancelText}
          okText={okText}
          visible={true}
          onCancel={handleCancel}
          onOk={onOk}
          className={classNames(`${prefixCls}-modal`)}
          footer={[
            user ? (
              <Button
                style={{ float: 'left' }}
                key="save"
                type="primary"
                onClick={() => {
                  updateDeviceConf();
                  onOk();
                }}
              >
                保存修改
              </Button>
            ) : null,
            <Button key="cancel" onClick={handleCancel}>
              取消选择
            </Button>,
            <Button key="ok" type="primary" onClick={onOk}>
              确定
            </Button>,
          ]}
        >
          <div className={classNames(`${prefixCls}-modal-wrap`)}>
            <div className={classNames(`${prefixCls}-modal-left`)}>
              <div className={classNames(`${prefixCls}-modal-select-wrap`)}>
                <Input
                  className={classNames(`${prefixCls}-modal-search`)}
                  placeholder={placeholder}
                  bordered={false}
                  prefix={searchPrefix}
                  onChange={onSearch}
                  onPressEnter={onSearch}
                />
                <div className={classNames(`${prefixCls}-modal-target`)}>
                  <div>指标:</div>
                  <Radio.Group onChange={onRadioChange} value={targetValue}>
                    <Radio.Button value="emphasis">重点指标</Radio.Button>
                    <Radio.Button value="all">全部</Radio.Button>
                  </Radio.Group>
                </div>
                <div
                  className={classNames(`${prefixCls}-modal-select`, {
                    warning: !(selectData.length < maximum),
                  })}
                >
                  {selectData.length < maximum ? (
                    <>
                      <ExclamationCircleFilled />
                      <div>已选择 {selectData.length} 个指标</div>
                    </>
                  ) : (
                    <>
                      <ExclamationCircleFilled />
                      <div>已达上限,最多选择 {maximum} 个指标</div>
                    </>
                  )}
                </div>
              </div>
              <div className={classNames(`${prefixCls}-modal-option-wrap`)}>
                {!quotaList.length && <Empty />}
428 429 430 431 432 433 434 435 436 437 438 439 440
                {!!quotaList.length &&
                  groupQuotaList.map((group, index) => (
                    <div key={index}>
                      <div className={classNames(`${prefixCls}-modal-class-title`)}>
                        {group.groupName}
                      </div>
                      <Row gutter={[0, 6]}>
                        {group.quotaList.map((item) => (
                          <Col span={8} key={item.key}>
                            <Checkbox
                              value={item.title}
                              checked={item.checked}
                              disabled={
441
                                ((selectData.length >= maximum) &&
程恺文's avatar
程恺文 committed
442 443
                                  !item.checked) ||
                                disabledList.includes(item.title)
444 445 446 447
                              }
                              onChange={(e) => handleCheckboxChange(e, item)}
                            >
                              {item.title}
程恺文's avatar
程恺文 committed
448 449 450 451 452 453 454 455 456 457
                              {item.notInFVersion && (
                                <Tooltip
                                  placement="bottom"
                                  title={`${item.notInFVersion} 版本不存在当前指标`}
                                >
                                  <InfoCircleOutlined
                                    className={classNames(`${prefixCls}-modal-class-mark`)}
                                  />
                                </Tooltip>
                              )}
458 459 460 461 462 463
                            </Checkbox>
                          </Col>
                        ))}
                      </Row>
                    </div>
                  ))}
涂茜's avatar
涂茜 committed
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
              </div>
            </div>
            <div className={classNames(`${prefixCls}-modal-right`)}>
              <div className={classNames(`${prefixCls}-modal-number`)}>
                已选:{selectData.length}/{maximum}
              </div>
              <div className={classNames(`${prefixCls}-modal-tree`)}>
                <Tree draggable={true} onDrop={handleDrop} {...treeProps}>
                  {selectData.map((item) => (
                    <TreeNode
                      key={item.key}
                      title={
                        <div className={classNames(`${prefixCls}-modal-tree-title`)}>
                          <div>{item.title}</div>
                          <CloseOutlined onClick={() => handleCancelSelect(item)} />
                        </div>
                      }
                    />
                  ))}
                </Tree>
              </div>
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
};

QuotaSelect.defaultProps = {
  buttonProps: {},
  width: 900,
  title: '选择显示字段',
  cancelText: '取消选择',
  okText: '确定',
  placeholder: '搜索关键词',
  searchPrefix: <SearchOutlined />,
  maximum: 0,
  user: null,
  pointType: 'cardPoints',
  deviceList: [],
  confList: [],
  treeProps: {},
程恺文's avatar
程恺文 committed
507 508 509 510
  onSelect: () => {},
  onModalCancel: () => {},
  onModalOk: () => {},
  onModalClose: () => {},
李纪文's avatar
李纪文 committed
511
  defaultSelect: 'emphasis',
程恺文's avatar
程恺文 committed
512
  disabledList: [],
513
  isCommonTag: false,
514
  showQuotaName: false,
涂茜's avatar
涂茜 committed
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
};

QuotaSelect.propTypes = {
  buttonProps: PropTypes.object,
  width: PropTypes.number,
  title: PropTypes.string,
  cancelText: PropTypes.string,
  okText: PropTypes.string,
  placeholder: PropTypes.string,
  searchPrefix: PropTypes.node,
  maximum: PropTypes.number,
  user: PropTypes.string,
  pointType: PropTypes.string,
  deviceList: PropTypes.array,
  confList: PropTypes.array,
  treeProps: PropTypes.object,
  onSelect: PropTypes.func,
  onModalCancel: PropTypes.func,
  onModalOk: PropTypes.func,
  onModalClose: PropTypes.func,
李纪文's avatar
李纪文 committed
535
  defaultSelect: PropTypes.string,
536
  disabledList: PropTypes.array,
537
  isCommonTag: PropTypes.bool,
538
  showQuotaName: PropTypes.bool,
涂茜's avatar
涂茜 committed
539 540 541
};

export default QuotaSelect;