import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaHelpfulTip,
	WeaLocaleProvider,
} from 'ecCom';
import {
	WeaForm,
	WeaTableNew
} from 'comsMobx';
import {
	message,
	Button,
	Modal,
} from 'antd';
import * as api from '../apis/newHolidayRule.js';
const getLabel = WeaLocaleProvider.getLabel;
const {
	TableStore
} = WeaTableNew;
const confirm = Modal.confirm;

class HrmNewHolidayRule {
	@observable permission = {
		hasRight: false,
		loading: true,
	}

	getPermissionInfo = (callback) => {
		api.getHasRight().then(cb => {
			const {
				hasRight
			} = cb;

			this.permission.hasRight = hasRight;
			this.permission.loading = false;
			if (hasRight) {
				callback && callback();
			}
		}).catch(error => {});
	}

	TOP = {
		showDropIcon: true,
		iconBgcolor: '#217346',
		icon: <i className='icon-coms-hrm'/>,
		title: getLabel('505561', "假期规则"),
	}

	@observable top = {
		loading: false,
	}

	@observable tConf = [];
	@observable rConf = [];

	@action getRightMenu = () => {
		api.getRightMenu().then(data => {
			const {
				btnMenu
			} = data;

			const {
				tConf,
				rConf
			} = this.filter(btnMenu);

			this.tConf = tConf;
			this.rConf = rConf;
		}, error => {})
	}

	filter = (datas) => {
		let tConf, rConf;
		tConf = datas.filter(item => {
			var bool = false;
			['isTop', 'isBatch'].forEach(prop => {
				const b = parseInt(item[prop]);
				if (b) {
					bool = true
				}
			});

			return bool
		})

		rConf = datas;

		return {
			tConf,
			rConf
		}
	}

	@computed get topButtons() {
		return this.tConf.map((item, index) => {
			const {
				menuFun,
				menuName
			} = item;

			return (
				<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ruxxsf@${index}`} 
					type="primary" 
					disabled={this.menuStatus[index] } 
					onClick={() => this[menuFun]()}
				>
					{menuName}
				</Button>
			)
		});
	}

	@computed get dropMenuDatas() {
		return this.rConf.map((item, index) => {
			const {
				menuFun,
				menuName,
				menuIcon
			} = item;

			return {
				key: index.toString(),
				disabled: this.menuStatus[index],
				icon: <i className={`${menuIcon}`} />,
				content: menuName,
				onClick: () => this[menuFun]()
			}
		});
	}

	get menuStatus() {
		const {
			comsWeaTableStore
		} = this.table, {
			loading,
			selectedRowKeys
		} = comsWeaTableStore;

		return [loading, selectedRowKeys.length === 0];
	}

	new = () => {
		this.dialog.title = getLabel(505562, '新建假期规则');
		this.dialogType = '1';
		this.dialog.visible = true;
		this.getLeaveRulesForm();
	}

	batchDelete = () => {
		let _this = this;
		confirm({
			title: getLabel('131329', '信息确认'),
			content: getLabel('385625', '确定要删除选择的记录吗？'),
			okText: getLabel('33703', '确定'),
			cancelText: getLabel('32694', '取消'),
			onOk() {
				const {
					comsWeaTableStore
				} = _this.table, {
					selectedRowKeys
				} = comsWeaTableStore;

				api.deleteLeaveRules({
					ruleIds: selectedRowKeys.toString()
				}).then(data => {
					const {
						sign
					} = data;

					if (sign === '1') {
						message.success(data.message);
						_this.getSearchList();
					} else {
						message.warning(data.message);
					}
				});
			},
			onCancel() {
				return false;
			},
		});
	}

	log = (id, source) => {
		const params = {
			logSmallType: '3060',
		};
		if (source === 'table') {
			Object.assign(params, {
				targetId: id,
			});
		}
		window.setLogViewProps(params);
	}

	buttonsAds = [getLabel(82529, '搜索'), getLabel(27088, '重置'), getLabel(32694, '取消')];

	TAB = {
		advanceHeight: 130,
		hasMask: false,
		searchType: ['base', 'advanced'],
		setShowSearchAd: bool => this.setShowSearchAd(bool),
		onSearch: () => this.onSearch(),
		onSearchChange: val => this.onSearchChange(val),
		buttonsAd: this.buttonsAds.map((name, index) => {
			const type = (index === 0) && "primary";
			let callback;
			if (index === 0) {
				callback = () => this.onSearch();
			} else if (index === 1) {
				callback = () => this.tab.form.resetConditionValue();
			} else {
				callback = this.setShowSearchAd
			}
			return <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1i9nwm@${index}`} type={type} onClick={() => callback(index === 2 && false)}>{name}</Button>
		})
	}

