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/holidayType';
const getLabel = WeaLocaleProvider.getLabel;
const {
	TableStore
} = WeaTableNew;
const confirm = Modal.confirm;

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

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

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

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

	@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@p0uo38@${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, loading, selectedRowKeys.length === 0];
	}

	new = () => {
		this.dialog.title = getLabel(505573, '新建假期类型');
		this.dialogType = '1';
		this.dialog.visible = true;
		this.getLeaveTypesForm();
	}

	save = () => {
		api.saveDisableLeaveRules({
			typeIds: this.checkedIds.toString()
		}).then(data => {
			const {
				sign
			} = data;

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

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

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

		let params;
		if (id !== undefined) {
			params = {
				typeId: id,
			}
		}
		api.getLeaveTypesForm(params).then(data => {
			const {
				condition,
				minimumUnit,
				isEnable,
			} = data;

			this.dialog.form = new WeaForm();
			this.dialog.conditions = condition;
			this.dialog.form.initFormFields(condition);
			this.dialog.loading = false;
			this.dialog.minimumUnit = minimumUnit;
			this.isEnable = isEnable;

			if (id !== undefined) {
				this.dialog.title = isEnable ? getLabel(505574, '编辑假期类型') : getLabel(505575, '查看假期类型');
			}

			this.lastSelectedHolidayUnit = this.dialog.form.getFormParams().minimumUnit;
		}, error => {})
	}

	@computed get dynamicTips() {
		return {
			minimumUnit: this.dialog.minimumUnit,
		};
	}

	@observable renderBlacklist = ['proportion'];

	lastSelectedHolidayUnit = ''; //上一次选中的请假单位

	@action onHolidayUnitChange = (value) => {
		const last = this.lastSelectedHolidayUnit;

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

		if (value === '3' || (['1', '2', '4'].includes(value) && last === '3')) {
			if (index > -1) this.renderBlacklist.splice(index, 1);
		} else {
			if (index === -1) {
				this.renderBlacklist.push('proportion');
				this.dialog.form.updateFields({
					proportion: {
						value: 8
					}
				});
			}
		}

		this.lastSelectedHolidayUnit = value;
	}

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

		window.e9HideFormFieldKeys = [];

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

		const params = form.getFormParams();

		let func;
		if (this.dialogType === '2') {
			Object.assign(params, {
				typeId: this.typeId
			});
			func = 'editLeaveTypes';
		} else {
			func = 'addLeaveTypes';
		}

		form.validateForm().then(f => {
			if (f.isValid) {
				api[func](params).then(data => {
					const {
						sign
					} = data;

					if (sign === '1') {
						message.success(data.message);
						this.closeDialog();
						this.getSearchList();
					} else {
						message.warning(data.message);
					}
				}, error => {})
			} else {
				f.showErrors();
				this.dialog.date = new Date();
			}
		})
	}

	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.deleteLeaveTypes({
					typeIds: selectedRowKeys.toString()
				}).then(data => {
					const {
						sign
					} = data;

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

	custom = () => {
		const {
			comsWeaTableStore
		} = this.table;

		comsWeaTableStore.setColSetVisible(true);
		comsWeaTableStore.tableColSet(true);
	}

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

	dialogType = '1';

	typeId = '';

	checkedIds = [];

	@observable isEnable = true; //当前假期类型是否启用

	@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(505574, '编辑假期类型');
		this.dialogType = '2';
		this.typeId = id;
		this.dialog.visible = true;
		this.getLeaveTypesForm(id);
	}

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

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

	collectChecked = (id) => {
		if (!this.checkedIds.includes(id)) {
			this.checkedIds.push(id);
		}
	}

	onCheckBoxChange = (val, id) => {
		if (val === '1') {
			if (!this.checkedIds.includes(id)) {
				this.checkedIds.push(id);
			}
		} else {
			if (this.checkedIds.includes(id)) {
				const index = this.checkedIds.findIndex(ckId => ckId === id);
				this.checkedIds.splice(index, 1);
			}
		}
	}

	DIALOG = {
		hasScroll: true,
		icon: 'icon-coms-hrm',
		iconBgcolor: '#217346',
		onCancel: () => this.closeDialog(),
		style: {
			width: 700,
			height: 350
		},
		moreBtn: {
			datas: []
		},
	}

	@computed get dialogButtons() {
		const btns = [];
		if (this.isEnable) {
			btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@jkr255`} type='primary' onClick={() => this.saveDialogForm()}>{getLabel(505564, '保存')}</Button>);
		}
		return btns;
	}

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

	@action closeDialog = () => {
		this.dialog.visible = false;
		this.renderBlacklist = ['proportion'];
	}

	FORMCONFIG = {
		dynamicFields: [{
			passiveKey: 'scopeValue', //分部
			activeKey: 'scopeType', //流程可见范围
			showValue: '1'
		}, {
			passiveKey: 'hoursToDay', //日折算时长
			activeKey: 'computingMode', //计算请假时长方式
			showValue: '2',
		}, {
			passiveKey: 'hoursToDay', //日折算时长
			activeKey: 'minimumUnit', //最小请假单位
			showValue: '1,2,3,4'
		}],
		staticTips: {
			hoursToDay: (
				<p style={{display:'inline-block', marginLeft: 15,paddingTop: 5}}>
					<span>{`${getLabel('391',"小时")}=1${getLabel('505553',"天")}`}</span>
					<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@ey8z8j`}
						style={{marginLeft: 10}}
         				title={getLabel('505576',"当计算请假时长方式选择按自然日计算请假时长时，需设置日折算时长。")}
        			/>
				</p>
			),
			proportion: (
				<p style={{display:'inline-block',marginLeft: 15}}>
					<span>{`${getLabel('391',"小时")}=1${getLabel('505553',"天")}`}</span>
					<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@hgubpw`}
						style={{marginLeft: 10}}
         				title={getLabel('505577',"编辑假期时当请假单位在天与小时之间变更时需设置假期余额的换算比例，设置保存后会自动进行历史余额的换算：如原有余额为5天，请假单位变更为小时，设置换算比例为8小时=1天，则保存后余额自动换算为40小时")}
        			/>
				</p>
			)
		},
		classNames: {
			hoursToDay: 'hrm-holiday-rule-form-input',
			proportion: 'hrm-holiday-rule-form-input',
		},
	}

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

	TAB = {
		advanceHeight: 170,
		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@a21ivd@${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().leaveName;
	}

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

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

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

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

	}

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

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


}

export const hrmHolidayType = new HrmHolidayType();