import * as Api from '../apis/workHour';
import {
	toJS
} from 'mobx';
import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaForm,
	WeaTableNew,
	WeaLogView,
} from 'comsMobx';
import {
	message
} from 'antd';
import {
	i18n
} from '../public/i18n';
const {
	TableStore
} = WeaTableNew;
const {
	LogStore
} = WeaLogView;

export class HrmWorkHour {
	@observable date = '';
	@observable main = {
		authorized: false,
		title: i18n.module.generalWorkingHours(),
		btnMenu: [],
		loading: true,
	}
	@observable searchPanel = {
		form: new WeaForm(),
		conditions: [],
		loading: true,
		isPanelShow: false,
		baseSearchValue: '',
		conditionCount: observable.ref(2),
	}
	@observable mainDialog = {
		title: '',
		visible: false,
		contentType: 'new',
	}
	@observable subDialog = {
		title: '',
		visible: false,
	}
	@observable mainTable = {
		tableStore: new TableStore(),
		selectedRowsKeys: '',
		curScope: '', //从列表中获取当前一般工作时间的应用范围
	}
	@observable formInfo = {
		form: new WeaForm(),
		conditions: [],
		loading: true,
		selectedScopeValue: '3',
		selectedNumberValue: '1',
		selectedTimeValue: '',
	}
	@observable signFormInfo = {
		form: new WeaForm(),
		conditions: [],
		temp: {},
		loading: true,
	}
	@observable tableEdit = {
		columns: [],
		datas: [{
			key: '1',
			day: i18n.label.monday(),
			am: [],
			pm: [],
		}, {
			key: '2',
			day: i18n.label.tuesday(),
			am: [],
			pm: [],
		}, {
			key: '3',
			day: i18n.label.wednesday(),
			am: [],
			pm: [],
		}, {
			key: '4',
			day: i18n.label.thursday(),
			am: [],
			pm: [],
		}, {
			key: '5',
			day: i18n.label.friday(),
			am: [],
			pm: [],
		}, {
			key: '6',
			day: i18n.label.saturday(),
			am: [],
			pm: [],
		}, {
			key: '7',
			day: i18n.label.sunday(),
			am: [],
			pm: [],
		}],
		selectedIndexs: [],
		totalTime: '',
	}
	@observable tabInfo = {
		selectedKey: '0'
	}
	@observable leftTree = {
		nodeId: '',
		nodeType: '0',
		nodeName: i18n.module.generalWorkingHours(),
		triggerRefresh: false
	}
	@observable selectCom = {
		selectedValue: '0',
	}
	@observable log = {
		visible: false,
		logStore: new LogStore(),
		targetId: '',
	}

	@computed get menu() {
		let topMenu = this.main.btnMenu.filter(item => item.isTop == '1' || item.isBatch == '1');
		// let rightMenu = this.main.btnMenu.filter(item => !item.isBatch);
		let rightMenu = this.main.btnMenu.filter(item => item);

		return {
			topMenu,
			rightMenu
		}
	}

