import {
	toJS,
	action,
	reaction,
	computed,
	observable,
} from 'mobx';
import {
	WeaForm,
	WeaTableNew,
} from 'comsMobx';
import {
	WeaDropdown,
	WeaLocaleProvider,
} from 'ecCom';
import {
	Button,
	message,
} from 'antd';
import {
	hrmImportCommon
} from './importCommon';
import {
	fetch,
	confirmation,
	getTopButtons,
	getDropMenuDatas,
	getDialogButtons,
	getMenusCreationConfig,
} from '../util/save-time-util.js';
import * as asyncFetch from '../apis/holidaySetting';
const getLabel = WeaLocaleProvider.getLabel;
const {
	TableStore
} = WeaTableNew;
const {
	ButtonSelect
} = WeaDropdown;


class HrmHolidySettingNew {
	//************权限*************
	@observable pageAccessPermission = {
		hasRight: false,
		loading: true,
	}

	@action getPermissionInfo = () => {
		fetch({
			asyncFetch,
			name: 'getHasRight',
			logic: (cb) => {
				const {
					hasRight
				} = cb;

				if (hasRight) {
					this.pageAccessPermission.hasRight = true;

					this.attendanceId && this.handleOrgTreeNodeClick({
						id: this.attendanceId
					});
				}
				this.pageAccessPermission.loading = false;
			}
		});
	}

	//*************头部**************
	topProps = {
		showDropIcon: true,
		iconBgcolor: '#217346',
		icon: <i className='icon-coms-hrm' />,
	}

	@observable btnMenu = [];

	@observable buttonSelect = [];

	@computed get toploading () {
		if (this.tab.selectedKey === '0') {
			return this.year.loading;
		} else {
			return this.table.comsWeaTableStore.loading;
		}
	}

	@computed get menusCreationConfig () {
		return getMenusCreationConfig(this.btnMenu);
	}

	@computed get topButtons () {
		const {
			topMenu
		} = this.menusCreationConfig;

		const topButtons = getTopButtons.call(this, {
			datas: topMenu,
			disabled: this.menuState,
		});

		if (this.tab.selectedKey === '1' && this.buttonSelect.length > 0) {
			const {
				selectedRowKeys
			} = this.table.comsWeaTableStore;

			topButtons.push(<ButtonSelect ecId={`${this && this.props && this.props.ecId || ''}_ButtonSelect@jed14w`}
				datas={toJS(this.buttonSelect)}
				btnProps={{ disabled: selectedRowKeys.length === 0 }}
				btnOnClick={key => this.btnOnClick(key)}
				menuOnClick={key => this.menuOnClick(key)}
			/>)
		}

		return topButtons;
	}

	btnOnClick = (key) => {
		if (key === '0') {
			confirmation.showDelConfirm({
				type: 1,
				logic: (type) => this.delHoildaySettingDatas(type),
			})
		} else {
			this.setDialogType('4');
			this.openDialog();
		}
	}

	menuOnClick = (key) => {

	}

	@computed get dropMenuDatas () {
		const {
			rightMenu
		} = this.menusCreationConfig;

		return getDropMenuDatas.call(this, {
			datas: rightMenu,
			disabled: this.menuState,
		});
	}

	@computed get menuState () {
		if (this.tab.selectedKey === '0') {
			const {
				loading
			} = this.year;

			return [loading, loading, loading];

		} else {
			const {
				loading
			} = this.table.comsWeaTableStore;

			return [loading, loading];
		}
	}

	@computed get rightMenuAsyncFetchParams () {
		const params = {
			groupId: this.groupId
		};
		if (this.tab.selectedKey === '1') {
			Object.assign(params, {
				isList: true
			});
		}
		return params;
	}

	@action getRightMenu = () => {
		fetch({
			asyncFetch,
			name: 'getMenus',
			fetchParams: this.rightMenuAsyncFetchParams,
			logic: (cb) => {
				const {
					btnMenu,
					buttonSelect = []
				} = cb;

				this.btnMenu = btnMenu;
				this.buttonSelect = buttonSelect;
			}
		});
	}

