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/annual';
import {
	exportExcel
} from '../apis/common';
import {
	i18n
} from '../public/i18n';
import {
	has
} from 'lodash';

const {
	TableStore
} = WeaTableNew;

export class HrmAnnualSetting extends HrmBaseStore {
	/********************* unobservable list *********************/
	topBtnAndMenu = () => {
		let btns = [
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@c1qdet`} type='primary' op='save' onClick={() => this.save()}>{i18n.button.save()}</Button>
		]
		if (window.WeaHrm4Formal)
			btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@tmotwv`} type='primary' op='modify' onClick={() => this.setAddedDays()}>{i18n.button.setAddedDays()}</Button>);
		else
			btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fk2rnv`} 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@41ocnx`} type='primary' op='import' onClick={() => this.import()}>{i18n.button.import()}</Button>);
			btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@s3gn83`} 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_ANNUAL_MANAGER')]
		}
	}

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

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

	getRadioGroupConfig = () => [{
		label: i18n.label.annualYear(),
		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;
	PSLyear;
	canExport = true;
	renderKeys = ['annualdays', 'addeddays', 'basedays', 'leavedays'];

	editorDialogRightMenu = [];
	getDialogOpButtons = () => {
		let buttons = [];
		this.editorDialogRightMenu.length = 0;
		buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fuwatw`} 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.tabConfig.tabs.length = 0;
		this.selectedSubCompany = null;

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

	@action treeNodeClick = (event, ids, nodeids, nodes) => {
		const {
			data: nodeData
		} = event.node.props;
		this.selectedSubCompany = nodeData;
		this.dirtyDatas.clear();
		this.getTableData();
	}

	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.annualyear = year;
		year != null && this.getTableData();
	}

	getTableData = () => {
		api.getAnnualManagerList(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;
				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;
	}

	onAnnualDayBlur = (id, val) => {
		if (this.dirtyDatas.get(id) == null)
			this.dirtyDatas.set(id, val);
		else
			this.dirtyDatas.set(id, Object.assign(this.dirtyDatas.get(id), val));
	}

	generateParams = () => {
		const params = {
			annualyear: this.annualyear,
			formal: window.WeaHrm4Formal
		}
		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.psubcompanyid,
					departmentid: this.selectedSubCompany.id
				})
			}
		}
		return params;
	}

	@action save = () => {
		this.valid = true;
		let obj = {};
		this.renderKeys.map(k => {
			obj[k] = [];
		});
		obj.resourceid = [];
		[...this.dirtyDatas.values()].map(data => {
			const keys = [...Object.keys(data)];
			keys.map(k => {
				const v = data[k];
				if (v == null || v.length == 0 || !/^[0-9]+([.]{1}[0-9]+){0,1}$/.test(v)) {
					this.valid = false;
					message.error(i18n.message[k]());
				}
			})
		});
		if (this.valid) {
			this.spinning = true;
			this.table.datas.map(data => {
				obj.resourceid.push(data.id);
				const dirtyData = this.dirtyDatas.get(data.id);
				this.renderKeys.map(k => {
					if (dirtyData == null) {
						obj[k].push(data[k])
					} else {
						has(dirtyData, k) ? obj[k].push(dirtyData[k]) : obj[k].push(data[k])
					}
				})
			});
			const params = {
				...this.generateParams()
			};
			[...Object.keys(obj)].map(k => {
				Object.assign(params, {
					[k]: obj[k]
				})
			});
			api.saveAnnualManager(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.processAnnualManager(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 setAddedDays = () => {
		if (this.spinning)
			return;
		if (this.table.datas.length == 0) {
			return;
		} else {
			this.confirmInfo({
				content: i18n.confirm.setAddedDays(),
				onOk: () => {
					this.spinning = true;
					api.addeddayssetting(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];
			} 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 hrmAnnualSetting = new HrmAnnualSetting();