ParmarsModal.jsx 9.41 KB
Newer Older
1
import React, { useState, useRef, useContext, useEffect } from 'react';
2
import { Modal, Form, Table, Input, Button, message, Select, Tag } from 'antd';
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 44 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
import { DeleteOutlined } from '@ant-design/icons';
import styles from './ParmarsModal.less';
const EditableContext = React.createContext(null);
const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};
const EditableCell = ({
  dataSource,
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);
  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };
  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({
        ...record,
        ...values,
      });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };
  let childNode = children;
  let keyNameRule = [
    {
      required: true,
      message: `${title}不能为空`,
    },
    {
      validator: (rule, value) => {
        let list = JSON.parse(JSON.stringify(dataSource));
        // 合并内置字段
        if (value && list.some((item, i) => item.field === value && item.key !== record.key)) {
          return Promise.reject(new Error('参数称重复,请重新输入'));
        }
        return Promise.resolve();
      },
    },
  ];
  let rules = dataIndex === 'field' ? keyNameRule : [];
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
  const rendeFrom = () => {
    if (dataIndex === 'defaultValue' && record.type === '选择型') {
      let options = record.valueDesc
        .split(';')
        .map(item => ({ label: item.split(':')[1], value: item.split(':')[0] }));

      return (
        <Select
          // showSearch
          placeholder="选择值"
          optionFilterProp="children"
          optionLabelProp="value"
          // filterOption={(input, option) =>
          //   (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
          // }
          options={options}
          ref={inputRef}
          onPressEnter={save}
          onBlur={save}
        />
      );
    }
    return (
      <Input
94
        readOnly={record.releaseDate && dataIndex !== 'defaultValue'}
95 96 97 98 99 100
        ref={inputRef}
        onPressEnter={save}
        onBlur={save}
      />
    );
  };
101 102 103 104 105 106 107 108 109
  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={rules}
      >