	@action
	getAuth = () => {
		Api.getAuth().then(rs => {
			const {
				status,
				hasRight
			} = rs;

			if (status == '1') {
				hasRight && this.grantAuth();
				this.main.loading = false;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	grantAuth = () => {
		this.main.authorized = true;
	}

	@action
	getButtonsMenu = () => {
		Api.getButtonsMenu().then(rs => {
			const {
				status,
				rightMenu,
			} = rs;

			if (status == '1') {
				this.main.btnMenu = rightMenu;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	getTableInfo = () => {
		const {
			tableStore
		} = this.mainTable, {
			nodeType,
			nodeId
		} = this.leftTree, {
			baseSearchValue,
			form
		} = this.searchPanel;

		let params = {
			flowTitle: baseSearchValue,
			...form.getFormParams()
		};
		if (nodeType == '0') {
			params = {
				companyid: nodeId,
				...params
			}
		} else {
			params = {
				subcompanyid1: nodeId,
				...params
			}
		}

		Api.getTableInfo(params).then(rs => {
			const {
				sessionkey,
				status = '1'
			} = rs;

			if (status == '1') {
				sessionkey && tableStore.getDatas(sessionkey, 1);
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	getFormInfo = (type) => {
		let params;
		let func;

		if (type == 'search') { //高级搜索
			func = 'getSearchInfo';
			params = {};
		}
		if (type == 'basic') { //基本信息表单
			func = 'getSettingListSetForm'
			if (this.mainDialog.contentType == 'edit') {
				params = {
					id: this.mainTable.selectedRowsKeys
				}
			}
		}
		if (type == 'sign') { //在线签到考勤设置表单
			func = 'getOnlineKqSystemSetForm'
			if (this.mainDialog.contentType == 'edit') {
				params = {
					id: this.mainTable.selectedRowsKeys
				}
			}
		}

		Api[func](params).then(rs => {
			const {
				status,
				conditions,
				totaltime = '',
			} = rs;

			if (status == '1') {
				if (conditions) {
					if (type == 'search') { //高级搜索
						this.adjustSearchCondtion(conditions);
						this.searchPanel.conditions = conditions;
						this.searchPanel.form.initFormFields(conditions);
						this.stoploading('search');
					}

					if (type == 'basic') { //基本信息
						this.tableEdit.totalTime = totaltime;

						const tb = conditions.splice(1, 1);
						this.deleteRules(conditions);
						this.tableEdit.datas = this.translate(tb[0].table.datas); //获取列表数据

						const {
							contentType
						} = this.mainDialog;

						this.changeRules(conditions);

						if (contentType == 'edit') {
							this.setDefaultValue(conditions);
							this.parseDate(conditions);
						} else {
							this.setDefaultSubDepartment(conditions);
						}

						this.formInfo.conditions = conditions;
						this.formInfo.form.initFormFields(conditions);
						this.stoploading('basic');
					}
					if (type == 'sign') { //考勤应用设置
						const {
							curScope
						} = this.mainTable;

						if (curScope == '3') { //当前是总部，因此考勤应用设置中不需要对象浏览按钮
							const cs = conditions[0].items.splice(-1, 1);
							this.signFormInfo.temp = cs;
						}

						this.adjustKqConditions(conditions);

						this.signFormInfo.conditions = conditions;
						this.signFormInfo.form.initFormFields(conditions);
						this.stoploading('sign');
					}
				}
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	parseDate = (conditions) => {
		conditions.map(c => {
			c.items.map(item => {
				const key = item.domkey[0];
				if (key == 'fromvalidedate') {
					item.startValue = item.value[0];
					item.endValue = item.value[1];
				}
			});
		});
	}

	@action
	changeRules = (conditions) => {
		conditions.map(c => {
			c.items.map(item => {
				const key = item.domkey[0];
				if (key == 'fromvalidedate') {
					item.rules = 'required|array';
				}
			});
		});
	}

	@action
	deleteRules = (conditions) => {
		conditions.map(c => {
			c.items.map(item => {
				const type = item.conditionType;
				if (type == 'SELECT') {
					delete item.rules;
				}
			})
		});
	}

	@action
	setDefaultValue = (conditions) => {
		conditions.map(c => {
			c.items.map(item => {
				const key = item.domkey[0];
				if (key == 'scheduleType') {
					this.exportSelectedValue(item.value, 'scope');
				}
				if (key == 'signType') {
					this.exportSelectedValue(item.value, 'number');
				}
				if (key == 'signStartTime') {
					this.exportSelectedValue(item.value, 'time');
				}
			})
		})
	}

	@action
	setDefaultSubDepartment = (conditions) => {
		const {
			nodeId,
			nodeType,
			nodeName
		} = this.leftTree;

		if (nodeType == '0') {
			this.formInfo.selectedScopeValue = '3'
		} else {
			this.formInfo.selectedScopeValue = '4';
			conditions.map(c => {
				c.items.map(item => {
					const key = item.domkey[0];
					if (key == 'relatedId') {
						item.browserConditionParam.replaceDatas = [{
							id: nodeId,
							name: nodeName
						}]
					}
					if (key == 'scheduleType') {
						item.value = '4';
					}
				})
			})
		}

	}

	@action
	changeSignForm = () => { //重新渲染考勤应用设置表单
		const {
			conditions,
			temp,
		} = this.signFormInfo, {
			selectedScopeValue
		} = this.formInfo;

		const len = toJS(conditions)[0].items.length;

		const cp = toJS(conditions);

		if (selectedScopeValue == '3' && len > 4) { //总部且包含对象浏览按钮
			const cs = cp[0].items.splice(-1, 1);
			this.signFormInfo.temp = cs;
		}
		if (selectedScopeValue == '4' && len < 5) { //分部且不包含对象浏览按钮
			cp[0].items.push(toJS(temp)[0]);
		}

		this.signFormInfo.form = new WeaForm();
		this.signFormInfo.conditions = cp;
		this.signFormInfo.form.initFormFields(cp);
	}

	@action
	adjustKqConditions = (conditions) => {
		conditions.map(c => {
			c.items.map(item => {
				const key = item.domkey[0];
				if (key == 'needSign') {
					item.helpfulTip = i18n.message.openThenShowSignInSignOut();
				}
				if (key == 'signIpScope') {
					item.rules = 'required|string';
				}
				if (key == 'signTimeScope_start') {
					const [
						startValue,
						endValue
					] = item.value;

					item.startValue = startValue;
					item.endValue = endValue;
				}
			})
		});
	}

	@action
	setCurScope = (curScope) => {
		this.mainTable.curScope = curScope;
	}

	@action
	save = () => {
		const {
			com
		} = this.tableEdit, {
			selectedKey
		} = this.tabInfo;

		if (selectedKey == '0') { //保存基本信息

			this.ignorePartVerify();

			this.formInfo.form.validateForm().then(f => {
				if (f.isValid && this.verifyTableEdit()) {

					if (!this.deepValidate(f)) return

					this.recoverloading('basic');
					let params = {
						...this.formInfo.form.getFormParams(),
						...this.jsonTranslate(com.props.datas)
					}

					const {
						selectedScopeValue,
						selectedNumberValue
					} = this.formInfo;

					if (selectedScopeValue == '3') {
						params = {
							...params,
							relatedId: '',
						}
					}

					if (selectedNumberValue == '1') {
						params = {
							...params,
							signStartTime: '',
						}
					}

					if (this.mainDialog.contentType == 'edit') {
						params = {
							...params,
							id: this.mainTable.selectedRowsKeys
						}
					}

					Api.saveSettingListSetForm(params).then(rs => {
						const {
							status
						} = rs;

						if (status == '1') {
							message.success(i18n.message.saveSuccess());
							this.getTableInfo();
							this.closeDialog('main');
						} else {
							message.warning(i18n.message.saveFailed());
						}
					}).catch(error => {
						message.error(error);
					});
				} else {
					f.showErrors();
					this.setDate({
						date: new Date()
					});
				}
			})
		} else { //保存在线考勤设置
			const {
				form
			} = this.signFormInfo;


			form.validateForm().then(f => {
				if (f.isValid) {
					const {
						signTimeScope_start,
						signTimeScope_end
					} = form.getFormParams();

					if (!this.isPaired(signTimeScope_start, signTimeScope_end)) {
						message.warning(i18n.message.startTimeIsAlone());
						return
					}

					if (signTimeScope_start && signTimeScope_end && !this.isFinishTimeLater(signTimeScope_start, signTimeScope_end)) {
						message.warning(i18n.message.startTimeMustGreater());
						return
					}

					const params = {
						...form.getFormParams(),
						id: this.mainTable.selectedRowsKeys,
					}

					Api.saveOnlineKqSystemSetForm(params).then(rs => {
						this.recoverloading('sign');
						const {
							status
						} = rs;

						if (status == '1') {
							message.success(i18n.message.saveSuccess());
							this.getTableInfo();
							this.closeDialog('main');
						} else {
							message.warning(i18n.message.saveFailed());
						}
					}).catch(error => {
						message.error(error);
					});
				} else {
					f.showErrors();
					this.setDate({
						date: new Date()
					});
				}
			})
		}
	}

	isPaired = (startTime, endTime) => {
		if ((startTime && !endTime) || (!startTime && endTime)) {
			return false
		}

		return true
	}

	isFinishTimeLater = (startTime, endTime) => {
		let arr = [];

		['startTime', 'endTime'].map(t => {
			eval(t).split(':').map(m => {
				arr.push(parseInt(m))
			});
		});

		const [startHour, startMinutes, endHour, endMinutes] = arr;

		if (startHour > endHour) {
			return false
		}
		if ((startHour == endHour) && (startMinutes >= endMinutes)) {
			return false
		}

		return true
	}

	@action
	deepValidate = (f) => {
		const arr = f.fieldArr,
			params = this.formInfo.form.getFormParams(),
			startTime = params.fromvalidedate,
			endTime = params.tovalidedate;

		for (let i = 0; i < arr.length; i++) {
			if (arr[i].conditionType == 'RANGEPICKER' && !startTime && !endTime) {
				f.showError('fromvalidedate__tovalidedate', i18n.message.effectiveDateRequired());
				return false
			}
		}
		return true;
	}

	@action
	jsonTranslate = (datas) => {
		const keys = ['monstarttime1', 'monendtime1', 'monstarttime2', 'monendtime2',
			'tuestarttime1', 'tueendtime1', 'tuestarttime2', 'tueendtime2',
			'wedstarttime1', 'wedendtime1', 'wedstarttime2', 'wedendtime2',
			'thustarttime1', 'thuendtime1', 'thustarttime2', 'thuendtime2',
			'fristarttime1', 'friendtime1', 'fristarttime2', 'friendtime2',
			'satstarttime1', 'satendtime1', 'satstarttime2', 'satendtime2',
			'sunstarttime1', 'sunendtime1', 'sunstarttime2', 'sunendtime2'
		];

		let values = [];
		toJS(datas).map(data => {
			data.am.map(item => {
				values.push(item)
			})
			data.pm.map(item => {
				values.push(item)
			})
		});

		const obj = {};
		keys.map((key, index) => {
			obj[key] = values[index];
		});

		return obj;
	}

	@action
	ignorePartVerify = () => {
		const {
			selectedScopeValue,
			selectedNumberValue
		} = this.formInfo;

		const arr = ['relatedId', 'signStartTime'];

		let noVerifyField;
		if (selectedScopeValue == '3') {
			if (selectedNumberValue == '1') {
				noVerifyField = arr;
			} else {
				noVerifyField = arr.slice(0, 1);
			}
		} else {
			if (selectedNumberValue == '1') {
				noVerifyField = arr.slice(1, 2);
			} else {
				noVerifyField = [];
			}
		}

		window.e9HideFormFieldKeys = noVerifyField;
	}

	@action
	verifyTableEdit = () => {
		const datas = toJS(this.tableEdit.datas);

		for (let i = 0; i < datas.length; i++) {
			if (datas[i].am.some(item => item) || datas[i].pm.some(item => item)) {
				if (!this.isCouple(datas[i])) return false
			}
		}
		return true;
	}

	@action
	isCouple = (datas) => {
		const bool = datas.am.every(item => item) && datas.pm.every(item => item);
		if (!bool) {
			message.warning(i18n.message.startTimeIsAlone());
			return false
		} else {
			if (!this.isGreater(datas)) return false
		}

		return true;
	}

	@action
	isGreater = (datas) => {
		const {
			compareTime
		} = this, {
			selectedTimeValue,
			selectedNumberValue,
		} = this.formInfo;

		const startAmTime = datas.am[0],
			endAmTime = datas.am[1],
			startPmTime = datas.pm[0],
			endPmTime = datas.pm[1];

		const bool = compareTime(startAmTime, endAmTime) && compareTime(startPmTime, endPmTime);

		if (!bool) {
			message.warning(i18n.message.startTimeMustGreater());
			return false
		} else {
			if (!compareTime(endAmTime, startPmTime)) {
				message.warning(i18n.message.afternoonStartTimeShouldBeLater());
				return false
			} else {
				if (selectedNumberValue == '2' && selectedTimeValue && (!compareTime(endAmTime, selectedTimeValue) || !compareTime(selectedTimeValue, startPmTime))) { //校验二次签到时间
					message.warning(i18n.message.secondSignTip());
					return false
				}
			}
		}
		return true;
	}


	@action
	compareTime = (startTime, endTime) => {
		const st = startTime.split(':'),
			dt = endTime.split(':'),
			st0 = parseInt(st[0]),
			st1 = parseInt(st[1]),
			dt0 = parseInt(dt[0]),
			dt1 = parseInt(dt[1]);

		if (st0 > dt0) {
			return false
		}
		if (st0 == dt0) {
			if (!(st1 < dt1)) {
				return false
			}
		}

		return true;
	}

	@action
	translate = (datas) => {

		let obj = {};
		datas.map(data => {
			Object.assign(obj, data);
		});

		const arr = Object.values(obj);

		let advanceDatas = toJS(this.tableEdit.datas)

		arr.map((val, index) => {
			let i = Math.floor(index / 4); //对应advanceDatas索引值

			if (advanceDatas[i].am.length < 2) {
				advanceDatas[i].am.push(val)
			} else {
				advanceDatas[i].pm.push(val)
			}

		});

		return advanceDatas;
	}

	@action
	resetTableEdit = () => {
		const datas = toJS(this.tableEdit.datas);

		datas.map(data => {
			data.am = [];
			data.pm = [];
		});

		this.tableEdit.datas = datas;

		this.tableEdit.selectedIndexs = [];
	}

	@action
	changeAm = (cb, index) => {
		const datas = toJS(this.tableEdit.datas);

		if (cb.length !== 0) {
			datas[index].am = cb;
		} else {
			datas[index].am = ['', ''];
		}

		this.tableEdit.datas = datas;
	}

	@action
	changePm = (cb, index) => {
		const datas = toJS(this.tableEdit.datas);

		if (cb.length !== 0) {
			datas[index].pm = cb;
		} else {
			datas[index].pm = ['', ''];
		}

		this.tableEdit.datas = datas
	}

	@action
	adjustSearchCondtion = (conditions) => {
		conditions[0].items.splice(2, 1);
	}

	@action
	recoverloading = (type) => {
		if (type == 'basic') {
			this.formInfo.loading = true;
		} else {
			this.signFormInfo.loading = true;
		}
	}

	@action
	stoploading = (type) => {
		if (type == 'search') {
			this.searchPanel.loading = false;
		} else if (type == 'basic') {
			this.formInfo.loading = false;
		} else {
			this.signFormInfo.loading = false;
		}
	}

	@action
	deleteTableInfo = () => {
		const params = {
			id: this.mainTable.selectedRowsKeys
		}

		Api.deleteTableRows(params).then(rs => {
			const {
				status
			} = rs;

			if (status == '1') {
				message.success(i18n.message.deleteSuccess());
				this.getTableInfo();
			} else {
				message.warning(i18n.message.actionError())
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	clickTreeNode = (id, type, name) => {
		this.setTreeNodeInfo(id, type, name);
		this.resetSearchInfo();
		this.refreshTable();
		this.getTableInfo();
	}

	@action
	setTreeNodeInfo = (id, type, name) => {
		this.leftTree.nodeId = id;
		this.leftTree.nodeType = type;
		this.leftTree.nodeName = name;
	}

	@action
	setBaseSearchValue = (val) => { //设置搜索的基本值
		this.searchPanel.baseSearchValue = val;
	}

	@action
	closeAuth = () => { //关闭权限
		this.main.authorized = false;
	}

	@action
	changeSearchPanelStatus = (bool) => { //改变弹框的状态
		this.searchPanel.isPanelShow = bool;
	}

	@action
	openDialog = (dialogType, contentType) => { //打开弹框（包括一级弹框和二级弹框）
		if (dialogType == 'main') {
			this.mainDialog.contentType = contentType;
			this.mainDialog.visible = true;
			this.mainDialog.title = (contentType == 'new') ? i18n.label.newWorkHour() : i18n.label.editWorkHour();

			this.getFormInfo('basic');
			(contentType == 'edit') && this.getFormInfo('sign')
		} else {
			this.subDialog.visible = true;
			this.subDialog.title = i18n.label.selectQuotingSet();

		}
	}

	@action
	closeDialog = (type) => { //关闭弹框
		if (type == 'main') {
			const {
				contentType
			} = this.mainDialog;

			this.mainDialog.visible = false;
			this.refreshFormInfo();
			this.resetTableEdit();
			contentType == 'edit' && this.refreshSignFormInfo();
		} else {
			this.subDialog.visible = false;
		}
	}

	@action
	setSelectedRowsKeys = (keys) => { //设置列表被选中的值（用作编辑和删除的参数）
		this.mainTable.selectedRowsKeys = keys;
	}

	@action
	setTableEditDatas = (datas) => { //修改可编辑列表的值
		this.tableEdit.datas = datas;
	}

	@action
	exportSelectedValue = (val, type) => {
		if (type == 'scope') {
			this.formInfo.selectedScopeValue = val;
		} else if (type == 'number') {
			this.formInfo.selectedNumberValue = val;
		} else {
			this.formInfo.selectedTimeValue = val;
		}
	}

	@action
	refreshPage = () => { //刷新页面
		this.resetSearchInfo();
		this.forceLeftTreeRefresh();
		this.getTableInfo();
		this.clickTreeNode('0', '0', i18n.module.generalWorkingHours());
	}

	@action
	resetSearchInfo = () => { //重置搜索条件
		this.searchPanel.isPanelShow = false;
		this.searchPanel.form.resetConditionValue();
		this.searchPanel.baseSearchValue = '';
	}

	@action
	refreshFormInfo = () => { //重置表单
		this.formInfo.form = new WeaForm();
		this.formInfo.conditions = [];
		this.formInfo.loading = true;
		this.formInfo.selectedScopeValue = '3';
		this.formInfo.selectedNumberValue = '1';
		this.formInfo.selectedTimeValue = '';
	}

	@action
	refreshSignFormInfo = () => { //重置表单
		this.signFormInfo.form = new WeaForm();
		this.signFormInfo.conditions = [];
		this.signFormInfo.loading = true;
	}

	@action
	refreshTable = () => { //重置列表
		this.mainTable.tableStore = new TableStore();
	}


	@action
	clickTab = (key) => { //tab切换
		this.tabInfo.selectedKey = key;
	}

	@action
	resetSelectInfo = () => {
		this.selectCom.selectedValue = '0';
	}

	@action
	resetBasicSet = () => { //清除一般工作时间设置
		this.formInfo.form.resetConditionValue();
		this.formInfo.selectedScopeValue = '3';
		this.formInfo.selectedNumberValue = '1';

		const datas = toJS(this.tableEdit.datas);

		datas.map(data => {
			data.am = [];
			data.pm = [];
		});

		this.tableEdit.datas = datas;
	}

	@action
	setRef = (com) => {
		this.tableEdit.com = com;
	}

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

	@action
	synchro = () => {
		const {
			selectedIndexs,
			com
		} = this.tableEdit, {
			selectedValue
		} = this.selectCom;

		const datas = toJS(this.tableEdit.datas),
			index = parseInt(selectedValue),
			am = datas[index].am,
			pm = datas[index].pm;


		toJS(selectedIndexs).map(i => {
			datas[i].am = am;
			datas[i].pm = pm;
		})

		this.tableEdit.datas = datas;

		this.tableEdit.selectedIndexs = [];
	}

	@action
	setSelectedIndex = (indexs) => { //tableEdit选中行的索引
		this.tableEdit.selectedIndexs = indexs;
	}

	@action
	setSelectDateIndex = (key) => { //下拉框选中值的key（可以被用作索引）
		this.selectCom.selectedValue = key;
	}

	@action
	setDate = (date) => {
		this.date = date;
	}

}