import * as Api from '../apis/salaryIndexMaintenance';
import {
	toJS
} from 'mobx';
import {
	observable,
	action,
	computed,
	extendObservable,
} from 'mobx';
import {
	WeaForm,
	WeaTableNew
} from 'comsMobx';
import {
	message
} from 'antd';
import {
	i18n
} from '../public/i18n';
import {addContentPath} from '../util/index.js'
const {
	TableStore
} = WeaTableNew;

export class HrmSalaryIndexMaintenance {
	title = i18n.module.salaryIndexMaintenance();
	@observable btnMenu = [];
	@observable authorized = false;
	@observable loading = true;
	@observable isPanelShow = false;
	@observable leftTree = {
		treeNodeId: '',
		triggerRefresh: false,
		nodeType: '0',
	}
	@observable table = {
		tableStore: new TableStore(),
		selectedRowsKeys: '',
	}
	@observable searchPanel = {
		condition: [],
		form: new WeaForm(),
		value: '',
		loading: true,
		conditionCount: observable.ref(2),
	}
	@observable editor = {
		visible: false,
		form: new WeaForm(),
		condition: [],
		floading: true,
		tloading: true,
		date: '',
		excelFileId: '',
		tableEditDatas: [],
		datas: [],
		columns: [],
		hasImportRight: false,
		url: '',
		com: {},
		otherParams: {},
		isImportFinish: false,
		total:0,
	}
	@observable resultDialog = {
		datas: [],
		title: observable.ref(i18n.label.importResult()),
		visible: false,
		loading: true,
	}

	@observable currentPage = 1;
	@observable pageSize = 10;

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