	rightMenuDisposer = reaction(() => this.rightMenuAsyncFetchParams, rightMenuAsyncFetchParams => {
		this.getRightMenu();
	})

	new = () => {
		this.setDialogType('0');
		this.openDialog();
	}

	import = () => {
		const params = [getLabel('129833', '导入模板'), getLabel('505581', "节假日导入"), 'holidaySet', true];

		const funcs = ['setTempletName', 'setImportDialogTitle', 'setImportType', 'setImportDialogVisible'];

		funcs.map((func, index) => {
			hrmImportCommon[func](params[index]);
		})
	}

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

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

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

	init = () => {
		this.year.loading = true;

		fetch({
			asyncFetch,
			name: 'initHolidaySet',
			fetchParams: this.countAsyncFetchParams,
			logic: (cb) => {
				const {
					status
				} = cb;

				if (status === '1') {
					message.success(cb.message);
					this.refreshContent();
				} else {
					message.warning(cb.message);
				}

				this.year.loading = false;
			}
		});
	}

	//**************组织树******************
	get treeProps () {
		return ({
			title: getLabel(505582, '考勤组'),
			rightStr: 'KQHolidaySetAdd:Add',
			dataUrl: '/api/hrm/kq/group/getGroupTree',
			handleOrgTreeNodeClick: (params) => this.handleOrgTreeNodeClick(params)
		}
		)
	}

	@observable groupId = '0';

	@observable tree = {
		triggerRefresh: false,
	}

	@action handleOrgTreeNodeClick = (params) => {
		const {
			id
		} = params;

		this.groupId = id;
	}

	@action triggerRefresh = () => {
		this.tree.triggerRefresh = !this.tree.triggerRefresh;
	}

	@computed get hasRightLayout () {
		return this.groupId !== '0' ? true : false;
	}

	//**************无数据图标******************

	get noDataProps () {
		return {
			className: 'icon-coms-blank',
			tip: getLabel('505583', "请先选择左侧考勤组")
		}
	}

	//**************标签页******************
	get tabProps () {
		return {
			datas: [{
				key: '0',
				title: getLabel('490', "日历")
			}, {
				key: '1',
				title: getLabel('491', "清单")
			}]
		}
	}

	@observable tab = {
		selectedKey: '0'
	}

	@action handleTabClick = (key) => {
		this.tab.selectedKey = key;
	}

	tabDisposer = reaction(() => this.tab.selectedKey, selectedKey => {
		if (this.groupId === '0') return;

		this.refreshContent();
	})

	//**************日期选择器******************
	datePickerProps = {
		arrow: true,
		type: 'year',
		onChange: (value) => this.handleDatePickerChange(value)
	}

	@observable datePicker = {
		value: new Date()
	}

	@observable fullYear = '';

	@action handleDatePickerChange = (value) => {
		this.fullYear = value.year ? value.year() : value.getFullYear();
		this.datePicker.value = value;
		this.year.value = value;
	}

	//**************总计******************
	colorIconProps = {
		pixel: 10,
		shape: 'square',
	}

	get helpfulTipProps () {
		return {
			width: 150,
			style: {
				marginLeft: 10
			},
			title: getLabel('390077', "点击图标可以过滤数据！")
		}
	}

	@observable summary = {
		annotations: [],
		iconStates: [1, 1, 1],
	}

	@action handleIconClick = (value, index) => {
		this.summary.iconStates[index] = value;
	}

	@computed get hasHelpfulTip () {
		return (this.summary.annotations.length > 0) ? true : false
	}

	@computed get countAsyncFetchParams () {
		const params = {
			groupId: this.groupId,
			currentYear: this.fullYear ? this.fullYear : new Date().getFullYear(),
		};

		return params;
	}

	@computed get hoildayType () {
		let checked = [];

		this.summary.iconStates.map((val, index) => {
			if (val !== 0) checked.push(index + 1);
		});

		return {
			changeType: checked.toString()
		}
	}

