import React from 'react';
import {
	WeaFormItem,
	WeaSearchGroup,
} from 'ecCom';
import {
	WeaSwitch
} from 'comsMobx';
import {
	toJS
} from 'mobx';
import {
	Row,
	Col,
} from 'antd';

class MagicForm extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			usedAsForceUpdate: new Date()
		}
	}

	//监听表单元素事件的回调函数
	handleFormChange = (cb) => {
		const {
			onFormElementsChange,
			dynamicFields,
		} = this.props;

		dynamicFields && dynamicFields.map(field => {
			const {
				activeKey,
			} = field;

			if (Object.keys(cb)[0] === activeKey) {
				this.forceUpdate();
			}
		});
		//当父组件没有传onFormElementsChange属性时，不执行下面的回调函数。
		if (!onFormElementsChange) return;

		onFormElementsChange(cb);
	}

	//强制刷新组件
	forceUpdate = () => {
		this.setState({
			usedAsForceUpdate: new Date()
		});
	}

	//判断当前表单元素能否被渲染
	canRender = (domkey) => {
		const {
			dynamicFields,
			form
		} = this.props;

		//表单元素能否被渲染的标志：true -> 可以被渲染; false -> 不可以被渲染
		let flag = true;

		dynamicFields.map(field => {
			const {
				passiveKey,
				activeKey,
				showValue
			} = field;

			const showValueArray = showValue.split(',');
			//判断是否为被联动的表单元素（被动）
			if (domkey === passiveKey) {
				const activeValue = form.getFormParams()[activeKey];

				if (!showValueArray.includes(activeValue)) {
					flag = false;
				}
			}
		});

		return flag;
	}

	getSubComponent = (params) => {
		const {
			dirtyKeys, //需要被特殊渲染的表单元素的domkey集合
			dirtyComponent, //特殊组件
			classNames,
		} = this.props, {
			domkey,
			item,
			form,
			label
		} = params;

		if (dirtyKeys && dirtyKeys.includes(domkey)) {
			return dirtyComponent(params)
		} else {
			return (
				<div className={this.getClassName(domkey)}>
					<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@bbt74r`} 
						fieldConfig={item} 
						form={form} 
						formParams={form.getFormParams()} 
						onChange={this.handleFormChange}
					/>
					{this.getSiblingComponent(domkey, form)}
				</div>
			)
		}
	}

	getClassName = (domkey) => {
		const {
			classNames
		} = this.props;

		return this.isObjectHasDomkey(classNames, domkey) ? classNames[domkey] : '';
	}

	//获取WeaSwitch组件的相邻组件
	getSiblingComponent = (domkey, form) => {
		const {
			staticTips, //静态提示
			dynamicTips, //动态提示
			transverseSiblingComponents, //横向相邻组件
			longitudinalSiblingComponents, //纵向相邻组件
			customizations, //自定义组件
		} = this.props;

		let siblings = [];
		//静态提示
		if (this.isObjectHasDomkey(staticTips, domkey)) {
			siblings.push(staticTips[domkey]);
		}
		//动态提示
		if (this.isObjectHasDomkey(dynamicTips, domkey)) {
			siblings.push(<p style={{padding: '5px 0'}}>{ dynamicTips[domkey][parseInt(form.getFormParams()[domkey]) - 1] }</p>);
		}
		//横向相邻组件
		if (this.isObjectHasDomkey(transverseSiblingComponents, domkey)) {
			siblings.push(transverseSiblingComponents[domkey]);
		}
		//纵向相邻组件
		if (this.isObjectHasDomkey(longitudinalSiblingComponents, domkey)) {
			siblings.push(longitudinalSiblingComponents[domkey]);
		}
		//自定义组件
		if (this.isObjectHasDomkey(customizations, domkey)) {
			siblings.push(customizations[domkey]);
		}

		return siblings;
	}

	//判断domkey是否在容器中
	isObjectHasDomkey = (obj, domkey) => {
		return obj && Object.keys(obj).includes(domkey)
	}

	render() {
		const {
			conditions,
			form,
			isFormInit,
			dynamicFields, //动态域
			date, //刷新组件
			dirtyKeys,
			renderBlacklist, //不需要渲染的items，
			labels,
			wrapperStyle
		} = this.props, {
			usedAsForceUpdate
		} = this.state;

		if (!isFormInit) return null;

		//WeaFormItem组件的容器
		const formItemContainer = [];

		const translatedConditions = toJS(conditions);
		//conditions数据类型：数组或者对象
		const c = Array.isArray(translatedConditions) ? translatedConditions[0] : conditions;

		c.items.map((item, index) => {
			const {
				domkey,
			} = item;

			//判断当前表单元素是否需要被渲染
			if (dynamicFields && !this.canRender(domkey[0])) return

			if (renderBlacklist && renderBlacklist.includes(domkey[0])) return

			if (labels && Object.keys(labels).includes(domkey[0])) {
				item.label = labels[domkey[0]];
			}

			const isDirty = dirtyKeys ? dirtyKeys.includes(domkey[0]) : false;

			const {
				label,
				labelcol,
				fieldcol
			} = item;

			formItemContainer.push(
				<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@b74cs0@${index}`}
			        label={!isDirty ? label : ''}
			        colon={!isDirty ? true : false}
			        labelCol={{span: labelcol}}
			        wrapperCol={{span: fieldcol}}
			        error={!isDirty && form.getError(item) } 
	 				tipPosition='bottom'
	 				className={isDirty ? 'hrm-special-form' : ''}
          		>	
          			{this.getSubComponent({
          				domkey:domkey[0], 
          				label:item.label,
          				item, 
          				form, 
          			})}
          		</WeaFormItem>
			)
		})

		return <div className="wea-form-item-group" style={wrapperStyle ? wrapperStyle : {padding: '20px 15%'}} >{formItemContainer}</div>
	}
}

//复合表单组件
class CompositeForm extends React.Component {
	constructor(props) {
		super(props);
	}

	render() {
		const {
			conditions
		} = this.props;

		return (<div>
				{
					conditions.map((c, index) => {
						const {
							title
						} = c;

						return  (<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@1e4i34@${index}`} 
								    showGroup
								    title={title} 
								    children={<MagicForm ecId={`${this && this.props && this.props.ecId || ''}_MagicForm@a7s07b@${index}`} {...this.props} conditions={c} />}
								 />)
					})
				}
				</div>)
	}
}

//高级搜索表单
class SearchForm extends React.Component {
	constructor(props) {
		super(props);
	}

	render() {
		const {
			form,
			conditions,
			isFormInit
		} = this.props;

		if (!isFormInit) return null;

		const formItemContainer = [];

		conditions.map(c => {
			c.items.map((item, index) => {
				formItemContainer.push(
					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@3pfo48@${index}`} span={10} offset={1}>
					    <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@cbhmgr@${index}`}
					        label={`${item.label}`}
					        labelCol={{span: 6}}
					        wrapperCol={{span: 18}}
					        style={{paddingTop: 20}}>
					            {<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@rhdlwv@${index}`} fieldConfig={item} form={form} formParams={form.getFormParams()} />}
					    </WeaFormItem>
					</Col>
				)
			})
		})

		return (
			<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@jc4vs8`}>{formItemContainer}</Row>
		)
	}
}

export {
	MagicForm,
	CompositeForm,
	SearchForm,
}