loadGroupNew.jsx 11.8 KB
Newer Older
1 2
import React, { useState, useEffect } from 'react';
import { Modal, Spin, Table, Button, notification, Form, Input } from 'antd';
3
import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
4 5
import { HTML5Backend } from 'react-dnd-html5-backend';
import { DndProvider } from 'react-dnd';
6
import { LoadFieldsByGroup, LoadGroup, ChangeOrder } from '@/services/tablemanager/tablemanager';
7 8 9 10 11 12 13 14
import DraggableBodyRow from './DraggableBodyRow';
import styles from './index.less';
const LoadGroupNew = props => {
  const { onCancel, visible, formObj, callBackSubmit } = props;
  const [groupData, setGroupData] = useState(null); // 分组后的数组
  const [pickIndex, setPickIndex] = useState(0); // 当前选中的索引
  const [loading, setLoading] = useState(false); // 数据是否加载完毕
  const [isModalVisible, setIsModalVisible] = useState(false); // 添加分组弹窗是否显示
15 16
  const [dragType, setDragType] = useState(); // 拖拽的是分组还是字段
  const [modalType, setModalType] = useState(); // 模态类型
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 54 55 56 57 58 59 60 61 62 63
  const [form] = Form.useForm();
  useEffect(() => {
    if (visible) {
      // 获取分组名称
      let p1 = new Promise((resolve, reject) => {
        setLoading(true);
        LoadGroup({ tableName: formObj.tableName })
          .then(res => {
            setLoading(false);
            if (res.code === 0) {
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch(err => {
            reject(err);
            setLoading(false);
          });
      });
      p1.then(res => {
        // 获取字段数据
        let arr = res.data.root.map(item => item.text);
        LoadFieldsByGroup({
          tableName: formObj.tableName,
          groupName: arr.join(','),
        }).then(response => {
          setLoading(false);
          if (response.code === 0) {
            res.data.root.forEach(item => {
              item.fieldData = [];
              response.data.root.forEach(element => {
                if (element.Group === item.text) {
                  item.fieldData.push(element);
                }
              });
            });
            setGroupData(res.data.root);
          }
        });
      });
    }
  }, [visible]);
  const columns = [
    {
      title: '字段名',
      dataIndex: 'Name',
64
      width: 250,
65 66 67 68 69
      key: 'Name',
    },
    {
      title: '形态',
      dataIndex: 'Shape',
70
      width: 120,
71 72 73 74 75 76 77 78
      key: 'Shape',
    },
  ];
  const columnsGroup = [
    {
      title: '组名称',
      dataIndex: 'text',
      key: 'text',
邓超's avatar
邓超 committed
79 80 81 82 83
      render: (text, record) => (
        <div>
          {text} <span>({record.fieldData.length})</span>
        </div>
      ),
84 85 86 87 88 89
    },
  ];
  const components = {
    body: {
      row: DraggableBodyRow,
    },
90 91 92
    style: {
      backgroundColor: 'red',
    },
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
  };
  // 提交
  const onSubumit = () => {
    setLoading(true);
    let arr = [];
    groupData.forEach(item => {
      item.fieldData.forEach(ele => {
        arr.push({ groupName: item.text, ID: ele.ID });
      });
    });

    ChangeOrder(arr).then(res => {
      setLoading(false);
      if (res.code === 0) {
        notification.success({
          message: '提示',
          duration: 3,
          description: '编辑成功',
        });
        callBackSubmit();
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };
  // 移动数组元素到指定位置
  const moveInArray = (arr, from, to) => {
    // 确保是有效数组
    if (Object.prototype.toString.call(arr) !== '[object Array]') {
      throw new Error('Please provide a valid array');
    }
    // 删除当前的位置
    let item = arr.splice(from, 1);
    // 确保还剩有元素移动
    if (!item.length) {
      throw new Error(`There is no item in the array at index ${from}`);
    }
    // 移动元素到指定位置
    arr.splice(to, 0, item[0]);
    return arr;
  };
  // 拖拽表格
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
  const moveRow = (dragIndex, hoverIndex, tableType, dragTypes) => {
    // console.log(dragIndex, hoverIndex, tableType, dragTypes);
    if (dragTypes === 'field') {
      // 拖拽体为字段
      if (tableType === 'field') {
        // 字段换位
        setGroupData(val => {
          let newData = JSON.parse(JSON.stringify(val));
          newData[pickIndex].fieldData = moveInArray(
            newData[pickIndex].fieldData,
            dragIndex,
            hoverIndex,
          );
          return newData;
        });
      } else {
        // 字段拖拽到组
        if (hoverIndex === pickIndex) {
          return;
        }
        setGroupData(val => {
          let newData = JSON.parse(JSON.stringify(val));
          newData[hoverIndex].fieldData.push(newData[pickIndex].fieldData[dragIndex]);
          newData[pickIndex].fieldData.splice(dragIndex, 1);
          return newData;
        });
165
      }
166 167
    } else {
      // 组拖拽
168 169
      setGroupData(val => {
        let newData = JSON.parse(JSON.stringify(val));
170
        newData = moveInArray(newData, dragIndex, hoverIndex);
171 172
        return newData;
      });
173
      setPickIndex(hoverIndex);
174 175 176
    }
  };
  // 点击行添加样式
177
  const setRowClassName = (record, index) => (index === pickIndex ? styles.clickRowStyle : '');
178
  // 新增分组
179 180 181 182 183 184 185 186
  const addGroup = type => {
    setModalType(type);
    if (type === 'add') {
      form.resetFields();
    } else {
      form.setFieldsValue({ groupName: groupData[pickIndex].text });
    }

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    setIsModalVisible(true);
  };

  // 删除分组
  const delGroup = () => {
    if (groupData[pickIndex].text === '(未分组)') {
      notification.error({
        message: '提示',
        duration: 3,
        description: '默认分组不能删除',
      });
      return;
    }
    setGroupData(val => {
      let newData = JSON.parse(JSON.stringify(val));
202
      let defaultGroupIndex = newData.findIndex(item => item.text === '(未分组)');
203 204 205 206 207 208 209 210 211 212 213 214
      newData[defaultGroupIndex].fieldData = [
        ...newData[defaultGroupIndex].fieldData,
        ...newData[pickIndex].fieldData,
      ];
      newData.splice(pickIndex, 1);
      // 删除后指向未分组
      setPickIndex(defaultGroupIndex);
      return newData;
    });
  };
  // 保存新建分组
  const handleOk = () => {
215 216 217 218 219 220 221 222
    if (!form.getFieldsValue().groupName) {
      notification.error({
        message: '提示',
        duration: 3,
        description: '请填写组名',
      });
      return;
    }
223
    // 判断是否有重复的组名
224
    let isRepeat = groupData.some(item => item.text === form.getFieldsValue().groupName);
225 226 227 228 229 230 231 232
    if (isRepeat) {
      notification.error({
        message: '提示',
        duration: 3,
        description: '该组名已存在',
      });
      return;
    }
233 234 235 236 237
    if (modalType === 'add') {
      let obj = {
        text: form.getFieldsValue().groupName,
        fieldData: [],
      };
238 239 240 241 242
      setGroupData(val => {
        let newData = JSON.parse(JSON.stringify(val));
        newData.push(obj);
        return newData;
      });
243 244 245 246 247 248
    } else {
      setGroupData(val => {
        let newData = JSON.parse(JSON.stringify(val));
        newData[pickIndex].text = form.getFieldsValue().groupName;
        return newData;
      });
249
    }
250
    setIsModalVisible(false);
251 252 253 254 255 256 257 258 259 260
  };
  return (
    <div>
      <Modal
        title="字段配置"
        visible={visible}
        onOk={onSubumit}
        onCancel={onCancel}
        maskClosable={false}
        destroyOnClose
261
        width="680px"
262 263 264 265 266 267 268 269 270 271 272
      >
        <div
          className="button_content"
          style={{
            display: 'flex',
            justifyContent: 'flex-end',
            marginBottom: '10px',
            marginRight: '11px',
          }}
        >
          <Button
273
            onClick={() => addGroup('add')}
274 275 276 277 278 279 280 281 282
            style={{
              display: 'flex',
              alignItems: 'center',
              marginRight: '1rem',
            }}
          >
            添加分组
            <PlusOutlined />
          </Button>
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
          <Button
            disabled={pickIndex === 0}
            type="primary"
            ghost
            onClick={() => addGroup('edit')}
            style={{
              display: 'flex',
              alignItems: 'center',
              marginRight: '1rem',
            }}
          >
            编辑分组
            <EditOutlined />
          </Button>
          <Button
            danger
            disabled={pickIndex === 0}
            onClick={delGroup}
            style={{ display: 'flex', alignItems: 'center' }}
          >
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
            删除分组
            <DeleteOutlined />
          </Button>{' '}
        </div>
        <Spin spinning={loading}>
          <DndProvider backend={HTML5Backend}>
            {groupData && (
              <div
                className="table_box"
                style={{
                  display: 'flex',
                  justifyContent: 'center',
                  height: '550px',
                  marginBottom: '20px',
                }}
              >
                {/* 组名称表 */}
                <Table
                  bordered
                  rowKey={record => record.text}
323
                  style={{ width: '200px' }}
324 325 326 327 328 329
                  columns={columnsGroup}
                  dataSource={groupData}
                  components={components}
                  size="small"
                  scroll={{ y: 510 }}
                  pagination={false}
330
                  rowClassName={(record, index) => setRowClassName(record, index)}
331 332 333
                  onRow={(record, index) => ({
                    tableType: 'group',
                    index,
334 335 336 337 338
                    pickIndex,
                    dragType,
                    onMouseEnter: event => {
                      setDragType('group');
                    }, // 点击行
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
                    moveRow,
                    onClick: event => {
                      event.stopPropagation();
                      setPickIndex(index);
                    }, // 点击行
                  })}
                />
                <div
                  className="line"
                  style={{
                    width: '1px',
                    backgroundColor: 'rgb(153, 187, 232)',
                    margin: '0 15px',
                  }}
                />
                {/* 字段名表 */}
                <Table
                  bordered
                  columns={columns}
358
                  style={{ width: '400px' }}
359 360 361 362 363 364 365 366
                  rowKey={record => record.Name}
                  dataSource={groupData[pickIndex].fieldData}
                  components={components}
                  size="small"
                  pagination={false}
                  scroll={{ y: 510 }}
                  onRow={(record, index) => ({
                    tableType: 'field',
367 368
                    pickIndex,
                    dragType,
369
                    index,
370 371 372
                    onMouseEnter: event => {
                      setDragType('field');
                    }, // 点击行
373 374 375 376 377 378 379 380 381
                    moveRow,
                  })}
                />
              </div>
            )}
          </DndProvider>
        </Spin>
        {/* 添加分组弹窗 */}
        <Modal
382
          title={modalType === 'add' ? '添加分组' : '编辑分组'}
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
          style={{ top: '200px' }}
          visible={isModalVisible}
          maskClosable={false}
          onOk={() => handleOk()}
          onCancel={() => {
            setIsModalVisible(false);
            form.resetFields();
          }}
        >
          <Form
            form={form}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 18 }}
            initialValues={{ remember: true }}
          >
            <Form.Item label="添加分组" name="groupName">
              <Input placeholder="请输入分组名称" />
            </Form.Item>
          </Form>
        </Modal>
      </Modal>
    </div>
  );
};

export default LoadGroupNew;