import {
	observable,
	action,
	computed,
	reaction,
} from 'mobx';
import {
	WeaLocaleProvider,
} from 'ecCom';
import {
	WeaForm,
} from 'comsMobx';
import {
	message
} from 'antd';
import {
	fetch,
	getMenusCreationConfig,
	getTopButtons,
	getDropMenuDatas,
	msg,
} from '../util/save-time-util.js';
import {
	checkNeedInit
} from "../components/init/confirmUtil.js";
import * as asyncFetch from '../apis/initSetting';
const getLabel = WeaLocaleProvider.getLabel;

const isEmptyArray = (value) => {
	return value.length === 0
}

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

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

				if (hasRight) {
					this.pageAccessPermission.hasRight = true;
				}
				this.pageAccessPermission.loading = false;
			}
		});
	}

	//*************头部**************
	get topProps () {
		return {
			showDropIcon: true,
			iconBgcolor: '#217346',
			icon: <i className='icon-coms-hrm' />,
			title: getLabel('505591', "一键启用考勤"),
		}
	}

	@observable btnMenu = [];

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

		return 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,
		});

		return topButtons;
	}


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

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

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

		return [loading];
	}


	@action getRightMenu = () => {
		fetch({
			asyncFetch,
			name: 'getRightMenu',
			fetchParams: {
				isInitResult: this.hasInit
			},
			logic: (cb) => {
				const {
					btnMenu,
				} = cb;

				this.btnMenu = btnMenu;
			}
		});
	}

	startInit = () => {
		this.handleInitButtonClick();
	}

	log = () => {
		window.setLogViewProps({ logSmallType: 3075 });
	}

	//*************表单**************
	formConfig = {
		renderBlacklist: ['restTime_start'],
		classNames: {
			'workTime': 'hrm-init-form-datepicker',
			'restTime': 'hrm-init-form-datepicker',
			'workDate': 'hrm-init-form-select',
		},
	}

	@observable errors = {};

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

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

		fetch({
			asyncFetch,
			name: 'getSetupForm',
			logic: (cb) => {
				const {
					condition,
					datas,
				} = cb;

				this.processCondition(condition);

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

				this.slideModalDatas = datas;
			}
		});
	}

	processCondition = (condition) => {
		const ICONS = ['icon-portal-official-o', 'icon-coms02-rest', 'Icon-coms03-rest', 'icon-coms-New-schedule', 'icon-coms-New-schedule'],
			COLORS = ['#2DB7F5', '#2DB7F5', '#CCC'],
			RULE = 'scopeRequired|scopeDirty';

		condition.map(c => {
			c.items.map((item, index) => {
				const key = item.domkey[0];

				if (['workTime', 'restTime', 'excludeRestTime', 'workDate'].includes(key)) {
					item.label = (<span>
						<i className={`${ICONS[index]} hrm-init-form-icon`} style={{ color: COLORS[index] ? COLORS[index] : '' }} />
						<span className='hrm-init-form-label'>
							{item.label}
						</span>
					</span>);
				}

				if (key === 'restTime_start') {
					item.rules = RULE;
				}
			});
		});
	}

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

	@action resetForm = () => {
		this.formElements.form.resetForm();
	}

	@computed get hasInitButton () {
		return this.formElements.form.isFormInit;
	}

	handleInitButtonClick = () => {
		this.validateForm({
			success: (moreValidate) => {
				if (!moreValidate()) return;

				checkNeedInit(() => {
					this.popConfirmVisible = true;
				})
			},
			fail: (f) => {
				const {
					form
				} = this.formElements, {
					workTime,
					restTime
				} = form.getFormParams();

				Object.assign(this.errors, {
					workTime: !workTime ? `"${getLabel('505592', '上班时间')}" ${getLabel('505571', '未填写')}` : ''
				});

				Object.assign(this.errors, {
					restTime: !restTime ? `"${getLabel('505593', '下班时间')}" ${getLabel('505571', '未填写')}` : '',
				});

				f.showErrors();

				this.formElements.date = new Date();

				Object.assign(this.errors, {
					workTime: '',
					restTime: ''
				});
			}
		});
	}

	validateForm = (params) => {
		const {
			form
		} = this.formElements, {
			excludeRestTime,
		} = form.getFormParams();

		const noValidateField = () => {
			window.e9HideFormFieldKeys = [];

			if (excludeRestTime !== '1') {
				window.e9HideFormFieldKeys.push('restTime_start__restTime_end');
			}
		}

		noValidateField();

		const {
			success,
			fail,
		} = params;

		form.validateForm().then(f => {
			if (f.isValid) {
				success(() => this.validateTime());
			} else {
				fail(f);
			}
		});
	}

	validateTime = () => {
		const {
			form
		} = this.formElements, {
			workTime,
			restTime,
			restTime_start,
			restTime_end,
		} = form.getFormParams();

		const compareTime = (start, end) => {
			const startTime = start.split(':');
			const endTime = end.split(':');

			const rulea = (startTime[0] === endTime[0]) && (startTime[1] < endTime[1]);
			const ruleb = startTime[0] < endTime[0];

			if (rulea || ruleb) {
				return true
			}
			return false;
		}

		const msgs = [];
		if (!compareTime(workTime, restTime)) {
			msgs.push(`【${getLabel('505593', '下班时间')}】 ${getLabel('505594', '不能早于')} 【${getLabel('505592', '上班时间')}】`);
		}

		if (restTime_start && !compareTime(restTime_start, restTime_end)) {
			msgs.push(`【${getLabel('505595', '休息结束时间')}】 ${getLabel('505594', '不能早于')} 【${getLabel('505596', '休息开始时间')}】`);
		}

		if (msgs.length > 0) {
			msg.showFailMsg(msgs, 2);
			return false;
		} else {
			return true;
		}

	}
	//*************配置向导**************
	@observable popConfirmVisible = false;

	@observable slideModalVisible = false;

	@observable slideModalDatas = [];

	@observable slideTop = 0;

	confirm = () => {
		this.hasInit = true;

		this.getStepDatas({
			success: () => {
				this.add(() => this.init());
			}
		});
	}

	cancel = () => {
		this.popConfirmVisible = false;
	}

	switchSlideModal = () => {
		this.slideModalVisible = this.slideModalVisible ? false : true;
	}

	close = () => {
		this.slideModalVisible = false;
	}

	setDistanceToPeak = (distance) => {
		this.slideTop = distance;
	}

	//*************步骤******************
	@observable hasInit = false;

	@observable steps = {
		status: 'process',
		items: [],
	}

	@computed get initItemNames () {
		const names = [];

		this.steps.items.map(item => {
			const {
				title
			} = item;
			names.push(title);
		});

		return names;
	}

	@action getStepDatas = (params) => {
		fetch({
			asyncFetch,
			name: 'getSetupSteps',
			logic: (cb) => {
				const {
					items
				} = cb;

				Object.assign(this.steps, {
					items
				});

				const {
					success
				} = params;

				success();
			}
		});
	}

	startInitDisposer = reaction(() => this.hasInit, hasInit => {
		this.getRightMenu();

		if (!hasInit) {
			this.newForm();
			this.steps.items = [];
			this.analysis.results = [];
			this.currentIndex = 0;
		}
	});

	//*************初始化结果**************
	@observable currentIndex = 0;

	@observable analysis = {
		results: []
	}

	@action increase = () => {
		this.currentIndex++;
	}

	@computed get currentName () {
		const items = this.steps.items;

		return `${getLabel('505597', '初始化')}${items[this.currentIndex].title}`
	}

	@computed get initConfig () {
		return {
			name: this.currentName,
			status: '2'
		}
	}

	@action add = (next) => {
		this.analysis.results.push(this.initConfig);
		next();
	}

	@action result = (cb) => {
		const {
			sketch,
			status,
			description,
			url,
		} = cb;

		const replace = (config) => {
			const targetItem = this.analysis.results[this.currentIndex];

			Object.assign(targetItem, config);
		}

		const changeStepStatus = (status) => {
			const targetItem = this.steps.items[this.currentIndex];
			const _status = (status === '0') ? 'error' : 'finish';

			Object.assign(targetItem, {
				status: _status
			});
		}

		const resultConfig = {
			status,
			sketch,
			url,
		};

		description && !isEmptyArray(description) && Object.assign(resultConfig, {
			description
		});

		changeStepStatus(status);

		replace(resultConfig);
	}

	@computed get isInitFinish () {
		return this.currentIndex === this.steps.items.length
	}


	@computed get hasAnalysisResult () {
		return this.analysis.results.length > 0
	}

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

		const fetchParams = {
			...form.getFormParams(),
			index: this.currentIndex,
		}

		fetch({
			asyncFetch,
			name: 'performInitialization',
			fetchParams,
			logic: (cb) => {
				const {
					status
				} = cb;

				this.result(cb);

				this.increase();

				!this.isInitFinish && this.add(() => this.init());
			}
		});
	}

	back = () => {
		this.hasInit = false;
		this.popConfirmVisible = false;
	}

	//*************其他**************
	refresh = (operateForm) => {
		if (this.hasInit) {
			this.back();
		} else {
			operateForm(this);
		}
	}



}

export const hrmInit = new HrmInit();