	@action getHolidayCount = () => {
		fetch({
			asyncFetch,
			name: 'getHolidayCount',
			fetchParams: this.countAsyncFetchParams,
			logic: (cb) => {
				const {
					type,
				} = cb;

				this.summary.annotations = type;
			}
		});
	}

	countDisposer = reaction(() => this.countAsyncFetchParams, countAsyncFetchParams => {
		const {
			groupId
		} = countAsyncFetchParams;

		if (groupId !== '0' && this.tab.selectedKey === '0') {
			this.getHolidayCount();
		}
	});

	//**************搜索框******************
	inputSearchProps = {
		style: {
			float: 'right',
			margin: 10
		},
		onSearch: (val) => this.handleInputSearch(val)
	}

	@observable inputSearch = {
		value: '',
	}

	@action handleInputSearch = (value) => {
		this.inputSearch.value = value;
	}

	inputSearchDisposer = reaction(() => this.tab.selectedKey, selectedKey => {
		if (selectedKey === '0') {
			this.inputSearch.value = '';
		}
	})

	//**************年视图******************
	yearProps = {
		onDateSelect: (date) => this.handleDateSelect(date)
	}

	@observable calendar = [];

	@observable _year = '';

	@observable month = '';

	@observable day = '';

	@observable year = {
		loading: false,
		value: new Date(),
		date: new Date(),
	}

	@action handleDateSelect = (date) => {
		this._year = date.getYear();
		this.month = date.getMonth() + 1;
		this.day = date.getDayOfMonth();

		if (this.isHoliday) {
			this.setDialogType('2');
		} else {
			this.setDialogType('1');
		}

		this.openDialog();
	}

	@computed get isHoliday () {
		if (this.month && this.day) {
			const {
				changeType,
			} = this.calendar[this.month - 1][this.day - 1];

			return changeType ? true : false;
		} else {
			return false
		}
	}

	@computed get dateSelectId () {
		const {
			changeType,
			id,
		} = this.calendar[this.month - 1][this.day - 1];

		if (changeType) return id;
	}

	@computed get formatDate () {
		let month, day;
		if (this.month < 10) {
			month = `0${this.month}`;
		} else {
			month = this.month;
		}
		if (this.day < 10) {
			day = `0${this.day}`;
		} else {
			day = this.day;
		}
		return `${this._year}-${month}-${day}`;
	}

	@computed get isyearloaded () {
		return this.calendar.length > 0 ? true : false;
	}

	@computed get calendarAsyncFetchParams () {
		const params = {
			...this.countAsyncFetchParams,
			...this.hoildayType
		};

		return params;
	}

	@action getHolidaySetCalendar () {
		this.year.loading = true;

		fetch({
			asyncFetch,
			name: 'getHolidaySetCalendar',
			fetchParams: this.calendarAsyncFetchParams,
			logic: (cb) => {
				const {
					data,
				} = cb;

				this.calendar = data;
				this.year.loading = false;
				this.year.date = new Date();
			}
		});
	}

	yearDisposer = reaction(() => this.calendarAsyncFetchParams, calendarAsyncFetchParams => {
		const {
			groupId
		} = calendarAsyncFetchParams;

		if (groupId !== '0' && this.tab.selectedKey === '0') {
			this.getHolidaySetCalendar();
		}
	});

	//***************列表*****************
	tableProps = {
		hasOrder: true,
		needScroll: true,
		onOperatesClick: (record, rowIndex, operate) => this.handleOperatesClick(record, rowIndex, operate)
	}

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

	@action handleOperatesClick = (record, rowIndex, operate) => {
		const {
			randomFieldId
		} = record, {
			index
		} = operate;

		this.setOperatedRowId(randomFieldId);

		if (index === '0') {
			this.setDialogType('2');
			this.openDialog();
		}

		if (index === '1') {
			confirmation.showDelConfirm({
				type: 0,
				logic: (type) => this.delHoildaySettingDatas(type),
			});
		}

		if (index === '2') {
			this.log(randomFieldId, 'table');
		}

		if (index === '3') {
			this.setDialogType('3');
			this.openDialog();
		}
	}

