import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaHelpfulTip,
	WeaLocaleProvider,
} from 'ecCom';
import {
	WeaForm
} from 'comsMobx';
import {
	message,
	Button
} from 'antd';
import {
	fetch,
} from '../util/save-time-util.js';
import {
	commonStore
} from './commonStore';
import * as asyncFetch from '../apis/travelRule';
import * as timeSelectionApi from '../apis/timeSelection.js';
const getLabel = WeaLocaleProvider.getLabel;

class HrmTravelRule {
	//页面配置项
	pageConfig = {
		asyncFetch: asyncFetch,
		hasOrgTree: false,
		hasAdvancedSearch: false,
		hasTable: false,
		permissAsyncName: 'getHasRight',
		menusAsyncName: 'getMenus',
		formAsyncName: 'getTravelRulesForm',
	};

	hourToDayRuleTip = (tip) => (
		<span style={{ marginLeft: 15 }}>
			{`${getLabel('391', "小时")}=1${getLabel('505553', "天")}`}
			<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@dast8b`}
				style={{ marginLeft: 10 }}
				title={tip}
			/>
		</span>
	)

	//表单配置项
	formConfig = {
		classNames: {
			hoursToDay: 'hrm-travel-rule-form-input',
			exit_hoursToDay: 'hrm-travel-rule-form-input',
			proportion: 'hrm-travel-rule-form-input',
			exit_proportion: 'hrm-travel-rule-form-input',
			travel_timeselection: 'hrm-travel-timeselection',
			exit_timeselection: 'hrm-exit-timeselection',
		},
		dynamicFields: [{
			passiveKey: 'hoursToDay',
			activeKey: 'minimumUnit',
			showValue: '1,2,3,4'
		}, {
			passiveKey: 'hoursToDay',
			activeKey: 'computingMode',
			showValue: '2',
		}, {
			passiveKey: 'exit_hoursToDay',
			activeKey: 'exit_minimumUnit',
			showValue: '1,2,3,4'
		}, {
			passiveKey: 'exit_hoursToDay',
			activeKey: 'exit_computingMode',
			showValue: '2',
		},
		{//时间选择方式
			passiveKey: 'travel_timeselection', //时间选择方式
			activeKey: 'minimumUnit',
			showValue: '2',
		},
		{//时间选择方式
			passiveKey: 'exit_timeselection', //时间选择方式
			activeKey: 'exit_minimumUnit',
			showValue: '2',
		}]
	}

	//*************头部**************

	get topTitle () { return { title: getLabel('505626', "出差公出规则") }; }

	//获取交互元素（按钮元素和下拉菜单元素）的状态
	getMenusState = () => {
		const {
			loading
		} = commonStore.formElements;

		//决定按钮是否可点击
		return [loading];
	}

	log = () => {
		window.setLogViewProps({
			logSmallType: '3062',
		});
	}

	save = () => {
		const {
			formElements,
		} = commonStore, {
			form
		} = formElements;

		this.neglectHiddenField();

		form.validateForm().then(f => {
			if (f.isValid) {
				fetch({
					asyncFetch,
					name: 'saveTravelRules',
					fetchParams: {
						...form.getFormParams()
					},
					logic: (cb) => {
						const {
							sign
						} = cb

						message[sign === '1' ? 'success' : 'warning'](cb.message);
					}
				});
			} else {
				f.showErrors();
				commonStore.forceUpdateForm();
			}
		})

	}

	//**************表单***************
	@observable minimumUnit = [];
	@observable exit_minimumUnit = [];
	@observable hoursToDay_Tips = '';
	@observable exit_hoursToDay_Tips = '';
	@observable proportion_Tips = '';
	@observable exit_proportion_Tips = '';

	@observable renderBlacklist = ['proportion', 'exit_proportion'];

	//获取表单元素提示信息
	@computed get dynamicTips () {
		return {
			minimumUnit: this.minimumUnit,
			exit_minimumUnit: this.exit_minimumUnit,
		};
	}

	@computed get travelTimeSelectionTip () {
		const {
			form
		} = commonStore.formElements, {
			travel_timeselection
		} = form.getFormParams();
		if (travel_timeselection == 1)
			return <span className="name-def" onClick={() => this.getDefForm(1)}>{getLabel('513303', '选项名称定义')}</span>;
		else
			return <span><WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@8vm09c`} style={{ marginLeft: 10 }} title={getLabel('514037', '前端选择具体起止时间时，时长不满半天的算半天，满半天不满一天的，算一天')} /></span>;
	}

	@computed get exitTimeSelectionTip () {
		const {
			form
		} = commonStore.formElements, {
			exit_timeselection
		} = form.getFormParams();
		if (exit_timeselection == 1)
			return <span className="name-def" onClick={() => this.getDefForm(2)}>{getLabel('513303', '选项名称定义')}</span>;
		else
			return <span><WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@p2yv9d`} style={{ marginLeft: 10 }} title={getLabel('514037', '前端选择具体起止时间时，时长不满半天的算半天，满半天不满一天的，算一天')} /></span>;
	}

	@computed get staticTips () {
		return {
			hoursToDay: this.hourToDayRuleTip(this.hoursToDay_Tips),
			exit_hoursToDay: this.hourToDayRuleTip(this.exit_hoursToDay_Tips),
			proportion: this.hourToDayRuleTip(this.proportion_Tips),
			exit_proportion: this.hourToDayRuleTip(this.exit_proportion_Tips),
			travel_timeselection: this.travelTimeSelectionTip,
			exit_timeselection: this.exitTimeSelectionTip
		}
	}

	@action setAdditionalFormDatas = (datas) => {
		const {
			form
		} = commonStore.formElements, {
			minimumUnit,
			exit_minimumUnit
		} = form.getFormParams();

		['minimumUnit', 'exit_minimumUnit', 'hoursToDay_Tips', 'exit_hoursToDay_Tips', 'proportion_Tips', 'exit_proportion_Tips'].map(v => {
			if (datas[v]) this[v] = datas[v];
		});

		this.minimumUnitTemp = minimumUnit;
		this.exit_minimumUnitTemp = exit_minimumUnit;
	}

	handleMinimumUnithange = (key, value) => {
		this.showOff(key, value);
	}

	showOff = (_key, value) => {
		const tempValue = (_key === 'minimumUnit') ? this.minimumUnitTemp : this.exit_minimumUnitTemp;

		const linkedKey = (_key === 'minimumUnit') ? 'proportion' : 'exit_proportion';

		const index = this.renderBlacklist.findIndex(key => key === linkedKey);

		if (value === '3' || (['1', '2', '4'].includes(value) && tempValue === '3')) {
			if (index > -1) this.renderBlacklist.splice(index, 1);
		} else {
			if (index === -1) this.renderBlacklist.push(linkedKey);
		}

		this[(_key === 'minimumUnit') ? 'minimumUnitTemp' : 'exit_minimumUnitTemp'] = value;

	}

	neglectHiddenField = () => {
		window.e9HideFormFieldKeys = [];

		this.renderBlacklist.map(key => {
			window.e9HideFormFieldKeys.push(key);
		})
	}

	isMainForm = () => {
		return true
	}

	refreshPage = () => {
		const {
			formElements,
		} = commonStore, {
			form
		} = formElements;

		this.renderBlacklist = ['proportion', 'exit_proportion'];

		window.e9ChangedFormFieldKey = 'resetFormNoNeedWarning';

		commonStore.getFormMaterial();

	}

	/** 选项名称定义 */
	@observable timeSelectionDialogVisible = false;
	@computed get timeSelectionDialog () {
		return {
			key: new Date().getTime(),
			...ecCom.WeaTools.getIconBGC('hrm'),
			style: {
				height: 200
			},
			title: getLabel('513303', '选项名称定义'),
			hasScroll: true,
			visible: this.timeSelectionDialogVisible,
			buttons: [
				<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@peahw2`} type="primary" onClick={() => this.saveDefForm()}>{getLabel(30986, '保存')}</Button>,
			],
			moreBtn: {
				datas: [
					{
						key: "1",
						icon: <i className="icon-coms-Preservation" />,
						content: getLabel(30986, '保存'),
						onClick: () => this.saveDefForm()
					},
				]
			},
			onCancel: () => {
				this.timeSelectionDialogVisible = false;
			}
		}
	}

	@action getDefForm = (selectiontype) => {
		this.selectiontype = selectiontype;
		const {
			formElements,
		} = commonStore, {
			form
		} = formElements;
		const { minimumUnit, exit_minimumUnit } = form.getFormParams();
		const params = { selectiontype, minimumUnit: (selectiontype == 1 ? minimumUnit : exit_minimumUnit) };
		timeSelectionApi.getTimeSelectionForm(params).then(data => {
			if (data.status == '1') {
				const { condition: fields } = data;
				this.formTarget = {
					fields,
					form: new WeaForm()
				};
				this.formTarget.form.initFormFields(fields);
				this.timeSelectionDialogVisible = true;
			} else {
				message.error(data.message);
			}
		})
	}

	@action saveDefForm = () => {
		const {
			formElements,
		} = commonStore, {
			form
		} = formElements;
		const { minimumUnit, exit_minimumUnit } = form.getFormParams();
		const params = { selectiontype: this.selectiontype, minimumUnit: (this.selectiontype == 1 ? minimumUnit : exit_minimumUnit) };

		const formData = this.formTarget.form.getFormParams();
		Object.assign(params, { ...formData });

		timeSelectionApi.saveTimeSelectionForm(params).then(data => {
			if (data.status == '1') {
				this.timeSelectionDialogVisible = false;
			} else {
				message.error(data.message);
			}
		})
	}
}

const hrmTravelRule = new HrmTravelRule();

export {
	hrmTravelRule
}