FormArray.js 16.9 KB
Newer Older
王绍森's avatar
王绍森 committed
1
import {
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
	Col,
	Form,
	Input,
	Select,
	DatePicker,
	TimePicker,
	Checkbox,
	Button,
	Radio,
	Switch,
	Upload,
	Icon,
	InputNumber,
	Cascader,
	TreeSelect,
	message,
王绍森's avatar
王绍森 committed
18 19 20 21 22 23 24 25 26 27 28 29
} from 'antd';
import React, { Component, Fragment } from 'react';
import styles from './index.less';
import PropTypes from 'prop-types';
import moment from 'moment';
import { countSpecialField } from '@/baseComponent/utils';
import TableSelect from './TableSelect';
import ChildForm from './ChildForm';
import ReactQuill from 'react-quill';
import baseConfig from '@/config/config';
import 'react-quill/dist/quill.snow.css';
import ButtonUpload from './ButtonUpload';
30
import { getToken } from '@/webPublic/one_stop_public/utils/token';
31 32 33 34
import {
  getSassApiHeader,
  getSysCode
} from '@/webPublic/one_stop_public/2023yunshangguizhou/utils';
王绍森's avatar
王绍森 committed
35 36 37 38 39 40 41 42 43 44

const RadioGroup = Radio.Group;
const Option = Select.Option;
const { TextArea } = Input;
const FormItem = Form.Item;

const CheckboxGroup = Checkbox.Group;
const { MonthPicker, RangePicker } = DatePicker;