		return {
			topMenu,
			rightMenu
		}
	}

	@action setPageSize = (pageSize) => {
		this.pageSize = pageSize;
	}

	@action setCurrentPage = (currentPage) => {
		this.currentPage = currentPage;
	}

	getImportTemplate = () => {
		const params = this.getTableEditParams();

		Api.getImportTemplate(params).then(datas => {
			const {status} = datas;

			if (status === '1') {
				window.location.href = addContentPath(this.editor.url) ;
			}else{
				message.warning(datas.message);
			}
		})
	}

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

			if (status == '1') {
				if (hasRight) {
					this.authorized = true;
					this.handleLeftTreeClick(0, '0');
				} else {
					this.loading = false;
				}
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	getTableInfo = () => {
		this.table.tableStore = new TableStore(); //清空表格选中状态

		const {
			value,
			form
		} = this.searchPanel;

		let params = {
			qname: value
		};

		const {
			subcompanyid,
			compensationyearmonth
		} = form.getFormParams();

		if (form.isFormInit) {
			params = {
				subcompanyid: subcompanyid,
				...params,
				...this.dateSplit(compensationyearmonth)
			};
		}

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

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

	@action
	dateSplit = (date) => {
		const arr = date.split('-'),
			year = arr[0],
			month = arr[1];

		return {
			compensationyear: year,
			compensationmonth: month
		}
	}

	@action
	getSubordinateTableInfo = () => {
		this.table.tableStore = new TableStore(); //清空表格选中状态

		const {
			value,
			form
		} = this.searchPanel, {
			treeNodeId,
			nodeType
		} = this.leftTree;

		let params;
		if (nodeType == '1') {
			params = {
				subcompanyid: treeNodeId,
			}
		} else if (nodeType == '2') {
			params = {
				departmentid: treeNodeId,
			}
		}

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

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

	@action
	getButtonsMenu = () => {
		const {
			treeNodeId,
			nodeType
		} = this.leftTree;

		let params;
		if (nodeType == '0') {
			params = {}
		} else if (nodeType == '1') {
			params = {
				subcompanyid: treeNodeId
			}
		} else {
			params = {
				departmentid: treeNodeId
			}
		}

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

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

	@action
	getSearchCondition = () => {
		Api.getSearchCondition().then(rs => {
			const {
				formField,
				status = '1',
			} = rs;

			if (status == '1') {
				if (formField) {
					this.searchPanel.condition = formField;
					this.searchPanel.form.initFormFields(formField);
				}
				this.searchPanel.loading = false;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	getEditorDatas = () => {
		this.getEditorForm();
	}

	@action
	getEditorForm = () => {
		this.editor.floading = true;

		const {
			treeNodeId,
			nodeType
		} = this.leftTree, {
			formType
		} = this.editor, {
			selectedRowsKeys
		} = this.table;

		let params;
		if (nodeType == '0') {
			params = {}
		} else if (nodeType == '1') {
			params = {
				subcompanyid: treeNodeId
			}
		} else {
			params = {
				departmentid: treeNodeId
			}
		}
		if (formType == 'edit') {
			params = {
				id: selectedRowsKeys,
				...params,
			};

		}
		Api.getEditorForm(params).then(rs => {
			const {
				status,
				formField,
				otherParams,
				url = '',
			} = rs;

			if (status == '1') {
				if (formField) {
					this.operateEditorCondition(formField);
					this.editor.condition = formField;
					this.editor.form.initFormFields(formField);
					this.editor.url = addContentPath(url) ;
					this.editor.otherParams = otherParams;
					this.resetPagination();
					this.getTableEditDatas();
				}
				this.editor.floading = false;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	resetPagination = () => {
		this.setCurrentPage(1);
		this.setPageSize(10);
	}

	operateEditorCondition = (conditions) => {
		const {
			formType
		} = this.editor;

		conditions.map(c => {
			c.items.map(item => {
				const type = item.conditionType;
				if (type == 'INPUT' || (type == 'DATEPICKER' && formType == 'edit')) {
					if (item.conditionType !== 'INPUT') item.conditionType = 'INPUT';
					item.otherParams = {
						hasBorder: true
					}
				}
			})
		});
	}

	getTableEditParams = () => {
		const {
			selectedRowsKeys
		} = this.table, {
			formType,
			form,
			isImportFinish,
		} = this.editor, {
			nodeType,
			treeNodeId
		} = this.leftTree, {
			compensationyearmonth
		} = form.getFormParams();

		let params = {
			isImportSuccess: (formType == 'new' && isImportFinish) ? 1 : 0,
			...this.dateSplit(compensationyearmonth)
		}

		if (nodeType == '1') {
			params = {
				...params,
				subcompanyid: treeNodeId
			}

		} else {
			params = {
				...params,
				departmentid: treeNodeId
			}
		}

		if (formType == 'edit') {
			params = {
				id: selectedRowsKeys,
				...params,
			};
		}

		return params;
	}

	@action
	getTableEditDatas = () => {
		this.editor.tloading = true;

		const params = Object.assign({},this.getTableEditParams(),{
			currentPage : this.currentPage,
			pageSize: this.pageSize,
		})

		Api.getTableEditDatas(params).then(rs => {
			const {
				status,
				table,
				count,
			} = rs, {
				datas = [],
				columns = [],
			} = table;

			if (status == '1') {
				this.editor.total = count;
				this.editor.datas = datas;
				this.editor.columns = columns;
				this.editor.tloading = false;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	getEditorAuth = () => {
		const {
			treeNodeId,
			nodeType,
		} = this.leftTree, {
			selectedRowsKeys
		} = this.table, {
			formType
		} = this.editor;

		let params;
		if (nodeType == '0') {
			params = {}
		} else if (nodeType == '1') {
			params = {
				subcompanyid: treeNodeId
			}
		} else {
			params = {
				departmentid: treeNodeId
			}
		}

		if (formType == 'edit') {
			params = {
				id: selectedRowsKeys,
				...params,
			}
		}

		Api.getEditorAuth(params).then(rs => {
			const {
				status,
				hasButton
			} = rs;

			if (status == '1') {
				this.editor.hasImportRight = hasButton;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	deleteTableRows = () => {
		const {
			nodeType,
			treeNodeId
		} = this.leftTree;

		let params = {
			ids: this.table.selectedRowsKeys
		};
		if (nodeType == '1') {
			params = {
				subcompanyid: treeNodeId,
				...params
			}
		} else if (nodeType == '2') {
			params = {
				departmentid: treeNodeId,
				...params
			}
		}

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

			if (status == '1') {
				if (success) {
					message.success(rs.message);
					(nodeType == '0') ? this.getTableInfo(): this.getSubordinateTableInfo();
				} else {
					message.warning(rs.message)
				}
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	editorSave = () => {
		const {
			formType,
			com,
			tableEditDatas,
			datas
		} = this.editor, {
			nodeType,
			treeNodeId,
		} = this.leftTree, {
			selectedRowsKeys,
		} = this.table;

		if (tableEditDatas.length == 0) {
			this.setTableEditDatas(datas);
		} else {
			this.setTableEditDatas(tableEditDatas)
		}

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

				const {
					subcompanyshow,
					compensationyearmonth
				} = this.editor.form.getFormParams();

				let params = {
					subcompanyshow: subcompanyshow,
					detailData:JSON.stringify(toJS(this.editor.tableEditDatas)),
					...this.dateSplit(compensationyearmonth),
				}

				if (nodeType == '0') {
					params = {
						...params
					}
				} else if (nodeType == '1') {
					params = {
						subcompanyid: treeNodeId,
						...params
					}
				} else {
					params = {
						departmentid: treeNodeId,
						...params
					}
				}

				if (formType == 'new') {
					func = 'add';
				} else {
					func = 'edit';
					params = {
						id: selectedRowsKeys,
						...params
					}
				}

				this.editor.floading = true;

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

					if (status == '1') {
						if (success) {
							message.success(rs.message);
							this.setEditorDialogVisible(false);
							(nodeType == '0') ? this.getTableInfo(): this.getSubordinateTableInfo();
						} else {
							message.warning(rs.message)
						}
					} else {
						message.error(rs.message);
					}

					this.editor.floading = false;
				}).catch(error => {
					message.error(error);
				});
			} else {
				f.showErrors();
				this.setDate({
					date: new Date()
				});
			}
		});
	}

	handleFormChange = (datas) => {
		if (datas.compensationyearmonth) {
			this.getTableEditDatas();
		}
	}

	@action
	submit = () => {
		const {
			formType,
			otherParams,
			excelFileId,
			form,
		} = this.editor, {
			nodeType,
			treeNodeId
		} = this.leftTree, {
			compensationyearmonth
		} = form.getFormParams(), {
			selectedRowsKeys
		} = this.table;

		let params = {
			excelfile: excelFileId,
			...this.dateSplit(compensationyearmonth)
		};

		if (nodeType == '1') {
			params = {
				...params,
				subcompanyid: treeNodeId
			}
		} else {
			params = {
				...params,
				departmentid: treeNodeId
			}
		}

		if (formType == 'edit') {
			params = {
				...params,
				id: selectedRowsKeys
			}
		}

		this.setResultInfoDialogVisible(true);

		Api.submit(params).then(rs => {
			const {
				status,
				success,
				errordatas,
			} = rs;

			if (status == '1') {
				if (success) {
					this.finishImport();
				} else {
					if (errordatas) {
						this.resultDialog.datas = errordatas;
					} else {
						this.assembleErrorDatas(rs.message);
					}
				}
				nodeType == '0' ? this.getTableInfo() : this.getSubordinateTableInfo();
				this.getTableEditDatas();
				this.resultDialog.loading = false;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	assembleErrorDatas = (message) => {
		this.resultDialog.datas = [{
			colnum: '',
			message: message,
			rownum: ''
		}]
	}

	@action
	finishImport = () => {
		this.editor.isImportFinish = true;
	}

	@action
	setResultInfoDialogVisible = (bool) => {
		this.resultDialog.visible = bool;

		if (!bool) {
			this.resultDialog.loading = true;
			this.resultDialog.datas = [];
		}

	}

	@action
	setEditorDialogVisible = (bool, type) => {
		this.editor.visible = bool
		if (bool) {
			extendObservable(this.editor, {
				formType: type,
				title: type == 'new' ? i18n.label.newSalaryIndexDatas() : i18n.label.editSalaryIndexDatas(),
			});
			this.getEditorDatas();
			this.getEditorAuth();
		} else {
			this.editorDialogReset();
		}
	}

	@action
	editorDialogReset = () => {
		this.editor.form = new WeaForm();
		this.editor.excelFileId = '';
		this.editor.treeNodeId = '';
		this.editor.columns = [];
		this.editor.datas = [];
		// this.editor.floading = true;
		this.editor.tloading = true;
		this.editor.tableEditDatas = [];
		this.editor.isImportFinish = false;
	}

	@action
	setPanelStatus = (bool) => {
		const {
			condition
		} = this.searchPanel;

		this.isPanelShow = bool;
		bool && this.isEmpty(toJS(condition)) && this.getSearchCondition();
	}

	@action
	setBaseValueOfSearch = (val) => {
		this.searchPanel.value = val;
	}

	@action
	setSelectedRowsKeys = (id) => {
		this.table.selectedRowsKeys = id;
	}

	@action
	handleLeftTreeClick = (id, type, name) => {
		this.leftTree.treeNodeId = id;
		this.isPanelShow && this.setPanelStatus(false);
		this.searchPanel.form.resetForm();
		this.searchPanel.value = '';
		this.leftTree.nodeType = type;
		if (type == '0') {
			this.getTableInfo();
		} else {
			this.getSubordinateTableInfo();
		}
		this.setTitle(type, name);
	}

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

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

	@action
	setExcelFileId = (id) => {
		this.editor.excelFileId = id;
	}

	@action
	setTableEditDatas = (datas) => {
		this.editor.tableEditDatas = datas;
	}

	@action
	setTableEditRef = (com) => {
		this.editor.com = com;
	}

	@action
	setTitle = (type, subTitle) => {
		if (type == '0') {
			this.title = i18n.module.salaryIndexMaintenance();
		} else {
			this.title = i18n.module.salaryIndexMaintenance() + `( ${type=='1' ? i18n.label.subcompany() : i18n.label.department()}: ${subTitle} )`;
		}
	}

	@action
	getTableEditJsonDatas = (datas) => {
		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;
	}

	isEmpty = (c) => {
		if (c.length == 0) return true;
		return false;
	}

	@action
	mobxDatasReset = () => {
		const {
			form
		} = this.searchPanel;
		if (form.isFormInit) form.resetForm();
		this.searchPanel.value = '';
		this.isPanelShow = false;
		this.leftTree.treeNodeId = '';
		this.authorized = false;
		this.loading = true;
	}

}