	@observable tab = {
		showSearchAd: false,
		form: new WeaForm()
	}

	@computed get searchsBaseValue() {
		const {
			form
		} = this.tab;
		return form.getFormParams().ruleName;
	}

	@action setShowSearchAd = (bool) => {
		this.tab.showSearchAd = bool;
	}

	onSearch = () => {
		this.getSearchList();
		this.setShowSearchAd(false);
	}

	onSearchChange = (val) => {
		const {
			form
		} = this.tab;

		form.updateFields({
			ruleName: {
				value: val
			}
		});

	}

	@action getSearchForm = () => {
		api.getSearchCondition().then(data => {
			const {
				condition
			} = data;

			this.tab.form = new WeaForm();
			this.tab.form.setCondition(condition);
			this.getSearchList();
		}, error => {})
	}

	TABLE = {
		hasOrder: true,
		needScroll: true,
	}

	dialogType = '1';

	ruleId = '';

	@observable table = {
		comsWeaTableStore: new TableStore(),
	}

	@action getSearchList = () => {
		api.getSearchList({
			...this.tab.form.getFormParams()
		}).then(data => {
			const {
				sessionkey
			} = data;
			this.table.comsWeaTableStore = new TableStore();
			this.table.comsWeaTableStore.getDatas(sessionkey, 1);
		}, error => {})
	}

	@action onTableTdClick = (id) => {
		this.dialog.title = getLabel(505563, '编辑假期规则');
		this.dialogType = '2';
		this.ruleId = id;
		this.dialog.visible = true;
		this.getLeaveRulesForm(id);
	}

	del = (id) => {
		let _this = this;
		confirm({
			title: getLabel('131329', '信息确认'),
			content: getLabel('83877', '确定要删除吗？'),
			okText: getLabel('33703', '确定'),
			cancelText: getLabel('32694', '取消'),
			onOk() {
				api.deleteLeaveRules({
					ruleIds: id
				}).then(data => {
					const {
						sign
					} = data;

					if (sign === '1') {
						message.success(data.message);
						_this.getSearchList();
					} else {
						message.warning(data.message);
					}
				});
			},
			onCancel() {
				return false;
			},
		});
	}

	DIALOG = {
		hasScroll: true,
		icon: 'icon-coms-hrm',
		iconBgcolor: '#217346',
		onCancel: () => {
			this.dialog.visible = false;
			this.resetBalanceConversionRules();
		},
		style: {
			width: 700,
			height: 650
		},
		moreBtn: {
			datas: []
		},
	}

