import {
	inject,
	observer
} from 'mobx-react';
import {
	WeaDialog,
	WeaFormItem,
	WeaLocaleProvider,
} from 'ecCom';
import {
	WeaSwitch
} from 'comsMobx';
import {
	MagicForm,
} from '../../public/sweet-form.js';
import {
	Loading,
} from '../../public/learn.js';
import {
	getDialogButtons,
	confirmation,
} from '../../util/save-time-util.js';
import {
	BalanceConversionRules,
	MixBalanceConversionRulesNew
} from './BalanceConversionRules.js';
const getLabel = WeaLocaleProvider.getLabel;

@inject('commonStore')
@inject('hrmHolidayRule')
@observer
class Dialog extends React.Component {
	constructor(props) {
		super(props);
	}

	handleCancel = () => {
		this.props.commonStore.closeDialog();
	}

	//获取弹框按钮的配置数据
	getBtnConfigDatas = () => {
		const {
			saveFormDatas,
			formElements,
			table,
			dialog
		} = this.props.commonStore, {
			loading,
		} = formElements, {
			index
		} = table, {
			type
		} = dialog;

		const {
			syncVacationRules,
			isEnable,
			confirmBeforeSave,
		} = this.props.hrmHolidayRule;

		const name = ['-1', '0'].includes(index) ? getLabel('505564', '保存') : getLabel('19015', "同步");

		const saveHoliday = (type === 0) ? saveFormDatas : confirmBeforeSave;

		const callBack = ['-1', '0'].includes(index) ? saveHoliday : syncVacationRules;

		const btnDatas = [];

		if (isEnable === '1') {
			btnDatas.push({
				name: name,
				disabled: loading,
				onBtnClick: callBack
			});
		}

		return btnDatas;
	}

	//获取同一行的表单元素
	getTransverseSiblingComponents = (params) => {
		const {
			items,
			form
		} = params;

		//当没有表单元素传入时，直接返回
		if (!items) return

		let extendedDays, expirationDay;

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

			if (domkey[0] === 'extendedDays') {
				//当【允许延长有效期】开关关闭时，什么也不返回
				const extensionEnableValue = form.getFormParams().extensionEnable;

				if (!parseInt(extensionEnableValue)) return;

				//同一行的第二个表单元素
				extendedDays = (
					<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@mmxnti@${index}`}
			    		label={`${getLabel('505558',"超过有效期")}`}
			    		colon={false}
			    		labelCol={{span: 5}}
			    		wrapperCol={{span: 18}}
			    		error={form.getError(item) } 
	 					tipPosition='bottom'
	 					style={{float:'right',width:'86%',marginBottom: 0}}
          			>	
          				<div style={{display: 'inline-block',width: 60,marginRight:13}}>
          					<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@dyqkol@${index}`} fieldConfig={item} form={form} formParams={form.getFormParams()} />
          				</div>
          				{`${getLabel('505553',"天")}${getLabel('505559',"内")}${getLabel('505560',"可继续使用")}`}
          			</WeaFormItem>
				)
			}

