import * as Api from '../apis/trainArrange';
import {
	toJS
} from 'mobx';
import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaForm,
	WeaTableNew
} from 'comsMobx';
import {
	message
} from 'antd';
import {
	i18n
} from '../public/i18n';
import {
	openTrainArrange
} from '../public/pulic-func';
const {
	TableStore
} = WeaTableNew;

export class HrmTrainArrange {
	@observable date = '';
	@observable main = {
		authorized: false,
		title: i18n.module.trainArrange(),
		btnMenu: [],
		loading: true,
	}
	@observable searchPanel = {
		form: new WeaForm(),
		conditions: [],
		loading: true,
		isPanelShow: false,
		conditionCount: observable.ref(2),
	}
	@observable mainDialog = {
		title: '',
		visible: false,
		contentType: 'new',
	}
	@observable subDialog = {
		title: '',
		visible: false,
		contentType: 'new',
	}
	@observable mainTable = {
		tableStore: new TableStore(),
		selectedRowsKeys: '',
		funcIndex: '',
	}
	@observable subTable = {
		tableStore: new TableStore(),
		selectedRowsKeys: '',
	}
	@observable formInfo = {
		form: new WeaForm(),
		conditions: [],
		loading: true,
		selectedValue: '',
		hasBtn: false, //是否有保存按钮
	}
	@observable schedule = {
		columns: [],
		datas: [],
		loading: true,
	}
	@observable tabInfo = {
		selectedKey: '0'
	}
	@observable singlePage = {
		form: new WeaForm(),
		conditions: [],
		loading: true,
		tableStore: new TableStore(),
		trainPlanId: '',
	}

	@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 {
				api_status,
				btnMenu,
			} = rs;