const quillConfig = {
45 46 47 48 49 50 51
	toolbar: [
		[{ size: [] }],
		['bold', 'italic', 'underline', 'strike', 'blockquote'],
		[{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
		['link', 'image', 'video'],
		['clean'],
	],
王绍森's avatar
王绍森 committed
52 53 54
};

const ColDom = ({ children, filedSpan }) => {
55 56 57 58 59 60 61 62 63 64 65
	const bigSpan = Math.ceil(24 / filedSpan.big);
	const smallSpan = Math.ceil(24 / filedSpan.small);
	return (
		<Col
			xl={smallSpan}
			xxl={bigSpan}
			className={styles.colDom}
			style={countSpecialField(filedSpan.big)}>
			{children}
		</Col>
	);
王绍森's avatar
王绍森 committed
66 67 68
};

const FormItemDom = ({ info, children, nameSpan }) => {
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
	return (
		<FormItem
			label={info.name}
			required={info.required || false}
			labelCol={{
				xl: nameSpan.small,
				xxl: nameSpan.big,
			}}
			wrapperCol={{
				xl: 24 - nameSpan.small,
				xxl: 24 - nameSpan.big,
			}}
			colon={false}>
			{children}
		</FormItem>
	);
王绍森's avatar
王绍森 committed
85 86 87
};

export default class FormArray extends Component {
88 89 90 91 92 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 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
	constructor(props) {
		super(props);
		this.state = {};
	}

	formatTime = (time, formatTimeConfig = 'YYYY-MM-DD HH:mm') => {
		return moment(time);
	};

	datePickerOnchange = (dateString, key) => {
		const { changeValue } = this.props;
		changeValue(dateString, key);
	};

	defaultPropsCount = (info, value) => {
		const itemDisabled = typeof info.disabled !== 'undefined' ? info.disabled : false;
		const readOnly = typeof info.readOnly !== 'undefined' ? info.readOnly : false;
		const placeholder = typeof info.placeholder !== 'undefined' ? info.placeholder : '';
		const options = typeof info.options !== 'undefined' ? info.options : [];
		let itemValue = typeof value[info.key] === 'undefined' ? '' : value[info.key];
		if (['select', 'radioGroup'].indexOf(info.type) > -1) {
			itemValue = typeof itemValue === 'number' ? itemValue.toString() : itemValue;
			itemValue = typeof itemValue === 'boolean' ? itemValue + '' : itemValue;
		} else if (['selectMultiple', 'checkBoxMutiple', 'cascader'].indexOf(info.type) > -1) {
			itemValue = typeof itemValue === 'number' ? itemValue.toString() : itemValue;
			// 数字变成 字符串

			itemValue = typeof itemValue === 'string' && itemValue ? itemValue.split(',') : itemValue;
			// 有值且值是字符串则 变成数组

			itemValue = !itemValue ? [] : itemValue;
			// 没有值则变成空数组

			for (let i = 0; i < itemValue.length; i++) {
				itemValue[i] = typeof itemValue[i] === 'number' ? itemValue[i].toString() : itemValue[i];
				// 每一个值数字变成字符串
			}
		} else if (['datePicker', 'monthPicker', 'timePicker'].indexOf(info.type) > -1) {
			if (typeof itemValue !== 'object') {
				if (itemValue) {
					if (!isNaN(parseInt(itemValue)) && parseInt(itemValue) > 10000000) {
						itemValue = parseInt(itemValue);
						itemValue = moment(itemValue);
					} else {
						if (info.format) {
							itemValue = moment(itemValue, info.format);
						} else {
							itemValue = moment(itemValue);
						}
					}
				} else {
					itemValue = null;
				} /*格式化时间*/
			}
		} else if (['rangePicker'].indexOf(info.type) > -1) {
			if (typeof itemValue !== 'object') {
				let endValue = typeof value[info.endKey] === 'undefined' ? null : value[info.endKey];
				if (itemValue) {
					if (!isNaN(parseInt(itemValue)) && parseInt(itemValue) > 10000000) {
						itemValue = parseInt(itemValue);
					}
					if (!isNaN(parseInt(endValue)) && parseInt(endValue) > 10000000) {
						endValue = parseInt(endValue);
					}
					itemValue = [moment(itemValue), moment(endValue)];
				} else {
					itemValue = undefined;
				}
			}
		} else if (info.type === 'checkBox') {
			itemValue = !!itemValue;
		} else if (info.type === 'switch') {
			itemValue = !!value[info.key];
		}
		/*if(info.type === 'selectPeople'){
王绍森's avatar
王绍森 committed
163 164 165
      itemValue = typeof itemValue !== 'object' ? {key:itemValue,label: ''} : itemValue;
    }*/

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 223 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 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
		const defaultProps = {
			readOnly: this.props.readOnly ? true : readOnly,
			disabled: this.props.disabled ? true : itemDisabled,
			value: itemValue,
			placeholder: placeholder,
			options: options,
			className: styles[info.className] || '',
		};
		if (typeof info.precision !== 'undefined') {
			defaultProps.precision = info.precision;
		}
		return defaultProps;
	};

	rangeOnChange = (dateStrings = [], key, endKey) => {
		const { changeValue } = this.props;
		changeValue(dateStrings[0], key);
		changeValue(dateStrings[1], endKey);
	};

	changeInputNumber = (value, config) => {
		if (typeof value === 'number') {
			if (typeof config.min !== 'undefined' && value < config.min) {
				message.warning(`${config.name}不能小于${config.min}`);
			} else if (typeof config.max !== 'undefined' && value > config.max) {
				message.warning(`${config.name}不能大于${config.max}`);
			}
		}
	};

	domAssembly = () => {
		const { changeValue, value, config, fileSpan, nameSpan } = this.props;
		return config.map((info, i) => {
			let fieldDom = null;
			const defaultProps = this.defaultPropsCount(info, value);
			switch (info.type) {
				case 'input': // 普通文本
					fieldDom = (
						<Input
							{...defaultProps}
							style={info.style || {}}
							onChange={(e) => {
								changeValue(e.target.value, info.key);
							}}
						/>
					);
					break;
				case 'inputNumber': // 数字文本
					fieldDom = (
						<Fragment>
							<InputNumber
								{...defaultProps}
								style={info.style || { width: '100%' }}
								min={info.min ? info.min : 0}
								max={info.max ? info.max : Infinity}
								onChange={(value) => {
									this.changeInputNumber(value, info);
									changeValue(value, info.key);
								}}
							/>
							{info.formatter ? <span>{info.formatter}</span> : ''}
						</Fragment>
					);
					break;
				case 'idCard':
					fieldDom = (
						<Fragment>
							<Input
								{...defaultProps}
								style={info.style || {}}
								onChange={(e) => {
									changeValue(e.target.value, info.key);
								}}
							/>
						</Fragment>
					);
					break;
				case 'phone':
					fieldDom = (
						<Fragment>
							<InputNumber
								{...defaultProps}
								style={info.style || { width: '100%' }}
								min={0}
								max={info.max ? info.max : Infinity}
								onChange={(value) => {
									changeValue(value, info.key);
								}}
							/>
						</Fragment>
					);
					break;
				case 'checkBoxMutiple': // 多选 checkbox
					fieldDom = (
						<CheckboxGroup
							{...defaultProps}
							onChange={(value) => {
								changeValue(value, info.key);
							}}
						/>
					);
					break;
				case 'cascader': // 级联选择
					fieldDom = (
						<Cascader
							value={defaultProps.value}
							options={defaultProps.options}
							style={{ width: '100%' }}
							onChange={(value, selectedOptions) => {
								changeValue(value, info.key);
							}}
						/>
					); // 返回数组 [parent,child]
					break;
				case 'selectMultiple': // 下拉多选
					fieldDom = (
						<Select
							{...defaultProps}
							mode="multiple"
							allowClear
							style={{ width: '100%' }}
							onChange={(value) => {
								changeValue(value, info.key);
							}}>
							{defaultProps.options.map((optionItem) => {
								return (
									<Option
										key={
											typeof optionItem.key !== 'boolean' ? optionItem.key + '' : optionItem.key
										}>
										{optionItem.name}
									</Option>
								);
							})}
						</Select>
					);
					break;
				case 'select': // 下拉单选
					fieldDom = (
						<Select
							{...defaultProps}
							style={{ width: '100%' }}
							allowClear={typeof info.allowClear !== 'undefined' ? info.allowClear : true}
							onChange={(value) => {
								changeValue(value, info.key);
							}}>
							{defaultProps.options.map((optionItem) => {
								return (
									<Option
										key={typeof optionItem.key !== 'boolean' ? optionItem.key + '' : optionItem.key}
										disabled={optionItem.disabled}>
										{optionItem.name}
									</Option>
								);
							})}
						</Select>
					);
					break;
				case 'tableSelect':
					fieldDom = (
						<TableSelect
							config={info}
							value={defaultProps.value}
							onChange={changeValue}
							disabled={defaultProps.disabled}
						/>
					);
					break;
				case 'childForm':
					fieldDom = (
						<ChildForm
							config={info}
							value={defaultProps.value}
							onChange={changeValue}
							disabled={defaultProps.disabled}
						/>
					);
					break;
				case 'checkBox': // 布尔值选择
					fieldDom = (
						<Checkbox
							checked={defaultProps.value}
							disabled={defaultProps.disabled}
							onChange={(e) => {
								changeValue(e.target.checked, info.key);
							}}>
							{info.text}
						</Checkbox>
					);
					break;
				/*  case 'editable': // 可编辑的富文本
王绍森's avatar
王绍森 committed
357 358 359 360 361 362 363 364 365
            fieldDom = <div className={styles.Editable}>
              <Editable onChange={changeValue}
                        filedKey={info.key}
                        disabled={defaultProps.disabled}
                        value={defaultProps.value}
              />
            </div>;
            break;*/

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 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 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
				case 'datePicker': // 日期选择
					fieldDom = (
						<DatePicker
							showTime={info.showTime}
							{...defaultProps}
							style={{ width: '100%' }}
							format={info.format}
							onChange={(date, dateString) => {
								this.datePickerOnchange(dateString, info.key);
							}}
						/>
					);
					break;
				case 'timePicker': // 日期选择
					fieldDom = (
						<TimePicker
							{...defaultProps}
							style={{ width: '100%' }}
							format={info.format || 'HH:mm'}
							onChange={(date, dateString) => {
								this.datePickerOnchange(dateString, info.key);
							}}
						/>
					);
					break;
				case 'rangePicker': // 时间段选择
					if (info.disabledDate && info.disabledDate === 'afterYesterday') {
						// 禁用今天之前的时间
						defaultProps.disabledDate = (current) => {
							// Can not select days before today and today
							return current < moment().add(-1, 'days');
						};
					}
					fieldDom = (
						<RangePicker
							showTime={info.showTime}
							{...defaultProps}
							style={{ width: '100%' }}
							format={info.format}
							placeholder={info.placeholder || ['开始日期', '结束日期']}
							onChange={(dates, dateStrings) => {
								this.rangeOnChange(dateStrings, info.key, info.endKey);
							}}
						/>
					);
					break;

				case 'monthPicker': // 年月 选择
					fieldDom = (
						<MonthPicker
							{...defaultProps}
							style={{ width: '100%' }}
							format={info.format}
							onChange={(date, dateString) => {
								this.datePickerOnchange(dateString, info.key);
							}}
						/>
					);
					break;

				case 'textarea': // 文本框
					fieldDom = (
						<TextArea
							{...defaultProps}
							autoSize={{ minRows: 4, maxRows: 6 }}
							onChange={(e) => {
								changeValue(e.target.value, info.key);
							}}
						/>
					);
					break;
				case 'radioGroup': // 圆形 选择框
					fieldDom = (
						<RadioGroup
							value={defaultProps.value}
							disabled={defaultProps.disabled}
							style={{ width: '100%' }}
							onChange={(e) => {
								changeValue(e.target.value, info.key);
							}}>
							{defaultProps.options.map((optionItem) => {
								const radioValue =
									typeof optionItem.key !== 'boolean' ? optionItem.key + '' : optionItem.key;
								return (
									<Radio key={radioValue} value={radioValue}>
										{optionItem.name}
									</Radio>
								);
							})}
						</RadioGroup>
					);
					break;
				case 'switch': // 开关
					fieldDom = (
						<Switch
							{...defaultProps}
							checked={defaultProps.value}
							checkedChildren={info.checkedChildren || ''}
							unCheckedChildren={info.unCheckedChildren || ''}
							onChange={(e) => {
								changeValue(e, info.key);
							}}
						/>
					);
					break;
				case 'editor':
					let thisClassName = styles.editorLayout;
					if (info.className) {
						thisClassName = styles[info.className];
					}
					fieldDom = (
						<ReactQuill
							{...defaultProps}
							className={thisClassName}
							modules={quillConfig}
							onChange={(e) => {
								changeValue(e, info.key);
							}}
						/>
					);
					break;
				case 'upload':
					fieldDom = (
						<Upload
							action={baseConfig.uploadUrl + `&isConvert=${info.isConvert || false}`}
							accept={info.accept}
							multiple={info.multiple}
							{...defaultProps}
494
              headers={getSassApiHeader()}
495 496 497
              data={{
                token: getToken(),
              }}
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
							defaultFileList={value[info.key]}
							name="file"
							onChange={({ fileList }) => {
								changeValue(fileList, info.key);
							}}>
							<Button>
								<Icon type="upload" /> 上传
							</Button>
						</Upload>
					);

					break;
				case 'buttonUpload':
					fieldDom = (
						<ButtonUpload
							onChange={(url) => {
								changeValue(url, info.key);
							}}
							{...info}
							{...defaultProps}
						/>
					);
					break;
				case 'text':
					fieldDom = <div>{defaultProps.value || info.value}</div>;
					break;
				case 'TreeSelect':
					fieldDom = (
						<TreeSelect
							{...defaultProps}
							{...info.props}
							onChange={(v) => changeValue(v, info.key)}
						/>
					);
					break;
				case 'personalRender':
					fieldDom = info.render({ value, onChange: (v, key) => changeValue(v, key) });
					break;
				default:
					fieldDom = null;
					break;
			}
			return (
				<ColDom filedSpan={info.fileSpan || fileSpan} key={info.key + i}>
					<FormItemDom info={info} nameSpan={info.nameSpan || nameSpan}>
						{fieldDom}
					</FormItemDom>
				</ColDom>
			);
		});
	};

	render() {
		const { style } = this.props;
		return (
			<div className={styles.FormArray} style={style}>
				{this.domAssembly()}
			</div>
		);
	}
王绍森's avatar
王绍森 committed
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
}
/**
 * 最主要的 props 就是config.
 * config: 表单填写的每一个字段,根据type的不同渲染不同的组件,
 * 包含 [inputNumber(数字input),input,
 *      selectMultiple(多选下拉),select(单选下拉)
 *      checkBox(单选checkbox),
 *      checkBoxMutiple (多选checkbox)
 *      datePicker日期选择  value 传入 时间戳格式 等等
 *
 * 具体请查看下面的demo
 *
 * changeValue: 表单的值改变后的回调
 * value : 表单的值应该是一个对象state {name:'',phone:''....}
 * fileSpan : { big:5, small:4}
 *         small: 设置1366*768的屏幕 每一行显示几个字段  如 只显示3个 则 = 3
 *         big: 设置1920*1080的屏幕  每一行显示几个字段 同上
 * nameSpan { big:5, small:4}   同上设置 一个字段的 字段名和填写的值所占的比例
 * */

/**
 * 2019年3月7日
 * 钟是志
 * 增加对 时间段rangePicker选择的支持 具体使用见下面的 demo
 * */
FormArray.propTypes = {
584 585 586 587 588 589 590 591
	config: PropTypes.array,
	readOnly: PropTypes.bool,
	disabled: PropTypes.bool,
	changeValue: PropTypes.func,
	value: PropTypes.object,
	fileSpan: PropTypes.object,
	nameSpan: PropTypes.object,
	style: PropTypes.object,
王绍森's avatar
王绍森 committed
592 593
};
FormArray.defaultProps = {
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
	config: [
		{
			name: '数字选择',
			type: 'inputNumber',
			placeholder: '',
			key: 'scoreRank',
		},
		{
			name: '文本框',
			type: 'input',
			placeholder: '',
			key: 'scoreRank2',
		},
		{
			key: 'startDate',
			endKey: 'endDate',
			name: '时间段选择',
			type: 'rangePicker',
			format: 'YYYY-MM-DD',
			placeholder: ['开始时间', '结束时间'],
			required: true,
		},
		{
			name: '日期选择',
			type: 'datePicker',
			placeholder: '',
			key: 'scoreRank5',
		},
		{
			name: '下拉框选择',
			type: 'select',
			placeholder: '',
			key: 'scoreRank6',
		},
		{
			name: '下拉框多选',
			type: 'selectMultiple',
			placeholder: '',
			key: 'scoreRank7',
		},
		{
			key: 'studentType',
			name: 'checkBox多选',
			type: 'checkBoxMutiple',
			options: [
				{ label: '本科', value: '本科' },
				{ label: '专科', value: '专科' },
				{ label: '研究生', value: '研究生' },
			],
			required: true,
		},
	],
	changeValue: (value, key) => {},
	value: {},
	fileSpan: {
		big: 5,
		small: 4,
	},
	nameSpan: {
		big: 10,
		small: 12,
	},
	disabled: false,
	style: {},
王绍森's avatar
王绍森 committed
658
};