import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaHelpfulTip,
	WeaLocaleProvider,
} from 'ecCom';
import {
	message,
} from 'antd';
import {
	fetch,
	msg,
	validate,
	rule,
	confirmation,
} from '../util/save-time-util.js';
import {
	commonStore
} from './commonStore';
import * as asyncFetch from '../apis/holidayRule';
const getLabel = WeaLocaleProvider.getLabel;
class HrmHolidayRule {
	//页面配置项
	pageConfig = {
		asyncFetch: asyncFetch,
		hasOrgTree: false,
		isOrgTreeInfluenceForm: true,
		tableAsyncName: 'getSearchList',
		permissAsyncName: 'getHasRight',
		menusAsyncName: 'getMenus',
		searchAsyncName: 'getSearchCondition',
		delAsyncName: 'deleteLeaveRules',
		formAsyncName: 'getLeaveRulesForm',
		secondFormAsyncName: 'getSyncSettingForm',
		addAsyncName: 'addLeaveRules',
		editAsyncName: 'editLeaveRules',
		saveSecondFormAsyncName: 'saveSyncSetting',
		editIdPropertyName: 'ruleId',
		delIdPropertyName: 'ruleIds',
		searchLinkageFieldName: 'leaveName',
	};

	@observable renderBlacklist = ['extendedDays', 'expirationDay', 'proportion'];
	//表单配置项
	formConfig = {
		staticTips: {
			hoursToDay: (
				<p style={{display:'inline-block', marginLeft: 15,paddingTop: 5}}>
					<span>{`${getLabel('391',"小时")}=1${getLabel('1925',"天")}`}</span>
					<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@e1q3kq`}
						style={{marginLeft: 10}}
         				title={getLabel('505776',"当计算请假时长方式选择按自然日计算请假时长时，需设置日折算时长。")}
        			/>
				</p>
			),
			proportion: (
				<p style={{display:'inline-block',marginLeft: 15}}>
					<span>{`${getLabel('391',"小时")}=1${getLabel('1925',"天")}`}</span>
					<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@aorusj`}
						style={{marginLeft: 10}}
         				title={getLabel('505777',"编辑假期时当请假单位在天与小时之间变更时需设置假期余额的换算比例，设置保存后会自动进行历史余额的换算：如原有余额为5天，请假单位变更为小时，设置换算比例为8小时=1天，则保存后余额自动换算为40小时")}
        			/>
				</p>
			)
		},
		classNames: {
			hoursToDay: 'hrm-holiday-rule-form-input',
			proportion: 'hrm-holiday-rule-form-input',
			expirationMonth: 'hrm-select-short'
		},
		dynamicFields: [
			//【应用范围】联动配置项
			{
				passiveKey: 'scopeValue', //分部
				activeKey: 'scopeType', //应用范围
				showValue: '1'
			},
			//【最小请假单位】联动配置项
			{
				passiveKey: 'hoursToDay', //日折算时长
				activeKey: 'minimumUnit', //最小请假单位
				showValue: '1,2,3,4'
			},
			//【计算请假时长方式】联动配置项
			{
				passiveKey: 'hoursToDay', //日折算时长
				activeKey: 'computingMode', //计算请假时长方式
				showValue: '2',
			},
			//【启用假期余额】联动配置项
			{
				passiveKey: 'distributionMode', //余额发放方式
				activeKey: 'balanceEnable', //启用假期余额
				showValue: '1'
			}, {
				passiveKey: 'validityRule', //有效期规则
				activeKey: 'balanceEnable', //启用假期余额
				showValue: '1'
			}, {
				passiveKey: 'extensionEnable', //允许延长有效期
				activeKey: 'balanceEnable', //启用假期余额
				showValue: '1'
			}, {
				passiveKey: 'extendedDays', //检查余额
				activeKey: 'balanceEnable', //启用假期余额
				showValue: '1'
			}, {
				passiveKey: 'releaseRule', //释放规则
				activeKey: 'balanceEnable', //启用假期余额
				showValue: '1'
			},
			//【余额发放方式】联动配置项
			{
				passiveKey: 'annualAmount', //每人发放小时数
				activeKey: 'distributionMode', //余额发放方式
				showValue: '4'
			}, {
				passiveKey: 'priority', //优先级别
				activeKey: 'distributionMode', //余额发放方式
				showValue: '6'
			}, {
				passiveKey: 'calcMethod', //计算方式
				activeKey: 'distributionMode', //余额发放方式
				showValue: '2,3,6'
			},
			//【允许延长有效期】联动配置项
			{
				passiveKey: 'extendedDays', //允许延长有效期
				activeKey: 'extensionEnable', //允许延长有效期
				showValue: '1'
			},
			//【有效期规则】联动配置项
			{
				passiveKey: 'expirationMonth', //失效日期
				activeKey: 'validityRule', //有效期规则
				showValue: '3'
			}, {
				passiveKey: 'extensionEnable', //允许延长有效期
				activeKey: 'validityRule', //有效期规则
				showValue: '1,2,3'
			},
			//【释放规则】联动配置项
			{
				passiveKey: 'unrestrictedScope', //不受限范围
				activeKey: 'releaseRule', //释放规则
				showValue: '1,2'
			}
		],
	}
	//*************头部**************
	topTitle = getLabel('505561', "假期规则");

	//新建
	new = () => {
		const params = {
			title: getLabel(505562, '新建假期规则'),
			type: 0, //0：代表新建
		};
		['setSelectedRowIndex', 'openDialog'].map((f, i) => {
			commonStore[f](i === 0 ? '-1' : params);
		});

	}

	save = () => {
		fetch({
			asyncFetch,
			name: 'saveDisableLeaveRules',
			fetchParams: {
				ruleIds: this.enableRowsId.toString()
			},
			logic: (cb) => {
				const {
					sign
				} = cb;

				message[sign === '1' ? 'success' : 'warning'](cb.message);

				this.enableRowsId = [];

				const {
					table
				} = commonStore, {
					tableStore
				} = table;

				const current = tableStore.current;

				commonStore.getSearchList(current);
			}
		});
	}

	//批量删除
	batchDelete = () => {
		confirmation.showDelConfirm({
			type: 1,
			logic: (type) => commonStore.delTableRows(type),
		});
	}

	custom = () => {
		const {
			table
		} = commonStore, {
			tableStore
		} = table;

		['setColSetVisible', 'tableColSet'].map(f => {
			tableStore[f](true);
		});

	}

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

		//决定按钮是否可点击
		return [loading, loading, selectedRowKeys.length === 0];
	}

	//**************弹框****************
	//弹框的样式
	get style() {
		const {
			index
		} = commonStore.table;

		if (['-1', '0'].includes(index)) {
			return {
				width: 700,
				height: 600
			}
		} else {
			return {
				width: 600,
				height: 80
			}
		}
	}

	//获取余额发放规则的参数
	getConversionRulesParams = () => {
		const {
			form
		} = commonStore.formElements, {
			distributionMode
		} = form.getFormParams();

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

		const {
			balanceConversionRules,
			mixBalanceConversionRules
		} = this.conversionRules;

		const dynamicFormParams = {};

		if (distributionMode !== '6') {
			balanceConversionRules.map((balanceConversionRule, index) => {
				['timePoint', 'amount'].map(v => {
					Object.assign(dynamicFormParams, {
						[`${v}_${index}`]: balanceConversionRule[v]
					});
				});
			});
		} else {
			mixBalanceConversionRules.map((mixBalanceConversionRule, index) => {
				['entryTime', 'workYear', 'legalAmount', 'welfareAmount'].map(v => {
					Object.assign(dynamicFormParams, {
						[`${v}_${index}`]: mixBalanceConversionRule[v]
					});
				});
			});
		}

		Object.assign(dynamicFormParams, {
			'detailRuleLen': distributionMode !== '6' ? balanceConversionRules.length : mixBalanceConversionRules.length
		});

		return dynamicFormParams;
	}

	//不检验隐藏的表单元素
	neglectHiddenField = () => {
		//重置e9HideFormFieldKeys容器
		window.e9HideFormFieldKeys = [];

		const {
			form
		} = commonStore.formElements, {
			validityRule,
			scopeType, //应用范围
			scopeValue
		} = form.getFormParams();

		validityRule !== '3' && ['expirationDate'].map(key => {
			window.e9HideFormFieldKeys.push(key);
		});

		scopeType === '0' && ['scopeValue'].map(key => {
			window.e9HideFormFieldKeys.push(key);
		});

		if (this.renderBlacklist.find(key => key === 'proportion')) window.e9HideFormFieldKeys.push('proportion');
	}

	closeDialog = () => {
		this.resetBalanceConversionRules();
		this.resetFields();
	}

	//**************表单***************
	@observable minimumUnit = []; //【最小请假单位】提示信息集合
	@observable distributionMode = []; //【余额发放方式】提示信息集合
	@observable calcMethod = []; //【计算方式】提示信息集合
	@observable isRepeat = true; //【假期名称】是否重复
	@observable isEnable = '0';

	@computed get reverseCalcMethod() {
		const clone = [...this.calcMethod];

		if (clone.length === 0) return clone;

		let _clone = [];

		const first = clone.splice(0, 1);

		clone.forEach((c, i) => {
			_clone.push(c);

			if (i === 1) {
				_clone.push(first);
			}
		});

		return _clone;
	}


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

	@action setAdditionalFormDatas = (datas) => {
		if (!datas.minimumUnit) return

		const {
			form
		} = commonStore.formElements, {
			distributionMode,
			minimumUnit,
			calcMethod,
		} = form.getFormParams();

		['minimumUnit', 'distributionMode', 'calcMethod', 'isEnable'].map(v => {
			this[v] = datas[v];
		});
		['detailRule'].map(v => {
			if (datas[v]) this.conversionRules[distributionMode !== '6' ? 'balanceConversionRules' : 'mixBalanceConversionRules'] = datas[v];
		});

		this.tempValue = minimumUnit;
	}

	@action handleMinimumUnitChange = (value) => {
		const result = this.renderBlacklist.find(key => key === 'proportion');
		if (value === '3' || (['1', '2', '4'].includes(value) && this.tempValue === '3')) {
			if (result) this.renderBlacklist.pop();
		} else {
			if (!result) this.renderBlacklist.push('proportion');
		}
		this.tempValue = value;
	}

	//除了表单参数外，其他的参数
	getAdditionalParams = () => {
		return this.getConversionRulesParams()
	}

	isFieldRepeat = () => {
		this.isVacationNameRepeat();
	}

	//假期名称是否重复
	isVacationNameRepeat = () => {
		const {
			formElements,
			orgTree,
			table,
		} = commonStore, {
			form
		} = formElements, {
			organizationType,
		} = orgTree, {
			id
		} = table;

		const {
			leaveName,
			organizationId,
		} = form.getFormParams();

		fetch({
			asyncFetch: asyncFetch,
			name: 'isNameRepeat',
			fetchParams: {
				leaveName,
				organizationType,
				ruleId: id,
				organizationId: (organizationType === '0') ? '' : organizationId
			},
			logic: (cb) => {
				const {
					isRepeat
				} = cb;

				this.isRepeat = isRepeat;

				if (isRepeat) {
					form.showError('leaveName', `${getLabel('388883',"假期名称")}${getLabel('18082',"重复")}`);
					commonStore.forceUpdateForm();
				} else {
					commonStore.saveFormDatas();
				}
			}
		});
	}

	isMainForm = () => {
		const {
			index
		} = commonStore.table;

		return ['-1', '0'].includes(index) ? true : false;
	}

	confirmBeforeSave = () => {
		const {
			formElements,
			saveFormDatas,
			forceUpdateForm,
		} = commonStore, {
			form
		} = formElements;

		this.neglectHiddenField();

		form.validateForm().then(f => {
			if (f.isValid) {
				confirmation.showSaveConfirm({
					content: getLabel('390326', "假期规则改动后需重新设置假期余额，确认保存？"),
					logic: saveFormDatas,
				})
			} else {
				f.showErrors();
				forceUpdateForm();
			}
		})

	}

	//**************余额发放方式****************
	@observable conversionRules = {
		timeInterval: 1, //时间区间
		balanceConversionRules: [{
			timePoint: 1,
			amount: 0,
		}, {
			timePoint: 1,
			amount: 5,
		}],
		mixBalanceConversionRules: [{
			entryTime: 0,
			workYear: 0,
			legalAmount: 0,
			welfareAmount: 0
		}]
	}

	//改变余额换算规则
	@action changeBalanceConversionRules = (index, value) => {
		this.conversionRules.balanceConversionRules[index].amount = value ? value : 0;
	}

	@action changeEntryTime = (index, value) => {
		this.conversionRules.mixBalanceConversionRules[index].entryTime = value ? value : 0;
	}

	@action changeWorkYear = (index, value) => {
		this.conversionRules.mixBalanceConversionRules[index].workYear = value ? value : 0;
	}

	@action changeLegalAmount = (index, value) => {
		this.conversionRules.mixBalanceConversionRules[index].legalAmount = value ? value : 0;
	}

	@action changeWelfareAmount = (index, value) => {
		this.conversionRules.mixBalanceConversionRules[index].welfareAmount = value ? value : 0;
	}

	@action delBalanceConversionRule = (params) => {
		const type = params ? params.type : '';

		this.conversionRules[type === 'mix' ? 'mixBalanceConversionRules' : 'balanceConversionRules'].pop();
	}

	//设置余额换算规则
	@action setBalanceConversionRule = (balanceConversionRules) => {
		this.conversionRules.balanceConversionRules = balanceConversionRules;
	}

	@action setMixBalanceConversionRule = (mixBalanceConversionRules) => {
		this.conversionRules.mixBalanceConversionRules = mixBalanceConversionRules;
	}

	//设置时间间隔区间
	@action setTimeInterval = (value) => {
		const showValue = value ? value : 1;

		this.conversionRules.timeInterval = showValue;
	}

	//添加余额换算规则
	@action addBalanceConversionRule = (params) => {
		const type = params ? params.type : '';

		if (type === 'mix') {
			const {
				mixBalanceConversionRules,
			} = this.conversionRules;

			const config = {
				fields: [], //需要校验的域
				intervals: {
					'entryTime': 1,
					'workYear': 1,
					'legalAmount': 1,
					'welfareAmount': 1
				}, //时间间隔
				datas: mixBalanceConversionRules,
			}

			const result = rule.add(config);

			this.conversionRules.mixBalanceConversionRules = result
		} else {
			const {
				balanceConversionRules,
				timeInterval,
			} = this.conversionRules;

			const config = {
				fields: ['amount'],
				intervals: {
					'timePoint': timeInterval
				},
				datas: balanceConversionRules,
				msgs: [getLabel('505566', "年假")],
			}

			const result = rule.add(config);

			this.conversionRules.balanceConversionRules = result
		}
	}

	@action resetBalanceConversionRules = () => {
		//初始化换算条件
		this.setBalanceConversionRule([{
			timePoint: 1,
			amount: 0,
		}, {
			timePoint: 1,
			amount: 5,
		}]);

		this.setMixBalanceConversionRule([{
			entryTime: 0,
			workYear: 0,
			legalAmount: 0,
			welfareAmount: 0
		}]);
		//重置时间间隔
		['timeInterval'].map(interval => {
			this.conversionRules[interval] = 1;
		});
	}

	@action resetFields = () => {
		this.isRepeat = true;

		if (!this.renderBlacklist.find(key => key === 'proportion')) this.renderBlacklist.push('proportion');

		commonStore.setSelectedRowId('');
	}

	//**************列表****************
	enableRowsId = [];

	@action handleCkChange = (val, id) => {
		if (val === '1') {
			this.enableRowsId.push(id)
		} else {
			const targetIndex = this.enableRowsId.findIndex(_id => _id === id);
			if (targetIndex > -1) this.enableRowsId.splice(targetIndex, 1);
		}
	}

	@action collectCheckedId = (id) => {
		const result = this.enableRowsId.find(_id => _id === id);
		if (!result) this.enableRowsId.push(id);
	}

	@action refreshPage = () => {}

}

const hrmHolidayRule = new HrmHolidayRule();

export {
	hrmHolidayRule
}