110
        {rendeFrom()}
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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
      </Form.Item>
    ) : (
      <div className="editable-cell-value-wrap" onClick={toggleEdit}>
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};
const ParmarsModal = props => {
  const { pageUrl, visible, handleCancel, parmarCallBack, menuParmar, codeParam } = props;
  const [dataSource, setDataSource] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [count, setCount] = useState(0);

  useEffect(() => {
    if (visible) {
      // 给url通过字符串分割成表单需要的数据形式

      let parmas = pageUrl
        .split('|')[1]
        ?.split('&')
        ?.map((item, index) => {
          let obj = {
            field: item.split('=')[0],
            defaultValue: item.split('=')[1],
          };

          return obj;
        });

      if (!parmas) {
        parmas = [];
      }

      let codeParams = codeParam || [];
      console.log(menuParmar, codeParams, parmas, 'menuParmar');
      let finalArray = [];
      if (menuParmar) {
        finalArray = menuParmar?.concat(codeParams, parmas).reduce((acc, cur) => {
          let existingIndex = acc.findIndex(item => item.field === cur.field);
          if (existingIndex !== -1) {
            acc[existingIndex] = Object.assign(acc[existingIndex], cur);
          } else {
            acc.push(cur);
          }
          return acc;
        }, []);
      } else {
        finalArray = parmas;
      }

      console.log(finalArray.map((item, index) => ({ ...item, key: index })));
      let select = [];
      let newList = finalArray.map((item, index) => {
        if (parmas.some(ele => ele.field === item.field)) {
          select.push(index);
        }
        return { ...item, key: index };
      });
      setCount(finalArray.length);
      setDataSource(newList);
174
      debugger;
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
      setSelectedRowKeys(select);
    } else {
      setDataSource([]);
      setSelectedRowKeys([]);
      setCount(0);
    }
  }, [visible]);

  const onFinish = () => {
    console.log(selectedRowKeys, dataSource, 'selectedRowKeys');
    if (dataSource.some(item => !item.field)) {
      message.error('参数名称不能为空');
      return;
    }

    let selectSet = new Set(selectedRowKeys);
    let list = dataSource.reduce((acc, cur) => {
      console.log(acc, 'accc');
      if (selectSet.has(cur.key)) {
        acc.push(cur);
      }
      return acc;
    }, []);
    let parma = list.map(item => `${item.field}=${item.defaultValue}`).join('&');
    let parmas = dataSource.map(item => ({
      field: item.field,
      defaultValue: item.defaultValue,
      paramDesc: item.paramDesc,
203
      name: item.name,
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
    }));
    if (parma) {
      parmarCallBack(`${pageUrl.split('|')[0]}|${parma}`, parmas);
    } else {
      parmarCallBack(`${pageUrl.split('|')[0]}`, parmas);
    }
    console.log(list, 'list');
  };
  const handleDelete = key => {
    const newData = dataSource.filter(item => item.key !== key);
    const newSelect = selectedRowKeys.filter(item => item !== key);
    setSelectedRowKeys(newSelect);
    setDataSource(newData);
  };
  const defaultColumns = [
    {
      title: '序号',
      align: 'center',
      width: 50,
      render: (text, record, index) => <span>{index + 1}</span>,
    },
225 226 227 228 229 230 231 232 233 234 235
    {
      title: '类型',
      align: 'center',
      width: 70,
      render: (text, record) => {
        if (record.releaseDate) {
          return <Tag color="cyan">内置</Tag>;
        }
        return <Tag color="purple">自定义</Tag>;
      },
    },
236
    {
237 238 239
      title: '配置项',
      dataIndex: 'name',
      width: 250,
240 241 242
      editable: true,
    },
    {
243 244 245
      title: '参数名',
      dataIndex: 'field',
      width: 150,
246 247
      editable: true,
    },
248

249
    {
250 251 252
      title: '参数值',
      dataIndex: 'defaultValue',
      width: 150,
253 254
      editable: true,
    },
255

256
    {
257
      title: '参数配置说明',
258
      dataIndex: 'paramDesc',
259 260 261 262 263 264 265
      width: 250,
      editable: true,
    },

    {
      title: '操作',
      dataIndex: '',
266
      width: 50,
267 268 269 270 271 272
      align: 'center',
      render: (_, record) =>
        dataSource.length >= 1 ? (
          <Button
            style={{ border: 'none', padding: '4px 5px', background: 'none' }}
            onClick={() => handleDelete(record.key)}
273
            disabled={!!record.releaseDate}
274 275
          >
            <DeleteOutlined
276
              style={{ fontSize: '16px', color: `${record.releaseDate ? '#ccc' : '#e86060'}` }}
277 278 279 280 281 282 283 284 285 286 287 288
            />
          </Button>
        ) : null,
    },
  ];
  // 添加
  const handleAdd = () => {
    const newData = {
      key: count,
      field: '',
      defaultValue: '',
      paramDesc: '',
289
      name: '',
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 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 372 373 374 375 376 377 378
    };
    console.log(newData, 'newData');
    setDataSource([...dataSource, newData]);
    setSelectedRowKeys([...selectedRowKeys, count]);
    setCount(count + 1);
  };
  const handleSave = row => {
    const newData = [...dataSource];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    setDataSource(newData);
  };
  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };
  const columns = defaultColumns.map(col => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: record => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        dataSource,
        handleSave,
      }),
    };
  });
  // 表格复选框
  const onSelectChange = newSelectedRowKeys => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    getCheckboxProps: record => ({
      disabled: record.required,
    }),
  };
  return (
    <>
      <Modal
        title="参数配置"
        width="1100px"
        visible={visible}
        onOk={onFinish}
        onCancel={handleCancel}
        maskClosable={false}
        destroyOnClose
        centered
      >
        <div className={styles.contentParmars}>
          <Button
            onClick={handleAdd}
            type="primary"
            style={{
              marginBottom: 16,
            }}
          >
            添加参数
          </Button>
          <Table
            components={components}
            rowSelection={rowSelection}
            size="small"
            rowClassName={() => 'editable-row'}
            bordered
            dataSource={dataSource}
            columns={columns}
            scroll={{ y: '340px' }}
            pagination={false}
          />
        </div>
      </Modal>
    </>
  );
};

export default ParmarsModal;