	@computed get dialogButtons() {
		if (this.dialog.isEnable === '1') {
			return [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@shz2i0`} type='primary' onClick={() => this.validateDialogForm()}>{getLabel(505564, '保存')}</Button>]
		} else {
			return [];
		}
	}

	@observable dialog = {
		visible: false,
		loading: false,
		conditions: [],
		form: new WeaForm(),
		date: new Date(),
		calcMethod: [],
		distributionMode: [],
		isEnable: '1',
		title: '',
	}

	@action getLeaveRulesForm = (id) => {
		this.dialog.loading = true;

		let params;
		if (id !== undefined) {
			params = {
				ruleId: id,
			}
		}
		api.getLeaveRulesForm(params).then(data => {
			const {
				condition,
				calcMethod,
				distributionMode,
				unitName,
				detailRule,
				isEnable,
			} = data;

			this.dialog.form = new WeaForm();
			this.dialog.conditions = condition;
			this.dialog.form.initFormFields(condition);
			this.dialog.loading = false;
			this.dialog.calcMethod = calcMethod;
			this.dialog.distributionMode = distributionMode;
			this.dialog.isEnable = isEnable;
			if (id !== undefined) {
				this.dialog.title = (isEnable === '1') ? getLabel(505563, '编辑假期规则') : getLabel(505565, '查看假期规则');
			}
			this.conversionRules.unit = unitName;

			if (detailRule && detailRule.length > 0) {
				const isFH = Object.keys(detailRule[0]).length === 4;

				if (isFH) {
					this.setMixBalanceConversionRule(detailRule);
				} else {
					this.setBalanceConversionRule(detailRule);
				}
			}
		}, error => {})
	}

	validateDialogForm = () => {
		const {
			form
		} = this.dialog, {
			scopeType
		} = form.getFormParams();

		window.e9HideFormFieldKeys = [];

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

		form.validateForm().then(f => {
			if (f.isValid) {
				this.saveConfirm();
			} else {
				f.showErrors();
				this.dialog.date = new Date();
			}
		})
	}

	saveConfirm = () => {
		let _this = this;
		confirm({
			title: getLabel('131329', '信息确认'),
			content: getLabel('-1', '保存后会根据规则内容自动调整本年度的员工假期余额，历史年份则需要手动批处理后才会生效。'),
			okText: getLabel('33703', '确定'),
			cancelText: getLabel('32694', '取消'),
			onOk() {
				_this.saveDialogForm()
			},
			onCancel() {
				return false;
			},
		});
	}

	saveDialogForm = () => {
		const {
			form
		} = this.dialog;

		const params = {
			...form.getFormParams(),
			...this.getConversionRulesParams()
		};

		let func;
		if (this.dialogType === '2') {
			Object.assign(params, {
				ruleId: this.ruleId
			});
			func = 'editLeaveRules';
		} else {
			func = 'addLeaveRules';
		}

		api[func](params).then(data => {
			const {
				sign
			} = data;

			if (sign === '1') {
				message.success(data.message);
				this.dialog.visible = false;
				this.getSearchList();
			} else {
				message.warning(data.message);
			}
		}, error => {})
	}

	FORMCONFIG = {
		classNames: {
			expirationMonth: 'hrm-select-short',
			annualAmount: 'hrm-holiday-rule-form-input',
		},
		dynamicFields: [
			//【应用范围】联动配置项
			{
				passiveKey: 'scopeValue', //分部
				activeKey: 'scopeType', //应用范围
				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'
			},
		],
	}

	@computed get staticTips() {
		const {
			unit
		} = this.conversionRules;

		return {
			annualAmount: (
				<p style={{display:'inline-block', marginLeft: 10,paddingTop: 5}}>
					<span>{unit ? unit : getLabel(505553,'天')}</span>
				</p>
			),
		}
	}

	@action getUnitName = (id) => {
		api.getUnitName({
			typeId: id
		}).then(data => {
			const {
				unitName
			} = data;
			this.conversionRules.unit = unitName;
		}, error => {})
	}

	@observable renderBlacklist = ['extendedDays', 'expirationDay'];

	@computed get dynamicTips() {
		return {
			distributionMode: this.dialog.distributionMode,
			calcMethod: this.reverseCalcMethod,
		};
	}

	@computed get reverseCalcMethod() {
		const clone = [...this.dialog.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;
	}

	@observable conversionRules = {
		timeInterval: 1, //时间区间
		balanceConversionRules: [{
			timePoint: 1,
			amount: 0,
		}, {
			timePoint: 1,
			amount: 5,
		}],
		mixBalanceConversionRules: [{
			entryTime: 0,
			workYear: 0,
			legalAmount: 0,
			welfareAmount: 0
		}],
		unit: ''
	}

	@action changeBalanceConversionRules = (index, value) => {
		const val = value ? value : 0;
		this.conversionRules.balanceConversionRules[index].amount = val;
	}

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

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

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

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

	@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 val = value ? value : 1; //为空的情况

		this.conversionRules.timeInterval = val;
	}

	//添加余额换算规则
	@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 = this.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 = this.add(config);

			this.conversionRules.balanceConversionRules = result
		}
	}

	add = (config) => {
		const {
			fields,
			intervals,
			datas,
			msgs
		} = config;

		const last = datas[datas.length - 1];
		const clone = [...datas];

		if (!this.isComplete(fields, datas)) return datas;

		const newData = {};

		Object.keys(last).map((key, index) => {
			if (!fields.includes(key)) {
				Object.assign(newData, {
					[key]: last[key] + intervals[key],
				});
			} else {
				Object.assign(newData, {
					[key]: last[key] + 1,
				});
			}
		});

		clone.push(newData);

		return clone;

	}

	isComplete = (fields, datas) => {
		const unfilledRows = [];

		datas.map((data, index) => {
			fields.some(field => data[field] === undefined) && unfilledRows.push(index + 1);
		});

		(unfilledRows.length > 0) && message.warning(`${getLabel('505567',"第")} ${unfilledRows.toString()} ${getLabel('27592',"行")}${getLabel('505569',"余额发放")}${getLabel('505570',"天数")}${getLabel('505571',"未填写")}`);

		if (unfilledRows.length > 0) return false;

		return true;
	}

	@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;
		});
	}

	//获取余额发放规则的参数
	getConversionRulesParams = () => {
		const {
			form
		} = this.dialog, {
			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;
	}



}

export const hrmNewHolidayRule = new HrmNewHolidayRule();