			if (api_status) {
				this.main.btnMenu = btnMenu;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

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

		if (type == 'main') { //主表（培训安排）
			func = 'getMainTable';
			ts = this.mainTable.tableStore;
			params = {
				...this.searchPanel.form.getFormParams()
			};

		} else { //副表(公开范围)
			func = 'getSubTable';
			ts = this.subTable.tableStore;
			params = {
				trainPlanId: this.mainTable.selectedRowsKeys
			}
		}

		Api[func](params).then(rs => {
			const {
				api_status,
				sessionkey,
			} = rs;

			if (api_status) {
				sessionkey && ts.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 == 'main') { //培训安排
			func = 'getMainForm';
			if (this.mainDialog.contentType == 'edit') {
				params = {
					trainPlanId: this.mainTable.selectedRowsKeys
				}
			} else {
				params = {}
			}
		}

		if (type == 'sub') { //公开范围
			func = 'getSubForm';
			if (this.subDialog.contentType == 'edit') {
				params = {
					trainPlanRangeId: this.subTable.selectedRowsKeys
				}
			} else {
				params = {}
			}
		}


		Api[func](params).then(rs => {
			const {
				api_status,
				conditions,
				hasBtn = true,
			} = rs;

			if (api_status) {
				if (conditions) {
					// this.deleteParam(conditions); //todo
					if (type == 'search') {
						this.searchPanel.conditions = conditions;
						this.searchPanel.form.initFormFields(conditions);
						this.stoploading('search');
					} else {
						this.adjustCondition(conditions, type);
						this.formInfo.conditions = conditions;
						this.formInfo.form.initFormFields(conditions);
						this.formInfo.hasBtn = hasBtn;
						this.stoploading('form');
					}
				}

			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	deleteParam = (conditions) => {
		conditions.map(c => {
			c.items.map(item => {
				if (item.conditionType == 'INPUT') {
					delete item.otherParams
				}
			})
		});
	}

	@action
	adjustCondition = (conditions, type) => {
		conditions.map(c => {
			c.items.map(item => {
				const key = item.domkey[0];

				if (type == 'main') {
					if (key == 'planStartDate') {
						this.addLimitParam(item.value, conditions);
					}
					if (key == 'trainPlanActor') {
						item.rules = 'required|string'
					}
					if (key == 'trainPlanBudget') {
						item.conditionType = 'INPUTNUMBER'
					}
				} else {
					if (key == 'seclevel') {
						delete item.rules
					}
					if (key == 'trainPlanRangeType') {
						this.exportSelectedValue(item.value);
					}
				}
			});
		});
	}

	@action
	addLimitParam = (date, conditions, type) => {
		const cs = conditions || this.formInfo.conditions;

		cs.map(c => {
			c.items.map(item => {
				if (item.domkey[0] == 'planEndDate') {
					item.startValue = date;
				}
			});
		});

		if (type == 'single') {
			this.singlePage.conditions = cs;
		} else {
			this.formInfo.conditions = cs;
		}
	}

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

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

	@action
	save = (dialogType) => {
		const {
			form
		} = this.formInfo;
		dialogType == 'sub' && this.verify(); //因为是联动表单，所以这里需要特殊校验（只校验当前展示的字段）。

		form.validateForm().then(f => {
			if (f.isValid) {
				let func;
				let params;

				this.recoverloading('form');

				if (dialogType == 'main') { //保存主表单（培训安排）
					params = this.formInfo.form.getFormParams();

					if (this.mainDialog.contentType == 'edit') { //编辑
						func = 'saveEditMainForm';
						params = {
							trainPlanId: this.mainTable.selectedRowsKeys,
							...params
						}
					} else {
						func = 'saveMainForm'; //新建
					}

				} else { //保存副表单（公开范围）
					params = { //新建
						trainPlanId: this.mainTable.selectedRowsKeys,
						...form.getFormParams()
					}

					if (this.subDialog.contentType == 'edit') {
						func = 'saveEditSubForm';
						params = { //编辑
							trainPlanRangeId: this.subTable.selectedRowsKeys,
							...params
						}
					} else {
						func = 'saveSubForm';
					}
				}

				Api[func](params).then(rs => {
					const {
						api_status,
						sign
					} = rs;

					if (api_status) {
						if (sign == '1') {
							message.success(rs.message);
							this.closeDialog(dialogType);
							this.getTableInfo(dialogType);
							this.stoploading('form');
						} else {
							message.warning(rs.message)
						}
					} else {
						message.error(rs.message);
					}
				}).catch(error => {
					message.error(error);
				});
			} else {
				f.showErrors();
				this.setDate({
					date: new Date()
				});
			}
		})
	}

	@action
	saveSchedule = () => {
		const {
			com,
			datas
		} = this.schedule;

		if (com.refs.edit.doRequiredCheck().pass) {
			const params = {
				rowIndex: toJS(datas).length,
				trainPlanId: this.mainTable.selectedRowsKeys,
				...this.jsonTranslation(toJS(datas))
			}

			this.recoverloading('schedule');

			Api.saveSchedule(params).then(rs => {
				const {
					api_status,
					sign
				} = rs;

				if (api_status) {
					if (sign == '1') {
						message.success(rs.message);
						this.getTableInfo('main');
					} else {
						message.warning(rs.message)
					}
					this.stoploading('schedule');
				} else {
					message.error(rs.message);
				}
			}).catch(error => {
				message.error(error);
			});
		} else {
			return
		}
	}

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

		if (type == 'main') { //删除主表（培训安排）
			func = 'deleteMainTableInfo';
			params = {
				trainPlanIds: this.mainTable.selectedRowsKeys
			}
		} else { //删除副表（公开范围）

			func = 'deleteSubTableInfo';
			params = {
				trainPlanRangeIds: this.subTable.selectedRowsKeys
			}
		}

		Api[func](params).then(rs => {
			const {
				api_status,
				sign
			} = rs;

			if (api_status) {
				if (sign == '1') {
					message.success(rs.message);
					this.getTableInfo(type);
				} else {
					message.warning(rs.message)
				}
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	notify = () => {
		const {
			selectedRowsKeys
		} = this.mainTable;

		const params = {
			trainPlanId: selectedRowsKeys
		};
		Api.notify(params).then(rs => {
			const {
				api_status,
				sign,
			} = rs;

			if (api_status) {
				const func = (sign == '1') ? 'success' : 'warning';
				message[func](rs.message);
			} else {
				message.error(rs.message)
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	getTrainSchedule = () => {
		const {
			selectedRowsKeys
		} = this.mainTable;

		const params = {
			trainPlanId: selectedRowsKeys
		};

		this.recoverloading('schedule');

		Api.getTrainSchedule(params).then(rs => {
			const {
				api_status,
				columns,
				datas,
			} = rs;

			if (api_status) {
				this.schedule.columns = columns;
				this.schedule.datas = datas;
			} else {
				message.error(rs.message)
			}
			this.stoploading('schedule');
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	getTrainPlanContent = (id, type) => {
		const params = {
			trainLayoutId: id
		};

		Api.getTrainLayoutInfo(params).then(rs => {
			const {
				api_status,
			} = rs;

			if (api_status) {
				this.updateTrainPlanForm(rs, type);
			} else {
				message.warning(rs.error)
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	updateTrainPlanForm = (rs, type) => {
		const {
			trainLayoutContent,
			trainLayoutAim,
			layoutStartDate,
			layoutEndDate,
		} = rs;

		let form;

		if (type == 'single') {
			form = this.singlePage.form;
		} else {
			form = this.formInfo.form;
		}

		form.updateFields({
			trainPlanContent: {
				value: trainLayoutContent
			},
			trainPlanAim: {
				value: trainLayoutAim
			},
			planStartDate: {
				value: layoutStartDate
			},
			planEndDate: {
				value: layoutEndDate
			},
		})
	}

	@action
	getWorkFlowId = (id) => {
		Api.getWorkFlowId().then(rs => {
			const {
				api_status,
				workFlowId
			} = rs;

			if (api_status) {
				openTrainArrange(workFlowId, id || this.mainTable.selectedRowsKeys)
			} else {
				message.warning(rs.api_errormsg)
			}
		}).catch(error => {
			message.error(error);
		});
	}


	@action
	verify = () => {
		const {
			selectedValue
		} = this.formInfo;

		this.refreshContainer(); //重置e9HideFormFieldKeys容器

		let type;
		switch (selectedValue) { //设置需要校验的字段
			case '0':
				type = ''
				break;
			case '1':
				type = 'departmentId'
				break;
			case '2':
				type = 'jobactivitieId'
				break;
			case '3':
				type = 'jobtitleId'
				break;
			case '4':
				type = 'resourceId'
				break;
			case '5':
				type = 'subcompanyId'
				break;
		}
		this.needVerify(type);
	}

	@action
	refreshContainer = () => {
		window.e9HideFormFieldKeys = [];
		const arr = ['subcompanyId', 'departmentId', 'jobactivitieId', 'jobtitleId', 'resourceId'];
		window.e9HideFormFieldKeys = arr;
	}

	@action
	needVerify = (domkey) => {
		if (domkey) {
			const keys = window.e9HideFormFieldKeys;
			keys.splice(keys.findIndex(key => key == domkey), 1);
		}
	}

	@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.newTrainArrangement() : (contentType == 'edit') ? i18n.label.editTrainArrangement() : i18n.label.publicScope();
		} else {
			this.subDialog.contentType = contentType
			this.subDialog.visible = true;
			this.subDialog.title = (contentType == 'new') ? i18n.label.newPublicScope() : i18n.label.editPublicScope();
		}
	}

	@action
	closeDialog = (type) => { //关闭弹框
		if (type == 'main') {
			this.mainDialog.visible = false;
		} else {
			this.subDialog.visible = false;
		}
	}

	@action
	setSelectedRowsKeys = (keys, type) => { //设置列表被选中的值（用作编辑和删除的参数）
		if (type == 'main') {
			this.mainTable.selectedRowsKeys = keys
		} else if (type == 'sub') {
			this.subTable.selectedRowsKeys = keys;
		} else {
			this.singlePage.trainPlanId = keys;
		}
	}

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

	@action
	refreshPage = () => { //刷新页面
		this.resetSearchInfo();
		this.getTableInfo('main');
	}

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

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

	@action
	refreshTable = (type) => { //重置列表
		if (type == 'main') {
			this.mainTable.tableStore = new TableStore();
		} else {
			this.subTable.tableStore = new TableStore();
		}
	}

	@action
	refreshTableEdit = () => { //重置可编辑列表
		this.schedule.columns = [];
		this.schedule.datas = [];
	}

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

	@action
	jsonTranslation = (datas) => { //json转换
		let obj = {};
		datas.map((data, index) => {
			let o = {};
			for (let key of Object.keys(data)) {
				o[`${key}_${index}`] = data[key];
			}
			Object.assign(obj, o);
		})

		return obj;
	}

	@action
	exportSelectedValue = (val) => { //抛出浏览框回调的值
		this.formInfo.selectedValue = val;
	}

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

	@action
	setFuncIndex = (index) => {
		this.mainTable.funcIndex = index;
	}

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

	//----------------------------单页----------------------------
	@action
	getSingleArrangeInfo = (bool) => {
		this.singlePage.form = new WeaForm()
		this.singlePage.conditions = [];
		this.singlePage.loading = true;

		const params = {
			trainPlanId: this.singlePage.trainPlanId,
			isView: bool
		}

		Api.getSingleArrangeInfo(params).then(rs => {
			const {
				api_status,
				conditions,
				sessionkey
			} = rs;

			if (api_status) {
				bool && this.adjustSinglePageCondition(conditions)
				this.singlePage.conditions = conditions;
				this.singlePage.form.initFormFields(conditions);

				this.singlePage.tableStore.getDatas(sessionkey, 1);
				this.singlePage.loading = false;

				this.getSinglePageButtonsMenu(bool);
			} else {
				message.error(rs.message)
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	adjustSinglePageCondition = (conditions) => {
		conditions.map(c => {
			c.items.map(item => {
				if (item.conditionType == 'TEXTAREA' && item.viewAttr == 1) {
					item.conditionType = 'INPUT'
				}
			});
		});
	}

	@action
	getSinglePageButtonsMenu = (bool) => {
		const params = {
			trainPlanId: this.singlePage.trainPlanId,
			isView: bool
		}
		Api.getSinglePageButtonsMenu(params).then(rs => {
			const {
				api_status,
				btnMenu,
			} = rs;

			if (api_status) {
				this.main.btnMenu = btnMenu;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	singlePageSave = () => {
		const {
			form,
			trainPlanId
		} = this.singlePage;

		form.validateForm().then(f => {
			if (f.isValid) {
				const params = {
					trainPlanId: trainPlanId,
					...form.getFormParams()
				}
				Api.saveEditMainForm(params).then(rs => {
					const {
						api_status,
						sign
					} = rs;

					if (api_status) {
						if (sign == '1') {
							message.success(rs.message);
							this.getSingleArrangeInfo(true);
						} else {
							message.warning(rs.message)
						}
					} else {
						message.error(rs.message);
					}
				}).catch(error => {
					message.error(error);
				});
			} else {
				f.showErrors();
				this.setDate({
					date: new Date()
				});
			}
		})
	}
}