import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaBrowser,
	WeaSearchGroup,
	WeaFormItem
} from 'ecCom';
import {
	WeaForm,
	WeaTableNew,
	WeaSwitch
} from 'comsMobx';
import {
	Button,
	message,
	Tooltip
} from 'antd';
import FormInfo from '../coms/FormInfo';
import HrmBaseStore from './baseStore';
import * as api from '../apis/workingDayAdjust';
import {
	i18n
} from '../public/i18n';
import {
	findIndex,
	has
} from 'lodash';
import {
	convertCalendarDate
} from '../util/index';

const {
	TableStore
} = WeaTableNew;

export class HrmWorkingDayAdjust extends HrmBaseStore {
	/********************* unobservable list *********************/
	topBtnAndMenu = () => {
		let btns = [
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5ollsh`} type='primary' op="create" onClick={() => this.create()}>{i18n.button.create()}</Button>
		]
		this.displayType != 'calendar' && btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bck875`} type='primary' op="remove" disabled={this.multiRemoveable} onClick={() => this.remove()}>{i18n.button.multiDelete()}</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.copy(),
			icon: <i className={this.menuIconCollection.copy}/>,
			onClick: this.copy
		});
		return {
			btns,
			menus: [...menus, ...this.getBasicMenus('HRM_ENGINE_PUBLIC')]
		}
	}

	editorDialogRightMenu = [];
	getDialogOpButtons = () => {
		let buttons = [];
		this.editorDialogRightMenu.length = 0;
		switch (this.dialogParams.opType) {
			case 'create':
				!this.hasSet && buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@wzjozh`} type="primary" op="save" onClick={() => this.saveForm()}>{i18n.button.save()}</Button>);
				break;
			case 'modify':
				buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@9eistl`} type="primary" op="create" onClick={() => this.saveForm()}>{i18n.button.save()}</Button>);
				buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@slakfa`} type="primary" op="remove" onClick={() => this.removeForm()}>{i18n.button.delete()}</Button>);
				break;
			case 'copy':
				buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@b5i2n4`} type="primary" op="save" onClick={() => this.doCopy()}>{i18n.button.save()}</Button>);
				break;
		}

		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;
	}

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

	selectedSubCompany;
	calendarData = [];
	countryInfo;
	hasSet = false;

	itemRender = {
		relateweekday: (field, textAreaProps, form, formParams) => {
			if (formParams.changetype === '2')
				return (<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@5v3738`} fieldConfig={{...field, ...textAreaProps}} 
						form={form} formParams={formParams}/>)
			return null;
		}
	}
	/********************* unobservable list *********************/

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

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

	/********************* observable list *********************/
	@observable refreshCondition = new Date();
	@observable displayType = 'calendar';
	@observable currDate = new Date();
	@observable calendarData = [];
	@observable table = new TableStore();
	@observable holidayname = '';
	@observable spinning = false;
	@observable refreshDialog = new Date().getTime();
	@observable showAttendanceType = true;

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

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

	/********************* action list *********************/
	initData = () => {
		this.showAttendanceType = true;
		this.currDate = new Date();
		this.holidayname = '';
		this.selectedSubCompany = null;
		this.displayType = 'calendar';
		this.containerInitFinished = {
			...this.containerInitFinished,
			init: true
		}
		this.getCondition();
	}

	getCondition = (params) => {
		api.getCondition(params).then(data => {
			if (data.status === '1') {
				data.condition.map(f => {
					f.items.map(item => {
						if (item.domkey[0] === 'countryid') {
							this.countryInfo = item.browserConditionParam.replaceDatas;
						}
					})
				})
				this.setFormData('conditionForm', data.condition);
				this.refreshCondition = new Date();
				this.loadData();
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	generateParams = () => {
		const formParams = this.formTarget.conditionForm.getFormParams();
		let attendancetype;
		if (formParams.attendancetype == null)
			attendancetype = '';
		else if (formParams.attendancetype === '0')
			attendancetype = '';
		else
			attendancetype = formParams.attendancetype;
		const momentDate = this.moment(this.currDate);
		const ymd = momentDate.format('YYYY-MM-DD');
		const y = momentDate.year();
		const params = {
			year: y,
			countryid: formParams.countryid || 1,
			currentdate: ymd,
			attendancetype
		}
		return params;
	}

	generateFormParams = (obj) => {
		const formParams = this.formTarget.conditionForm.getFormParams();
		const params = {
			...obj
		}
		let countryid = '';
		if (obj.countryid != null)
			countryid = obj.countryid;
		else
			countryid = formParams.countryid;

		if (countryid == null || countryid === '')
			countryid = 1;

		Object.assign(params, {
			countryid
		})
		return params;
	}

	@action loadData = () => {
		this.displayType === 'calendar' ? this.getCalendar() : this.getDataList();
	}

	@action setHolidayName = (name) => this.holidayname = name;

	@action getCalendar = (params) => {
		if(this.spinning)
			return;
		this.spinning = true;
		this.calendarData.length = 0;
		api.getCalendar(this.generateParams()).then(data => {
			if (data.status === '1') {
				this.calendarData = data.calendar;
			} else {
				message.error(data.message);
			}
			this.spinning = false;
		}, error => {this.spinning = false;})
	}

	@action getDataList = (params) => {
		if(this.spinning)
			return;
		this.spinning = true;
		api.getDataList({ ...this.generateParams(),
			holidayname: this.holidayname
		}).then(data => {
			this.table = new TableStore();
			if (data.status === '1') {
				this.table.getDatas(data.sessionkey, 1);
			} else {
				message.error(data.message);
			}
			this.spinning = false;
		}, error => {this.spinning = false;})
	}

	getFormInfo = (params) => {
		api.getForm(params).then(data => {
			if (data.status === '1') {
				this.hasSet = false;
				if (this.opId == null && has(data, 'hasSetMsg')) {
					this.hasSet = true;
					message.error(data.hasSetMsg);
					data.formField[0].items = data.formField[0].items.splice(0, 2);
					data.formField[0].items.map(item => {
						item.viewAttr = 3;
						if (item.domkey[0] === 'holidaydate') {
							item.onChange = this.onFormDateChange;
						}
					})
					this.setFormData('hForm', data.formField);
					this.showDialog();
					return;
				}
				data.formField.map(f => {
					f.items.map(item => {
						if (item.domkey[0] === 'holidaydate') {
							item.onChange = this.onFormDateChange;
						}
					})
				})
				this.setFormData('hForm', data.formField);
				this.displayType === 'calendar' && params.holidaydate != null && this.formTarget.hForm.updateFields({
					holidaydate: {
						value: params.holidaydate
					}
				})
				this.showDialog();
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	showDialog = () => {
		if (this.formTarget.hForm.isFormInit) {
			const {
				hForm: form,
				hFormFields: fields
			} = this.formTarget;
			this.dialogParams.title = this.opId != null ? i18n.label.editWorkingDay() : i18n.label.createWorkingDay();
			this.dialogParams.opType = this.opId != null ? 'modify' : 'create';
			this.dialogParams.coms = <FormInfo ecId={`${this && this.props && this.props.ecId || ''}_FormInfo@rdazkr`} center={false} form={form} formFields={fields} menu={this.editorDialogRightMenu} itemRender={this.itemRender}/>;
			this.dialogParams.style = {
				width: 520,
				height: 250
			}
			this.dialogParams.visible = true;
			this.refreshDialog = new Date().getTime();
		}
	}

	onFormDateChange = (val) => {
		this.formTarget.hForm.updateFields({
			holidaydate: {
				value: val
			}
		})
		this.getFormInfo(this.generateFormParams({
			holidaydate: val,
			countryid: this.formTarget.hForm.getFormParams().countryid
		}));
	}

	@action onCountryChange = (obj) => {
		if (obj.countryid.value === '') {
			this.formTarget.conditionForm.updateFields({
				countryid: {
					value: obj.countryid.value
				}
			})
			return;
		}
		this.getCondition(this.generateParams());
	}

	@action onOptionChange = (key) => {
		if (key == 0) {
			key = '';
		}
		this.formTarget.conditionForm.updateFields({
			attendancetype: {
				value: key
			}
		})
		this.loadData();
	}

	@action changeView = (type) => {
		this.displayType = type;
		if(type === 'calendar')
			this.showAttendanceType = true;
		else
			this.showAttendanceType = false;
		this.loadData();
	}

	@action onDateChange = (date) => {
		this.currDate = date;
		this.getCondition(this.generateParams());
	}

	yearDateCellRender = (date) => {
		const ymd = convertCalendarDate(date);
		const d = date.getDayOfMonth();
		const weekday = this.moment(ymd, 'YYYY-MM-DD').day();
		const datas = this.toJS(this.calendarData);
		const index = findIndex(datas, {
			date: ymd
		});
		if(index < 0)
			return (
				<div style={{color: ((weekday === 0 || weekday === 6) ? '#999' : '#000')}}>{d}</div>
			)
		const data = datas[index];
		let color = data.bgColor;
		if(data.otherParam.type === '')
			return (
				<div style={{color: ((weekday === 0 || weekday === 6) ? '#999' : '#000')}} title=''>{d}</div>
			)
		const title = <div><div>{i18n.label.date()}: {data.otherParam.date}</div><div>{i18n.label.illustration()}: {data.otherParam.info}</div><div>{i18n.label.type()}: {data.otherParam.type}</div></div>
		return (
			<Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@4hfl5u`} title={title} placement="right">
				<div style={{background: color}} title=''>{d}</div>
			</Tooltip>
		)
	}

	onDateSelect = (date) => {
		const ymd = convertCalendarDate(date);
		const datas = this.toJS(this.calendarData);
		const dataIndex = findIndex(datas, {
			date: ymd
		});
		const record = dataIndex < 0 ? null : datas[dataIndex];
		let params = {
			holidaydate: ymd,
		};
		if (record != null && has(record, 'id')) {
			this.opId = record.id;
			params.id = record.id;
		} else {}
		this.getFormInfo(this.generateFormParams(params));
	}

	@action create = (params) => {
		if (params != null) {
			this.opId = params.id;
		} else {
			params = {};
		}

		const formParams = this.formTarget.conditionForm.getFormParams();
		Object.assign(params, {
			countryid: formParams.countryid || 1
		})
		this.getFormInfo(params);
	}

	@action saveForm = (params) => {
		if (this.spinning)
			return;
		this.formTarget.hForm.validateForm().then(f => {
			if (f.isValid) {
				const formParams = this.formTarget.hForm.getFormParams();
				const params = {
					...formParams,
					id: this.opId
				}
				this.spinning = true;
				api.saveForm(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.saveSuccess());
						this.dialogParams.onCancel();
						this.getCondition(this.generateParams());
					} else {
						message.error(data.message);
					}
					this.spinning = false;
				}, error => {
					this.spinning = false;
				})
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		})
	}

	@action removeForm = () => {
		this.confirmInfo({
			content: i18n.confirm.delete(),
			onOk: () => {
				api.remove({
					id: this.opId
				}).then(data => {
					if (data.status === '1') {
						this.dialogParams.onCancel();
						message.success(i18n.message.deleteSuccess());
						this.getCondition(this.generateParams());
					}
				})
			}
		});
	}

	@action copy = () => {
		const formParams = this.formTarget.conditionForm.getFormParams();
		api.getCopyForm({countryid: formParams.countryid}).then(data => {
			if (data.status === '1') {
				data.formField.map(f => {
					f.items.map(item => {
						if (item.domkey[0] === 'year') {
							item.min = [1980, 9999];
							item.max = [1980, 9999];
							item.rules = 'scopeRequired|scopeDirty';
						}
					})
				})
				this.setFormData('copyForm', data.formField);
				if (this.formTarget.copyForm.isFormInit) {
					const {
						copyForm: form,
						copyFormFields: fields
					} = this.formTarget;

					this.dialogParams.style = {
						width: 440,
						height: 145
					}
					this.dialogParams.title = i18n.button.copy();
					this.dialogParams.opType = 'copy';
					this.dialogParams.coms = <FormInfo ecId={`${this && this.props && this.props.ecId || ''}_FormInfo@d8hm00`} center={false} form={form} formFields={fields} menu={this.editorDialogRightMenu} />;
					this.dialogParams.visible = true;
				}
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	@action remove = (params) => {
		let content;
		if (params == null) {
			params = {
				id: this.table.selectedRowKeys
			}
			content = i18n.confirm.deleteSelected();
		} else {
			content = i18n.confirm.delete();
		}
		this.confirmInfo({
			content,
			onOk: () => {
				api.remove(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.deleteSuccess());
						this.getCondition(this.generateParams());
					}
				})
			}
		});
	}

	doCopy = () => {
		if (this.spinning)
			return;
		this.formTarget.copyForm.validateForm().then(f => {
			if (f.isValid) {
				const formParams = this.formTarget.copyForm.getFormParams();
				const params = {
					countryid: formParams.countryid,
					fromyear: formParams.year,
					toyear: formParams.yearto
				}
				this.spinning = true;
				api.saveCopyForm(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.opSuccess());
						this.dialogParams.onCancel();
						this.getCondition(this.generateParams());
					} else {
						message.error(data.message);
					}
					this.spinning = false;
				}, error => {
					this.spinning = false;
				})
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		})
	}
	/********************* action list *********************/
}

export const hrmWorkingDayAdjust = new HrmWorkingDayAdjust();