index.js 10.3 KB
Newer Older
涂茜's avatar
涂茜 committed
1
import React, { useContext, useEffect, useState } from 'react';
涂茜's avatar
涂茜 committed
2 3 4
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Button, Input, Radio, Modal, Checkbox, Row, Col, Tree, ConfigProvider } from 'antd';
涂茜's avatar
涂茜 committed
5
import Empty from '@wisdom-components/empty';
涂茜's avatar
涂茜 committed
6 7 8 9 10 11 12 13 14 15
import { ExclamationCircleFilled, SearchOutlined, CloseOutlined } from '@ant-design/icons';
import './index.less';

const { TreeNode } = Tree;

const QuotaSelect = ({
  buttonProps,
  width,
  title,
  cancelText,
涂茜's avatar
涂茜 committed
16
  okText,
涂茜's avatar
涂茜 committed
17 18
  onModalOk,
  onModalCancel,
19
  onModalClose,
涂茜's avatar
涂茜 committed
20 21 22 23 24 25 26 27
  searchPrefix,
  placeholder,
  maximum,
  dataSource,
  selectData,
  onCheckboxChange,
  onCancelSelect,
  treeProps,
涂茜's avatar
涂茜 committed
28
  onTreeDrop,
涂茜's avatar
涂茜 committed
29 30 31 32 33
}) => {
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('quota-select');

  const [visible, setVisible] = useState(false);
涂茜's avatar
涂茜 committed
34 35 36 37 38 39 40 41 42
  const [targetValue, setTargetValue] = useState('emphasis');
  const [allQuotaList, setAllQuotaList] = useState([]);
  const [quotaList, setQuotaList] = useState([]);

  useEffect(() => {
    if (dataSource.length > 0) {
      let data = dataSource.map((item) => ({
        ...item,
        checked: false,
涂茜's avatar
涂茜 committed
43 44
        title: item.name,
        key: item.name,
涂茜's avatar
涂茜 committed
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
      }));
      setAllQuotaList(data);
    }
  }, [dataSource]);

  useEffect(() => {
    if (targetValue === 'emphasis') {
      filterEmphasisQuota();
    }
  }, [allQuotaList]);

  useEffect(() => {
    let data = [...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
74
    newQuotaList = newQuotaList.filter((item) => item.isShow === '1');
涂茜's avatar
涂茜 committed
75 76
    setQuotaList(newQuotaList);
  };
涂茜's avatar
涂茜 committed
77 78 79 80 81 82 83 84 85 86 87

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

  // 关闭模态框
  const handleCancel = (e) => {
    if (e.target.innerHTML === cancelText) {
      onModalCancel && onModalCancel();
    } else {
88
      onModalClose && onModalClose();
涂茜's avatar
涂茜 committed
89 90 91 92
      setVisible(false);
    }
  };

涂茜's avatar
涂茜 committed
93
  const onOk = () => {
涂茜's avatar
涂茜 committed
94 95 96 97
    onModalOk && onModalOk();
    setVisible(false);
  };

涂茜's avatar
涂茜 committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  // 切换重点与全部
  const onRadioChange = (e) => {
    if (e.target.value === 'all') {
      setQuotaList(allQuotaList);
    } else {
      filterEmphasisQuota();
    }
    setTargetValue(e.target.value);
  };

  // 搜索指标
  const onSearch = (e) => {
    if (e.type === 'keydown' || e.target.value === '') {
      if (e.target.value !== '') {
        let newQuotaList = [];
        quotaList.forEach((item) => {
涂茜's avatar
涂茜 committed
114
          if (item.name.indexOf(e.target.value) > -1) newQuotaList.push(item);
涂茜's avatar
涂茜 committed
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
        });
        setQuotaList(newQuotaList);
      } else {
        if (targetValue === 'all') {
          setQuotaList(allQuotaList);
        } else {
          filterEmphasisQuota();
        }
      }
    }
  };

  // 处理复选框点击事件
  const handleCheckboxChange = (e) => {
    let newQuotaList = [...allQuotaList];
    let curSelectKey = [];
    let curSelectList = [...selectData];
    let data = curSelectList.filter((item) => item.title === e.target.value);
    if (data.length) {
      curSelectList = curSelectList.filter((item) => item.title !== e.target.value);
    } else {
      curSelectList.push({ key: e.target.value, title: e.target.value });
    }
    newQuotaList.forEach((item) => {
      if (item.title === e.target.value) {
        item.checked = !item.checked;
      }
    });
    curSelectKey = curSelectList.map((item) => item.key);
    onCheckboxChange({
      selectKey: curSelectKey,
      selectList: curSelectList,
    });
    setAllQuotaList(newQuotaList);
  };

  // 处理取消选择按钮点击事件
  const handleCancelSelect = ({ title }) => {
    let data = [...selectData];
    data = data.filter((item) => item.title !== title);
    onCancelSelect({
      selectKey: data.map((item) => item.key),
      selectList: 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);
      }
    }

    onTreeDrop({
      selectKey: data.map((item) => item.key),
      selectList: data,
    });
  };

涂茜's avatar
涂茜 committed
221 222 223
  return (
    <div className={classNames(prefixCls)}>
      <Button {...buttonProps} onClick={showModal} />
涂茜's avatar
涂茜 committed
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
      {visible && (
        <Modal
          centered
          width={width}
          title={title}
          cancelText={cancelText}
          okText={okText}
          visible={true}
          onCancel={handleCancel}
          onOk={onOk}
          className={classNames(`${prefixCls}-modal`)}
        >
          <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} defaultValue={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>
涂茜's avatar
涂茜 committed
271
              </div>
涂茜's avatar
涂茜 committed
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
              <div className={classNames(`${prefixCls}-modal-option-wrap`)}>
                {!quotaList.length && <Empty />}
                <Row gutter={[0, 6]}>
                  {!!quotaList.length &&
                    quotaList.map((item) => (
                      <Col span={8} key={item.key}>
                        <Checkbox
                          value={item.title}
                          checked={item.checked}
                          disabled={
                            (selectData.length > maximum || selectData.length === maximum) &&
                            !item.checked
                          }
                          onChange={handleCheckboxChange}
                        >
                          {item.title}
                        </Checkbox>
                      </Col>
                    ))}
                </Row>
涂茜's avatar
涂茜 committed
292 293
              </div>
            </div>
涂茜's avatar
涂茜 committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
            <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>
                      }
                    />
涂茜's avatar
涂茜 committed
310
                  ))}
涂茜's avatar
涂茜 committed
311 312
                </Tree>
              </div>
涂茜's avatar
涂茜 committed
313 314
            </div>
          </div>
涂茜's avatar
涂茜 committed
315 316
        </Modal>
      )}
