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

export class HrmPayrollManagement {
	@observable title = i18n.module.payrollManagement();
	@observable btnMenu = [];
	@observable authorized = false;
	@observable loading = true;
	@observable isPanelShow = false;
	@observable exportUrl = '';
	@observable table = {
		tableStore: new TableStore(),
		isEdit: false,
		isPayrollClosed: false,
		date: '',
		com: {},
		datas: [],
		columns: [],
		selectedRowsIds: '',
		callbackInfo: [],
		isHistoryTable: false,
		loading: true,
		deptPayrollInfoId: '',
		selectedRowIndexs: [],
	}
	@observable searchPanel = {
		condition: [],
		form: new WeaForm(),
		baseSearchValue: '',
		loading: true,
	}
	@observable leftTree = {
		nodeId: '',
		nodeType: '0',
		nodeName: i18n.module.payrollManagement(),
		triggerRefresh: false
	}

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

	@observable spinning = false;

	@observable percentage = 0;

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

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

	@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
	getPageAuth = () => {
		this.loading = true;
		Api.getPageAuth().then(rs => {
			const {
				status,
				hasRight
			} = rs;

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

	@action
	getButtonsMenu = () => {
		const {
			nodeType,
			nodeId
		} = this.leftTree, {
			isEdit,
			date,
			isHistoryTable
		} = this.table;

		let func;
		let params;
		if (nodeType == '0' || isHistoryTable) {
			func = 'getAllSubButtonsMenu';
			params = {};
		} else {
			func = 'getDeptButtonsMenu';
			if (nodeType == '1') {
				params = {
					subcompanyid: nodeId,
					yearmonth: date
				}
				if (isEdit) {
					params = {
						isedit: 1,
						...params
					}
				} else {
					params = {
						isedit: 0,
						...params
					}
				}
			} else {
				params = {
					departmentid: nodeId
				}
				if (isEdit) {
					params = {
						isedit: 1,
						...params
					}
				} else {
					params = {
						isedit: 0,
						...params
					}
				}
			}
		}

		Api[func](params).then(rs => {
			const {
				btnMenu,
				url,
				status = '1',
			} = rs;

			if (status == '1') {
				this.btnMenu = btnMenu;
				this.exportUrl = addContentPath(url) ;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

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

		this.resetTableStore();

		let params = {
			qname: baseSearchValue
		};

		if (form.isFormInit) {
			params = {
				...params,
				...form.getFormParams(),
			};
		}

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

		Api.getAllSubPayrollInfoTable(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
	getDeptPayrollInfoTable = () => {
		const params = this.getTableEditParams();

		Api.getDeptPayrollInfoTable(params).then(rs => {
			const {
				status,
				table,
				payid,
				count,
			} = rs, {
				columns,
				datas,
			} = table;

			if (status == '1') {
				this.adjustColumns(columns);
				this.adjustDatas(datas);
				this.table.columns = columns;
				this.table.datas = datas;
				this.table.loading = false;
				this.table.deptPayrollInfoId = payid;
				this.total = count;
				this.getButtonsMenu();
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

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

		let params = {
			qname: baseSearchValue
		};
		if (nodeType == '1') {
			params = {
				subcompanyid: nodeId,
				...params
			}
		} else {
			params = {
				departmentid: nodeId,
				...params
			}
		}
		if (form.isFormInit) {
			params = {
				...params,
				...form.getFormParams(),
			};
		}

		Object.assign(params,{
			currentPage:this.currentPage,
			pageSize:this.pageSize
		});

		Api.getEditableDeptPayrollTable(params).then(rs => {
			const {
				status,
				table,
				payid,
			} = rs, {
				columns,
				datas,
			} = table;

			if (status == '1') {
				this.adjustColumns(columns);
				this.adjustDatas(datas);
				this.table.columns = columns;
				this.table.datas = datas;
				this.table.loading = false;
				this.table.deptPayrollInfoId = payid;
				this.getButtonsMenu();
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	saveDeptPayrollInfo = () => {
		if (!this.isDeptPayrollInfoModify()) {
			return
		};
		this.recoverLoading('table');
		const {
			nodeType,
			nodeId
		} = this.leftTree, {
			callbackInfo,
			deptPayrollInfoId,
			date,
		} = this.table;

		let params;
		if (nodeType == '1') {
			params = {
				subcompanyid: nodeId
			}
		} else {
			params = {
				departmentid: nodeId
			}
		}
		const callback = toJS(callbackInfo),
			datasLength = callback.length;

		params = {
			payid: deptPayrollInfoId,
			detailData:JSON.stringify(toJS(this.table.datas)),
			...params,
		}

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

			if (status == '1') {
				this.quitLoading();
				if (success) {
					const {
						nodeId,
						nodeType,
						nodeName
					} = this.leftTree;

					message.success(rs.message);
					this.clickTreeNode(nodeId, nodeType, nodeName, date);
				} else {
					message.warning(rs.message);
				}

				this.table.callbackInfo = [];
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	adjustColumns = (columns) => {
		columns.map(c => {
			if (c.key == 'sent') {
				delete c.com
				c.useRecord = true
			}
			if (c.com) c.com[0].width = 150;
			c.width = 150
		});
	}

	@action
	adjustDatas = (datas) => {
		datas.map(data => {
			if (data.sent == '1') {
				data.com = {
					sent: [<span style={{color: '#4D7AD8'}}>{i18n.label.sent()}</span>]
				}
			} else {
				data.com = {
					sent: [<span style={{color: '#FF0000'}}>{i18n.label.unsend()}</span>]
				}
			}
		});
	}

	exportExcel = () => {
		if(window.setShare4ec){
			window.setShare4ec({mouldCode: 'HRM', itemCode: 'SALARY', encrypt: '1'}, this.exportFile);
		}else{
			this.exportFile({status: '1'});
		}
	}

	@action exportFile = (data = {}) => {
		if(data.status == '1'){
			const params = this.getTableEditParams();
			Object.assign(params, {sharepassword: data.sharepassword});
			Api.exportExcel(params).then(datas=>{
				const {status,url} = datas;

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

	getTableEditParams = () => {
		const {
			nodeType,
			nodeId
		} = this.leftTree, {
			form,
			baseSearchValue
		} = this.searchPanel, {
			date
		} = this.table;

		let params = {
			qname: baseSearchValue
		};
		if (nodeType == '1') {
			params = {
				subcompanyid: nodeId,
				...params
			}
		} else {
			params = {
				departmentid: nodeId,
				...params
			}
		}
		if (form.isFormInit) {
			params = {
				...params,
				...form.getFormParams(),
			};
		} else if (date) {
			params = {
				...params,
				'yearmonth': date
			}
		}

		return Object.assign({},params,{
			currentPage : this.currentPage,
			pageSize: this.pageSize,
		})
	}

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

		this.clickTreeNode(nodeId, nodeType, nodeName, '', true);
	}

	@action
	jsonTranslation = (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;
	}

	@action
	isDeptPayrollInfoModify = () => {
		const {
			callbackInfo
		} = this.table;

		if (toJS(callbackInfo).length == 0) {
			message.warning(i18n.confirm.noModification());
			return false
		} else {
			return true
		}
	}

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

	@action
	getSearchItems = () => {
		const {
			nodeType,
			nodeId,
		} = this.leftTree, {
			isPayrollClosed,
			date,
			isHistoryTable,
		} = this.table, {
			form
		} = this.searchPanel;

		let func;
		let params;

		if (nodeType == '1') {
			params = {
				subcompanyid: nodeId
			}
		} else if (nodeType == '2') {
			params = {
				departmentid: nodeId
			}
		}
		if (nodeType == '0' || isHistoryTable) {
			func = 'getAllSubSearchItems';
			params = {
				...params
			};
		}
		if (nodeType !== '0' && !isHistoryTable) {
			func = 'getDeptSearchItems';
			if (date) {
				params = {
					...params,
					yearmonth: date
				}
			}
		}
		if (form.isFormInit) {
			params = {
				...params,
				...form.getFormParams()
			}
		}

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

			if (status == '1') {
				if (formField) {
					this.searchPanel.condition = formField;
					this.searchPanel.form.initFormFields(formField);
					this.refreshPageTitle(); //放在这里是为了获取高级搜索中的时间
				}
				this.searchPanel.loading = false;
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	interval = '';

	@action
	createPayroll = () => {
		const {
			nodeType,
			nodeId
		} = this.leftTree, {
			form
		} = this.searchPanel;

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

		params = {
			...params,
			yearmonth: form.getFormParams().yearmonth
		}

		this.percentage = "0";

		this.spinning = true;

		Api.createPayroll(params);

		this.smtParams = params;

		this.getSalaryManageTime();

	}
		
	

	@action getSalaryManageTime = () => {
		Api.getSalaryManageTime(this.smtParams).then(datas => {
			const { status, percentage } = datas;

			if (status === "1") {
				this.percentage = percentage;
				if (percentage !== "100") {
					setTimeout(this.getSalaryManageTime,2000);
				}else{
					message.success(datas.message || "success");
					this.getDeptPayrollInfoTable();
					this.spinning = false;
				}
			}else{
				message.warning(datas.message || "error");
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	sendPayroll = () => {
		const {
			nodeType,
			nodeId
		} = this.leftTree, {
			selectedRowsIds,
			deptPayrollInfoId
		} = this.table;

		let params = {
			resourceids: selectedRowsIds,
			payid: deptPayrollInfoId,
		};
		if (nodeType == '1') {
			params = {
				subcompanyid: nodeId,
				...params
			}
		} else {
			params = {
				departmentid: nodeId,
				...params
			}
		}

		this.spinning = true;

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

			if (status == '1') {
				if (success) {
					message.success(rs.message);
					this.getDeptPayrollInfoTable();
				} else {
					message.warning(rs.message);
				}
			} else {
				message.error(rs.message);
			}

			this.spinning = false;
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	closePayroll = () => {
		const {
			nodeType,
			nodeId
		} = this.leftTree, {
			deptPayrollInfoId
		} = this.table;

		let params = {
			payid: deptPayrollInfoId,
		};
		if (nodeType == '1') {
			params = {
				...params,
				subcompanyid: nodeId
			}
		} else {
			params = {
				...params,
				departmentid: nodeId
			}
		}

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

			if (status == '1') {
				if (success) {
					message.success(rs.message);
					this.getDeptPayrollInfoTable();
				} else {
					message.warning(rs.message);
				}
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

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

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

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

			if (status == '1') {
				if (success) {
					message.success(rs.message);
					this.getButtonsMenu();
				} else {
					message.warning(rs.message);
				}
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

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

		this.isPanelShow = bool;

		bool ? this.getSearchItems() : this.recoverLoading('search');
	}

	@action
	recoverLoading = (type) => {
		if (type == 'search') {
			this.searchPanel.loading = true;
		} else {
			this.table.loading = true;
		}
	}

	@action
	quitLoading = () => {
		this.table.loading = false;
	}

	@action
	setBaseSearchValue = (val) => {
		this.searchPanel.baseSearchValue = val;
	}

	@action
	clickTreeNode = (id, type, name, date, isHistoryTable) => {
		this.setCurrentPage(1);
		this.setTreeNodeInfo(id, type, name);
		this.setPayrollDate(date);
		this.closeSearchPanel();
		this.resetSearch();
		this.makeDeptPayrollTableNoEditable();
		this.releaseSelection();
		this.setIdentification(isHistoryTable);
		this.recoverLoading();
		this.resetSelectedRows();
		this.getTable();
		this.getSearchItems(); //只为了获取日期，需要执行一次接口，是不是很蠢
	}

	@action
	refreshPageTitle = () => {
		const {
			nodeType,
			nodeName
		} = this.leftTree, {
			form
		} = this.searchPanel, {
			yearmonth
		} = form.getFormParams();

		this.table.date = yearmonth;

		if (nodeType == '0') {
			this.title = i18n.module.payrollManagement();
		} else {
			this.title = i18n.module.payrollManagement() + ` > ${nodeName}`;
			if (yearmonth) {
				this.title = this.title + `(${yearmonth})`;
			}
		}
	}

	@action
	setIdentification = (isHistoryTable) => {
		this.table.isHistoryTable = isHistoryTable ? true : false;
	}

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

	@action
	makeDeptPayrollTableNoEditable = () => {
		this.table.isEdit = false;
	}

	@action
	releaseSelection = () => {
		this.table.selectedRowsIds = '';
	}

	@action
	getTable = () => {
		const {
			nodeType
		} = this.leftTree, {
			isEdit,
			isHistoryTable
		} = this.table;

		if (isEdit) {
			this.getEditableDeptPayrollTable();
		} else {
			(nodeType == '0' || isHistoryTable) ? this.getAllSubPayrollInfoTable(): this.getDeptPayrollInfoTable();
		}
	}

	@action
	editDeptPayrollInfoTable = (bool) => {
		this.table.isEdit = bool;
		this.recoverLoading();
		this.resetSelectedRows();
		this.getTable(); //先加载表格数据，后获取功能按钮
		this.getSearchItems(); //只为了获取日期，需要执行一次接口，是不是很蠢
	}

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

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

	@action
	resetSearch = () => {
		this.searchPanel.form = new WeaForm();
		this.searchPanel.baseSearchValue = '';
	}

	@action
	closeSearchPanel = () => {
		this.isPanelShow = false;
	}

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

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

	@action
	setTableEditDatas = (dates) => {
		this.table.callbackInfo = dates;
		this.table.datas = dates;
	}

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

	@action
	closeAuth = () => {
		this.authorized = false;
	}

	@action
	setDeptPayrollTableSelectedRows = (selectedRowIndexs) => {
		this.table.selectedRowIndexs = selectedRowIndexs;
		this.getSelectedStaffsId();
	}

	@action
	resetSelectedRows = () => {
		this.table.selectedRowIndexs = [];
	}

	@action
	getSelectedStaffsId = () => {
		const {
			selectedRowIndexs
		} = this.table;

		this.table.selectedRowsIds = selectedRowIndexs.join(",");
	}

	@action
	resetObserableDatas = () => {
		this.closeAuth();
		this.closeSearchPanel();
		this.resetSearch();
		this.setCurrentPage(1);
		this.setPageSize(10)
	}

}