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

export class HrmFuncManageDecent {
	@observable canAdd = false;
  	@observable canCreate = false;
	@observable canDel = false;
	@observable detachable = false;

	@observable main = {
		btnMenu: [],
		authorized: false,
		loading: true,
		title: i18n.module.funcManageDecent(),
	}
	@observable formInfo = {
		fconditions: [],
		sconditions: [],
		form: new WeaForm(),
		loading: true,
		selectedValue: '',
		date: '',
	}
	@observable mainTable = {
		tableStore: new TableStore(),
		selectedRowKeys: '',
	}
	@observable mainDialog = {
		title: '',
		visible: false,
	}
	@observable mainTab = {
		isPanelShow: false,
		form: new WeaForm(),
		conditions: [],
		loading: true,
		conditionCount: observable.ref(2),
		baseSearchValue: '',
	}

	@computed get menu() {
		let topMenu = this.main.btnMenu.filter(item => item.isTop == '1' || item.isBatch == '1');
		topMenu = topMenu.filter(item => (item.menuFun == 'new' && this.canCreate) || (item.menuFun == 'batchDelete' && this.canDel));
		let rightMenu = this.main.btnMenu.filter(item => (item.menuFun == 'new' && this.canCreate) || (item.menuFun == 'batchDelete' && this.canDel) || item.isTop == '0');

		return {
			topMenu,
			rightMenu
		}
	}

	@action
	getAuth = async () => {
		this.hrmDeptId = null;
		this.hrmSubComId = null;
		this.loading = true;
		const data = await commonApi.detachable();
		const {status: s, detachable} = data;
		this.detachable = s == '1' && detachable == '1';

		const rs = await Api.getAuth();
		const {status, hasRight, message} = rs;
		if(status == '1'){
			if(hasRight){
				hasRight && this.grantAuth();
				this.main.loading = false;
			}
			this.loading = false;
			this.main.loading = false;
		}else{
			message.error(message);
		}
	}

