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

const {
	TableStore
} = WeaTableNew;

export class HrmPaidLeaveSetting extends HrmBaseStore {
	/********************* unobservable list *********************/
	topBtnAndMenu = () => {
		let btns = [
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@cpera6`} type='primary' op='save' onClick={() => this.save()}>{i18n.button.save()}</Button>,
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6c0f73`} type='primary' op='modify' onClick={() => this.multiOp()}>{i18n.button.multiOp()}</Button>

		]
		if (this.canExport) {
			btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@onxfog`} type='primary' op='import' onClick={() => this.import()}>{i18n.button.import()}</Button>);
			btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lqs3fj`} type='primary' op='export' onClick={() => this.export()}>{i18n.button.export()}</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')]
		}
	}

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

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

	getRadioGroupConfig = () => [{
		label: i18n.label.paidLeaveYear(),
		domkey: [
			'type'
		],
		options: [{
			key: '5',
			showname: i18n.label.tsyr(),
			selected: true
		}, {
			key: '8',
			showname: i18n.label.preYear()
		}, {
			key: '6',
			showname: i18n.label.setYear()
		}],
		selectLinkageDatas: {
			6: {
				conditionType: 'DATEPICKER',
				format: 'YYYY',
				domkey: ['PSLyear'],
				value: this.moment().year().toString()
			}
		},
		labelcol: 4,
		fieldcol: 20,
		date: new Date().getTime()
	}]

	setImportStore = (hrmImportResource) => {
		this.hrmImportResource = hrmImportResource;
	}

	selectedSubCompany;
	hrmImportResource;
	dirtyDatas = new Map();
	valid = true;
	canExport = true;

	editorDialogRightMenu = [];
	getDialogOpButtons = () => {
		let buttons = [];
		this.editorDialogRightMenu.length = 0;
		buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ttlywi`} type="primary" op="import" onClick={() => this.submit()}>{i18n.button.submit()}</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 refreshTopBtn = new Date().getTime();
	@observable table = new TableStore();
	@observable message = [];
	@observable spinning = false;

	dialogParams = {
		...this.dialogPropsDef,
		title: i18n.button.import(),
		style: {
			width: 870,
			height: 560
		},
		onCancel: () => {
			this.dialogParams.visible = false;
		}
	}
	/********************* observable list *********************/

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

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

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

		api.getCondition({
			pageId: 'PLSManagerList',
			type: 'PLSLeave'
		}).then(data => {
			if (data.status === '1') {
				this.tabConfig.tabs.length = 0;
				this.setFormData('conditionForm', data.formField);
				data.formField.map(field => {
					field.items.map(item => {
						if (item.domkey[0] === 'leavetype') {
							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');
	}

	onRadioGroupChange = (params) => {
		let year;
		switch (params.type) {
			case '5':
				year = this.moment().year();
				break;
			case '6':
				year = params.PSLyear;
				break;
			case '8':
				year = this.moment().year() - 1;
				break;
		}
		this.formTarget.conditionForm.updateFields({
			PSLyear: {
				value: year
			}
		});
		year != null && this.getTableData();
	}

	@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
			},
			PSLyear: {
				value: this.moment().year()
			}
		})
		this.refreshTab = new Date().getTime();
	}

	getTableData = () => {
		api.getPLSManagerList(this.generateParams()).then(data => {
			if (data.status === '1') {
				this.table = new TableStore();
				this.table.getDatas(data.sessionkey, 1);
				if (this.selectedSubCompany == null) {
					this.selectedSubCompany = {
						type: '1',
						id: data.subcompanyid
					}
				}
				this.canExport = data.export || false;
				this.refreshTopBtn = new Date().getTime();
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	filter = (val) => {
		if (/^[0-9]+([.]{1}[0-9]+){0,1}$/.test(val)) {

		} else {
			val = '';
			message.error('please input number');
		}
		return val;
	}

	onPSLdayBlur = (id, val) => {
		this.dirtyDatas.set(id, val);
	}

	generateParams = () => {
		const params = {
			...this.formTarget.conditionForm.getFormParams()
		}
		if (this.selectedSubCompany != null) {
			if (this.selectedSubCompany.type === '1') {
				Object.assign(params, {
					subcompanyid: this.selectedSubCompany.id
				})
			} else if (this.selectedSubCompany.type === '2') {
				Object.assign(params, {
					subcompanyid: this.selectedSubCompany.pid,
					departmentid: this.selectedSubCompany.id
				})
			}
		}
		return params;
	}

	@action save = () => {
		this.valid = true;
		[...this.dirtyDatas.values()].map(v => {
			if (v == null || v.length == 0 || !/^[0-9]+([.]{1}[0-9]+){0,1}$/.test(v)) {
				this.valid = false;
				message.error(i18n.message.paidLeaveDays());
			}
		})
		if (this.valid) {
			this.spinning = true;
			const params = {
				...this.generateParams(),
				resourceid: [...this.dirtyDatas.keys()].join(','),
				PSLdays: [...this.dirtyDatas.values()].join(',')
			}
			api.savePLSManager(params).then(data => {
				if (data.status === '1') {
					this.table.getDatas(null, 1);
					message.success(i18n.message.saveSuccess());
					this.spinning = false;
				} else
					message.error(data.message);
			}, error => {});
		}
	}

	@action multiOp = () => {
		if (this.spinning)
			return;
		if (this.table.datas.length == 0) {
			return;
		} else {
			this.spinning = true;
			api.processPLSManager(this.generateParams()).then(data => {
				if (data.status === '1') {
					message.success(i18n.message.opSuccess());
					this.table.getDatas(null, '1');
					this.spinning = false;
				} else {
					message.error(data.message);
					this.spinning = false;
				}
			}, error => {
				this.spinning = false;
			})
		}
	}

	@action
	import = () => {
		api.getImportForm(this.generateParams()).then(data => {
			if (data.status === '1') {
				this.message.length = 0;
				this.hrmImportResource.condition = this.convertCondition(data.condition);
				this.hrmImportResource.excelfile = '';
				this.hrmImportResource.filelist.length = 0;
				this.hrmImportResource.single = true;
				this.hrmImportResource.visible = true;
				this.dialogParams.visible = true;
			}
		})
	}

	convertCondition = (condition) => {
		let rs = [];
		condition.map((c, i) => {
			switch (i) {
				case 0:
					let obj = {
						title: c.title,
						defaultshow: c.defaultshow,
						items: []
					}
					c.items.map((item, i) => {
						obj.items.push({
							hasBorder: true,
							colSpan: 2,
							conditionType: 'TEXT',
							domkey: [`group_0_${i}`],
							fieldcol: 12,
							isQuickSearch: false,
							label: item.title,
							labelcol: 6,
							precision: 0,
							value: item.value,
							viewAttr: 1
						})
					});
					rs.push(obj);
					break;
				case 1:
					c.items.map(item => {
						rs[0].items.push(item);
					})
					break;
				case 2:
					rs.push(c);
					break;
			}
		})
		return rs;
	}

	@action submit = () => {
		this.message.length = 0;
		const keyField = this.hrmImportResource.keyField;
		const excelfile = this.hrmImportResource.excelfile || '';
		if (excelfile === '') {
			message.warning(i18n.message.selectImportTemplete());
			return;
		}
		const params = {
			...this.generateParams(),
			excelfile
		}
		api.saveImport(params).then(data => {
			if (data.status === '1') {
				if (has(data, 'errorInfo')) {
					this.message = data.errorInfo;
				} else {
					this.message = [data.message];
				}
				this.getTableData();
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	@action
	export = () => {
		if (this.spinning)
			return;
		this.spinning = true;
		api.exportData(this.generateParams()).then(data => {
			if (data.status === '1') {
				WeaTools.downloadFile('/weaver/weaver.file.ExcelOut', "GET");
			}
			this.spinning = false;
		}, error => {
			this.spinning = false;
		})
	}
	/********************* action list *********************/
}

export const hrmPaidLeaveSetting = new HrmPaidLeaveSetting();