	@computed get tableAsyncFetchParams () {
		const params = {
			...this.countAsyncFetchParams,
			holidayDesc: this.inputSearch.value,
		};

		return params
	}

	@action getSearchList = () => {
		fetch({
			asyncFetch,
			name: 'getSearchList',
			fetchParams: this.tableAsyncFetchParams,
			logic: (cb) => {
				const {
					sessionkey
				} = cb;

				this.table.comsWeaTableStore.getDatas(sessionkey, 1)
			}
		});
	}

	getDelFetchParams = (type) => {
		let params;
		if (type === 0) {
			params = {
				ids: (this.tab.selectedKey === '0') ? this.dateSelectId : this.operatedRowId
			};
		} else {
			params = {
				ids: this.table.comsWeaTableStore.selectedRowKeys.toString()
			}
		}

		return params;
	}

	delHoildaySettingDatas = (type) => {
		fetch({
			asyncFetch,
			name: 'deleteHolidaySet',
			fetchParams: this.getDelFetchParams(type),
			logic: (cb) => {
				const {
					sign
				} = cb;

				if (sign === '1') {
					message.success(cb.message);
					this.dialog.visible && this.closeDialog();
					this.refreshContent();
				} else {
					message.warning(cb.message);
				}
			}
		});
	}

	tableDisposer = reaction(() => this.tableAsyncFetchParams, tableAsyncFetchParams => {
		const {
			groupId
		} = tableAsyncFetchParams;

		if (groupId !== '0' && this.tab.selectedKey === '1') {
			this.getSearchList();
		}
	});

	setOperatedRowId = (id) => {
		this.operatedRowId = id;
	}

	//**************弹框****************
	dialogProps = {
		icon: 'icon-coms-hrm',
		iconBgcolor: '#217346',
		hasScroll: true,
		style: {
			width: 600,
			height: 340
		},
		onCancel: () => this.closeDialog()
	}

	@observable dialogType = '';

	@observable dialog = {
		visible: false,
	}

	@action openDialog = () => {
		this.dialog.visible = true;
	}

	@action closeDialog = () => {
		this.dialog.visible = false;
	}

	@action setDialogType = (type) => {
		this.dialogType = type;
	}

	@computed get dialogTitle () {
		let title;

		if (['0', '1'].includes(this.dialogType)) {
			title = getLabel('385333', "新建工作日期调整");
		}
		if (this.dialogType === '2') {
			title = getLabel('385334', "编辑工作日期调整")
		}
		if (['3', '4'].includes(this.dialogType)) {
			title = getLabel('505585', "同步考勤组");
		}

		return title;
	}

	@computed get dialogButtons () {
		const {
			loading
		} = this.formElements;

		const datas = [{
			name: getLabel('505564', '保存'),
			disabled: loading,
			onBtnClick: this.saveFormInfo
		}];

		if (this.tab.selectedKey === '0' && this.dialogType === '2') {
			datas.push({
				name: getLabel('131966', '删除'),
				disabled: loading,
				onBtnClick: () => confirmation.showDelConfirm({
					type: 0,
					logic: (type) => this.delHoildaySettingDatas(type),
				})
			})
		}

		const buttons = getDialogButtons({
			datas
		});

		return buttons;
	}

	//**************表单****************
	formConfig = {
		dynamicFields: [{
			passiveKey: 'relatedDay', //对应工作日
			activeKey: 'changeType', //类型
			showValue: '2'
		}, {
			passiveKey: 'syncGroupIds', //考勤组
			activeKey: 'isSync', //类型
			showValue: '1'
		}]
	}

	@observable formElements = {
		conditions: [],
		form: new WeaForm(),
		loading: false,
		date: new Date(),
	}

	@computed get formAsyncFetchName () {
		let name;
		if (['3', '4'].includes(this.dialogType)) {
			name = 'getSyncForm';
		} else {
			name = 'getHolidaySetForm';
		}

		return name;
	}