			if (domkey[0] === 'expirationDay') {
				expirationDay = (
					<div style={{marginLeft: 10, display:'inline-block'}}>
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@3s19ez@${index}`} fieldConfig={item} form={form} formParams={form.getFormParams()} />
					</div>
				)
			}
		});

		const transverseSiblingComponents = {
			'extensionEnable': extendedDays,
			'expirationMonth': expirationDay
		};

		return transverseSiblingComponents;
	}

	//【余额发放方式】开关联动自定义组件
	getCustomizedComponent = (params) => {
		const {
			form
		} = params, {
			distributionMode
		} = form.getFormParams();

		if (!['2', '3', '6'].includes(distributionMode)) return

		const relationShip = {
			'distributionMode': distributionMode !== '6' ? <BalanceConversionRules ecId={`${this && this.props && this.props.ecId || ''}_BalanceConversionRules@farn38`} /> : <MixBalanceConversionRulesNew ecId={`${this && this.props && this.props.ecId || ''}_MixBalanceConversionRulesNew@b6kx3x`} />
		}

		return relationShip;
	}

	handleFormChange = (cb) => {
		const key = Object.keys(cb)[0];
		const value = cb[key].value;

		const {
			formElements,
		} = this.props.commonStore, {
			form,
		} = formElements;

		//切换【应用范围】，重置【分部】浏览按钮
		(key === 'scopeType' && value === '0') && ['scopeValue'].map(key => {
			form.updateFields({
				[key]: []
			});
		});

		//下拉框【请假单位】选中项不为'1','3'项时，或【计算请假时长方式】不为第'1'项时，重置【日折算时长】
		((key === 'minimumUnit' && !['1', '3'].includes(value)) || (key === 'computingMode') && value !== '1') && ['hoursToDay'].map(key => {
			this.updateFormFields(key, 8);
		});

		//关闭【启用假期余额】开关后，重置【余额发放方式】、【有效期规则】、【允许延长有效期】和【释放规则】
		(key === 'balanceEnable' && value === '0') && ['distributionMode', 'validityRule', 'extensionEnable', 'releaseRule'].map((key, index) => {
			const val = [2, 3].includes(index) ? '0' : '1';
			this.updateFormFields(key, val);
		});

		//下拉框【余额发放方式】选中项不为2、3、6项时，重置定制化组件数据
		(key === 'distributionMode' && !['2', '3', '6'].includes(value)) && ['resetBalanceConversionRules'].map(f => {
			this.props.hrmHolidayRule[f]()
		});

		//下拉框【余额发放方式】选中项不为【每年自动发放固定天数】时，重置【每人发放天数】
		(key === 'distributionMode' && value !== '4') && ['annualAmount'].map(key => {
			this.updateFormFields(key, 1);
		});

		//下拉框【有效期规则】选中项不为【自定义次年失效日期】时，重置【失效日期】
		(key === 'validityRule' && value !== '3') && ['expirationMonth', 'expirationDay'].map(key => {
			this.updateFormFields(key, '1');
		});

		//关闭【允许延长有效期】开关后，重置开关后面的Input框
		(key === 'extensionEnable' && value === '0') && ['extendedDays'].map((key, index) => {
			this.updateFormFields(key, 90);
		});


		if (key === 'minimumUnit') {
			this.props.hrmHolidayRule.handleMinimumUnitChange(value)
		}

	}

	//更新表单元素的值
	updateFormFields = (key, val) => {
		const {
			formElements,
		} = this.props.commonStore, {
			form,
		} = formElements;

		form.updateFields({
			[key]: {
				value: val
			}
		});
	}

	getTransverseSecondComponent = (conditions) => {
		if (conditions.length === 0) return;

		let transverseSecondComponents = [];

		conditions[0].items.map(item => {
			const {
				domkey
			} = item;
			if (['extendedDays', 'expirationDay'].includes(domkey[0])) {
				transverseSecondComponents.push(item);
			}
		});

		return transverseSecondComponents
	}

	getLabels = (form) => {
		const {
			minimumUnit
		} = form.getFormParams();

		const label = (minimumUnit !== '3') ? getLabel('389334', "每人发放天数") : getLabel('388956', "每人发放小时数");

		return {
			'annualAmount': label
		}
	}

	render() {
		const {
			commonStore,
			hrmHolidayRule
		} = this.props, {
			dialog,
			dialogStaticProps,
			formElements,
			table,
		} = commonStore, {
			style,
			formConfig,
			dynamicTips,
			renderBlacklist,
		} = hrmHolidayRule, {
			title,
			visible,
		} = dialog, {
			form,
			date,
			loading,
			conditions
		} = formElements, {
			index
		} = table;

		return (
			<WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@c49fzl`}
          		title={title}
          		visible={visible}
          		style={style}
          		buttons={getDialogButtons({datas:this.getBtnConfigDatas()})}
          		onCancel={this.handleCancel}
	            {...dialogStaticProps}
        	>
        		{
        			loading 
        			? <Loading ecId={`${this && this.props && this.props.ecId || ''}_Loading@8zomd8`} size='sm' />
	        		: ['-1','0'].includes(index)
	        		? <MagicForm ecId={`${this && this.props && this.props.ecId || ''}_MagicForm@gyari6`} 
	        			{...formElements} 
	        			{...formConfig}
	        			renderBlacklist={renderBlacklist}
	        			date={date} 
	        			isFormInit={form.isFormInit}
	        			dynamicTips={dynamicTips}
	        			labels={this.getLabels(form)}
	        			transverseSiblingComponents={this.getTransverseSiblingComponents({
	        				form,
	        				items: this.getTransverseSecondComponent(conditions),
	        			})}
	        			customizations={this.getCustomizedComponent({
	        				form
	        			})}
	        			onFormElementsChange={this.handleFormChange}
	        		 />
	        		:  <MagicForm ecId={`${this && this.props && this.props.ecId || ''}_MagicForm@wcmwb2`} 
	        			{...formElements} 
	        			date={date} 
	        			isFormInit={form.isFormInit}/>

        		}
        	</WeaDialog>
		)
	}
}

export default Dialog