	@action
	getButtonsMenu = () => {
		Api.getButtonsMenu().then(cb => {
			const {
				api_status,
				btnMenu,
			} = cb;

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

	
	@action
	getTableInfo = () => {
		const params = {
			...this.mainTab.form.getFormParams(),
			name: this.mainTab.baseSearchValue
		}
		this.hrmSubComId != null && Object.assign(params, {subCompanyId: this.hrmSubComId});
		Api.getTableInfo(params).then(cb => {
			const {
				api_status,
				sessionkey,
			} = cb;

			if (api_status) {
				this.canCreate = cb.canAdd || false;
				this.canDel = cb.canDel || false;
				sessionkey && this.mainTable.tableStore.getDatas(sessionkey, 1);
			} else {
				message.error(cb.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	roleField;
	resourceField;

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

		if (!this.mainDialog.visible) {
			func = 'getSearchItems';
			params = {};
		} else {
			func = 'getForm';
			params = {};
			if (this.mainTable.selectedRowKeys) {
				Object.assign(params, {
					id: this.mainTable.selectedRowKeys
				});
			}
		}
		this.hrmSubComId != null && Object.assign(params, {subCompanyId: this.hrmSubComId});
		Api[func](params).then(cb => {
			const {
				api_status,
				conditions,
			} = cb;

			if (api_status) {
				if (!this.mainDialog.visible) {
					this.mainTab.conditions = conditions;
					this.mainTab.form.initFormFields(conditions);
					this.mainTab.loading = false;
				} else {
					this.splitConditions(conditions);

					const _conditions = [{
						defaultshow:true,
						items:[],
						title:i18n.label.maintainerSet()
					},{
						defaultshow:true,
						items:[],
						title:i18n.label.decentSet()
					}];
					conditions.map(c => {
						c.items.map( (item, index) => {
							const [ key ] = item.domkey;

							if (index < 3) {
								_conditions[0].items.push(item);
							}else{
								_conditions[1].items.push(item);
							}
							
							if (key == "roleId") {
								this.roleField = item;
							}
							if (key == "resourceId") {
								this.resourceField = item;
							}

						})
					})
					this.formInfo.form.setCondition(toJS(_conditions));
					this.formInfo.loading = false;
				}
				if(func == 'getForm') this.canAdd = cb.canAdd || false;
			} else {
				message.error(cb.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	splitConditions = (conditions) => {
		let fitems = [],
			sitems = [];

		conditions.map(c => {
			c.items.map((item, index) => {
				if (index < 3) {
					if (item.domkey[0] == 'permissionType') {
						this.exportSelectedValue(item.value);
					}
					fitems.push(item)
				} else {
					sitems.push(item)
				}
			});
		});

		this.formInfo.fconditions = [{
			items: fitems
		}];
		this.formInfo.sconditions = [{
			items: sitems
		}];
	}

	@action
	deleteTableInfo = () => {
		const params = {
			ids: this.mainTable.selectedRowKeys
		}
		Api.deleteTableInfo(params).then(cb => {
			const {
				api_status,
				sign
			} = cb;

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

	@action
	save = () => {
		this.ignoreVerify();

		this.formInfo.form.validateForm().then(f => {
			if (f.isValid) {
				let params = this.formInfo.form.getFormParams();
				this.hrmSubComId != null && Object.assign(params, {subCompanyId: this.hrmSubComId});
				if (this.mainTable.selectedRowKeys) {
					Object.assign(params, {
						id: this.mainTable.selectedRowKeys
					});
				} else {}

				Api.save(params).then(cb => {
					const {
						api_status,
						sign
					} = cb;

					if (api_status) {
						if (sign == '1') {
							message.success(cb.message);
							this.closeDialog();
							this.getTableInfo();
						} else {
							message.warning(cb.message)
						}
						this.formInfo.loading = false;
					}
				}).catch(error => {
					message.error(error);
				});
			} else {
				f.showErrors();
				this.setDate({
					date: new Date()
				});
			}
		});
	}

	@action
	ignoreVerify = () => {
		const { permissionType } = this.formInfo.form.getFormParams();

		window.e9HideFormFieldKeys = []; //清空容器

		if (permissionType == '2') window.e9HideFormFieldKeys = ['resourceId'];
		if (permissionType == '5') window.e9HideFormFieldKeys = ['roleId'];
	}

	@action
	openDialog = () => {
		this.mainDialog.visible = true;
		this.mainDialog.title = (!this.mainTable.selectedRowKeys) ? i18n.label.newFuncManageDecent() : i18n.label.editFuncManageDecent();
	}

	@action
	closeDialog = () => {
		this.mainDialog.visible = false;
		this.resetSelectedRowKeys();
	}

	@action
	resetSelectedRowKeys = () => {
		this.mainTable.selectedRowKeys = '';
	}

	@action
	changeSearchPanelStatus = (bool) => {
		this.mainTab.isPanelShow = bool;
	}

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

	@action
	refreshPage = () => {
		this.mainTab.isPanelShow = false;
		this.mainTab.form.reset();
		this.getTableInfo();
	}

	@action
	resetSearch = (type) => {
		this.mainTab.isPanelShow = false;
		this.mainTab.form = new WeaForm();
	}

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

	@action
	setSelectedRowKeys = (keys) => {
		this.mainTable.selectedRowKeys = keys;
	}

	@action
	setSearchBaseValue = (val) => {
		this.mainTab.baseSearchValue = val;
	}

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

	@action
	exportSelectedValue = (val) => {
		this.formInfo.selectedValue = val;
	}

	orgTreeProps = {
		needSearch: true,
		isLoadAllSub: true,
		topPrefix: "hrmSearch",
		inputLeftDom: `<b>${i18n.label.organization()}</b>`,
		// needDropMenu: true,
		treeNodeClick: this.treeNodeClick,
		params: {
			rightStr: "HrmEffectManageEmpower:Edit"
		},
	};

	@action treeNodeClick = (event, ids, nodeids, nodes) => {
		this.hrmDeptId = null;
		this.hrmSubComId = null;
		const { data } = event.node.props;
		const {type, id} = data;
		if(type == 1 || type == 0)
			this.hrmSubComId = id;
		else if(type == 2)
			this.hrmDeptId = id;
		this.getTableInfo();
	};
}