	@computed get formAsyncFetchParams () {
		let params;
		if (['0', '1'].includes(this.dialogType)) {
			params = {
				groupId: this.groupId,
				holidayDate: (this.dialogType === '1') ? this.formatDate : '',
			}
		}
		if (this.dialogType === '2') {
			params = {
				groupId: this.groupId,
				id: (this.tab.selectedKey === '0') ? this.dateSelectId : this.operatedRowId,
			}
		}

		return params;
	}

	@action getFormInfo = () => {
		this.formElements.loading = true;

		fetch({
			asyncFetch,
			name: this.formAsyncFetchName,
			fetchParams: this.formAsyncFetchParams,
			logic: (cb) => {
				const {
					condition
				} = cb;

				this.formElements.loading = false;
				this.formElements.conditions = condition
				this.formElements.form.initFormFields(condition)
			}
		});
	}

	@computed get saveAsyncFetchName () {
		let name;
		if (['0', '1'].includes(this.dialogType)) {
			name = 'addHolidaySet';
		}
		if (this.dialogType === '2') {
			name = 'editHolidaySet';
		}
		if (['3', '4'].includes(this.dialogType)) {
			name = 'syncHolidaySet';
		}

		return name;

	}

	@computed get saveAsyncFetchParams () {
		const params = {
			...this.formElements.form.getFormParams()
		}
		if (this.dialogType === '2') {
			Object.assign(params, {
				id: (this.tab.selectedKey === '0') ? this.dateSelectId : this.operatedRowId
			});
		}
		if (['3', '4'].includes(this.dialogType)) {
			const {
				selectedRowKeys
			} = this.table.comsWeaTableStore;

			Object.assign(params, {
				ids: (this.dialogType === '3') ? this.operatedRowId : selectedRowKeys.toString()
			});
		}

		return params;
	}

	saveFormInfo = () => {
		const {
			form
		} = this.formElements;

		this.ignoreFields();

		form.validateForm().then(f => {
			if (f.isValid) {
				this.formElements.loading = true;

				fetch({
					asyncFetch,
					name: this.saveAsyncFetchName,
					fetchParams: this.saveAsyncFetchParams,
					logic: (cb) => {
						const {
							sign
						} = cb;

						if (sign === '1') {
							message.success(cb.message);
							this.closeDialog();
							this.refreshContent();
						} else {
							message.warning(cb.message);
						}

						this.formElements.loading = false;
					}
				});
			} else {
				f.showErrors();
				this.formElements.date = new Date();
			}
		});
	}

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

		const {
			form
		} = this.formElements, {
			isSync,
		} = form.getFormParams();

		(!['3', '4'].includes(this.dialogType) && isSync !== '1') && ['syncGroupIds'].map(key => {
			window.e9HideFormFieldKeys.push(key);
		});
	}

	refreshContent = () => {
		if (this.tab.selectedKey === '0') {
			['getHolidayCount', 'getHolidaySetCalendar'].map(func => {
				this[func]();
			});
		} else {
			this.getSearchList();
		}
	}

	@action resetFormInfo = () => {
		this.formElements.conditions = [];
		this.formElements.form = new WeaForm();
	}

	@computed get hasDialogContentLoaded () {
		const {
			form
		} = this.formElements;

		return form.isFormInit ? true : false
	}

	formDisposer = reaction(() => this.dialog.visible, visible => {
		if (visible) {
			this.getFormInfo();
		} else {
			this.resetFormInfo();
		}
	});

	//**************其他****************
	setAttendanceId = (params) => {
		const {
			id
		} = params;

		this.attendanceId = id;
	}

	refresh = () => {
		this.reset();
		this.triggerRefresh();
	}

	reset = () => {
		this.groupId = '0';
		this.tab.selectedKey = '0';
		this.datePicker.value = new Date();
		this.fullYear = '';
		this.summary.iconStates = [1, 1, 1];
	}

}

const hrmHolidySettingNew = new HrmHolidySettingNew()

export {
	hrmHolidySettingNew
}