涂茜's avatar
涂茜 committed
317 318 319 320 321 322 323 324 325
    </div>
  );
};

QuotaSelect.defaultProps = {
  buttonProps: {},
  width: 900,
  title: '选择显示字段',
  cancelText: '取消选择',
涂茜's avatar
涂茜 committed
326
  okText: '确定',
涂茜's avatar
涂茜 committed
327 328 329 330 331 332 333 334
  placeholder: '搜索关键词',
  searchPrefix: <SearchOutlined />,
  maximum: 0,
  dataSource: [],
  selectData: [],
  treeProps: {},
  onModalCancel: () => {},
  onModalOk: () => {},
335
  onModalClose: () => {},
涂茜's avatar
涂茜 committed
336
  onCancelSelect: () => {},
涂茜's avatar
涂茜 committed
337
  onTreeDrop: () => {},
涂茜's avatar
涂茜 committed
338 339 340 341 342 343 344
};

QuotaSelect.propTypes = {
  buttonProps: PropTypes.object,
  width: PropTypes.number,
  title: PropTypes.string,
  cancelText: PropTypes.string,
涂茜's avatar
涂茜 committed
345
  okText: PropTypes.string,
涂茜's avatar
涂茜 committed
346 347 348 349 350 351 352 353
  placeholder: PropTypes.string,
  searchPrefix: PropTypes.node,
  maximum: PropTypes.number,
  dataSource: PropTypes.array,
  selectData: PropTypes.array,
  treeProps: PropTypes.object,
  onModalCancel: PropTypes.func,
  onModalOk: PropTypes.func,
354
  onModalClose: PropTypes.func,
涂茜's avatar
涂茜 committed
355
  onCancelSelect: PropTypes.func,
涂茜's avatar
涂茜 committed
356
  onTreeDrop: PropTypes.func,
涂茜's avatar
涂茜 committed
357 358 359
};

export default QuotaSelect;