import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaTableNew
} from 'comsMobx';
import {
	Button,
	message
} from 'antd';
import FormInfo from '../coms/FormInfo';
import HrmBaseStore from './baseStore';
import * as api from '../apis/paidLeaveManager';
import {
	i18n
} from '../public/i18n';

const {
	TableStore
} = WeaTableNew;

export class HrmPaidLeavePeriod extends HrmBaseStore {
	/********************* unobservable list *********************/
	topBtnAndMenu = () => {
		let btns = [
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@xg8jws`} type='primary' op='create' onClick={() => this.create()}>{i18n.button.create()}</Button>,
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@aeqgnm`} type='primary' op='remove' disabled={this.tableDataOperational} onClick={() => this.remove()}>{i18n.button.multiDelete()}</Button>,
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@i0zxaf`} type='primary' op='sync' onClick={() => this.sync()}>{i18n.button.syncToSubDept()}</Button>,
		]
		let menus = [];
		btns.map((btn, index) => {
			const {
				props
			} = btn;
			menus.push({
				key: index.toString(),
				content: props.children,
				icon: <i className={this.menuIconCollection[props.op]}/>,
				onClick: props.onClick,
				disabled: props.disabled || false
			});
		})
		menus.push({
			key: '11',
			content: i18n.button.columnVisibleSetting(),
			icon: <i className={this.menuIconCollection.setting}/>,
			onClick: () => this.definedColumn(this.table)
		})
		return {
			btns,
			menus: [...menus, ...this.getBasicMenus('HRM_ENGINE_HRM_PLS_MANAGER_SET')]
		}
	}

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

	tabConfig = {
		tabs: [],
		keyParam: 'viewCondition',
		activeTabKey: '1'
	}

	selectedSubCompany;

	editorDialogRightMenu = [];
	getDialogOpButtons = () => {
		let buttons = [];
		this.editorDialogRightMenu.length = 0;
		buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@b18iye`} type="primary" op="save" onClick={() => this.save()}>{i18n.button.save()}</Button>);
		buttons.map((btn, index) => {
			const {
				props
			} = btn;
			this.editorDialogRightMenu.push({
				key: index.toString(),
				content: props.children,
				icon: <i className={this.menuIconCollection[props.op]}/>,
				onClick: props.onClick
			});
		})

		this.dialogParams.moreBtn.datas = this.editorDialogRightMenu;
		return buttons;
	}
	/********************* unobservable list *********************/

	/********************* dialog info setting *********************/

	/********************* dialog info setting *********************/

	/********************* observable list *********************/
	@observable refreshTab = new Date().getTime();
	@observable table = new TableStore();

	dialogParams = {
		...this.dialogPropsDef,
		opType: '',
		style: {
			width: 500,
			height: 165
		},
		onCancel: () => {
			this.dialogParams.visible = false;
			this.opId = null;
		}
	}
	/********************* observable list *********************/

	/********************* computed list *********************/
	@computed get tableDataOperational() {
		return this.table.selectedRowKeys.length === 0;
	}
	/********************* computed list *********************/

	/********************* action list *********************/
	initData = () => {
		this.tabConfig.tabs.length = 0;
		this.selectedSubCompany = null;

		this.containerInitFinished = {
			...this.containerInitFinished,
			init: true
		}

		api.getCondition({
			type: 'PLSPeriod'
		}).then(data => {
			if (data.status === '1') {
				this.tabConfig.tabs.length = 0;
				this.setFormData('conditionForm', data.formField);
				data.formField.map(field => {
					field.items.map(item => {
						item.options.map((option, i) => {
							this.tabConfig.tabs.push({
								color: '#000000',
								groupId: option.key,
								title: option.showname,
								viewCondition: (i + 1).toString()
							})
						})
					})
				})
				this.setActiveTab('1');
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	@action treeNodeClick = (event, ids, nodeids, nodes) => {
		this.formTarget.conditionForm.resetForm();
		const {
			data: nodeData
		} = event.node.props;
		this.selectedSubCompany = nodeData;
		this.setActiveTab('1');
	}

	@action setActiveTab = (key) => {
		this.tabConfig.activeTabKey = key || this.tabConfig.tabs[0].viewCondition;
		const tabIndex = this.getTabIndex(this.tabConfig.tabs, key);
		if (tabIndex < 0) return;
		this.formTarget.conditionForm.updateFields({
			leavetype: {
				value: this.tabConfig.tabs[tabIndex].groupId
			}
		})
		this.refreshTab = new Date().getTime();
		this.getTableData();
	}

	getTableData = () => {
		const params = {
			...this.formTarget.conditionForm.getFormParams()
		}
		this.selectedSubCompany && Object.assign(params, {
			subcompanyid: this.selectedSubCompany.id
		});
		api.getPLSManagerSetList(params).then(data => {
			if (data.status === '1') {
				this.table = new TableStore();
				this.table.getDatas(data.sessionkey, 1);
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	getDataForm = (params, showDialog = false, create) => {
		create && Object.assign(params, {
			...this.formTarget.conditionForm.getFormParams(),
			subcompanyid: this.selectedSubCompany ? this.selectedSubCompany.id : '0',
		})
		api.getPLSManagerSetForm(params).then(data => {
			if (data.status === '1') {
				data.formField.map(f => {
					f.items.map((item, i) => {
						if (i == 0) {
							item.length = 4;
						}
					})
				})
				this.setFormData('dataForm', data.formField);
				showDialog && this.showDialog(create);
			} else {
				message.error(data.message);
			}
		})
	}

	@action create = (create = true, params = {}) => {
		if (!create) {
			this.opId = params.id;
		}
		this.getDataForm(params, true, create);
	}

	showDialog = (create) => {
		if (this.formTarget.dataForm.isFormInit) {
			this.dialogParams.coms = (
				<FormInfo ecId={`${this && this.props && this.props.ecId || ''}_FormInfo@3vcwvd`} center={false} menu={this.editorDialogRightMenu} 
					form={this.formTarget.dataForm} 
					formFields={this.formTarget.dataFormFields}/>
			)
			this.dialogParams.title = (create ? i18n.label.createPaidLeavePeriod() : i18n.label.editPaidLeavePeriod());
			this.dialogParams.visible = true;
		}
	}

	@action save = () => {
		this.formTarget.dataForm.validateForm().then(f => {
			if (f.isValid) {
				this.valid = true;
				const formParams = this.formTarget.dataForm.getFormParams();
				if (!/^\d+$/.test(formParams.PSLyear)) {
					this.valid = false;
					f.showError('PSLyear', i18n.message.mustIntVal());
				} else if (this.moment(formParams.startdate) > this.moment(formParams.enddate)) {
					this.valid = false;
					f.showError('enddate', i18n.message.expiryLessThanEffective());
				}
				if (this.valid) {
					const params = {
						id: this.opId != null ? this.opId : null,
						subcompanyid: this.selectedSubCompany ? this.selectedSubCompany.id : null,
						...formParams,
						...this.formTarget.conditionForm.getFormParams()
					}
					this.dialogParams.onCancel();
					api.savePLSManagerSet(params).then(data => {
						if (data.status === '1') {
							this.table.getDatas(null, 1);
							message.success(i18n.message.saveSuccess());
						} else
							message.error(data.message);
					}, error => {});
				}
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		});
	}

	@action remove = (params) => {
		let content;
		if (params == null) {
			params = {
				ids: this.table.selectedRowKeys
			}
			content = i18n.confirm.deleteSelected();
		} else {
			content = i18n.confirm.delete();
		}
		Object.assign(params, {
			subcompanyid: this.selectedSubCompany ? this.selectedSubCompany.id : null,
			...this.formTarget.conditionForm.getFormParams()
		})
		this.confirmInfo({
			content,
			onOk: () => {
				api.deletePLSManagerSet(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.deleteSuccess());
						this.table.getDatas(null, 1);
					}
				})
			}
		});
	}

	@action sync = () => {
		if (this.table.selectedRowKeys.length == 0) {
			message.error(i18n.message.syncDataNone());
			return;
		}
		this.confirmInfo({
			content: i18n.confirm.syncPaidLeavePeriod(),
			onOk: () => {
				const params = {
					ids: this.table.selectedRowKeys,
					subcompanyid: this.selectedSubCompany ? this.selectedSubCompany.id : null,
					...this.formTarget.conditionForm.getFormParams()
				}
				api.synPLSManagerSet(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.syncSuccess());
						this.getTableData();
					}
				})
			}
		});
	}
	/********************* action list *********************/
}

export const hrmPaidLeavePeriod = new HrmPaidLeavePeriod();