import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaForm,
	WeaTableNew,
	WeaSwitch
} from 'comsMobx';
import {
	WeaNewScroll
} from 'ecCom';
import {
	Button,
	message
} from 'antd';
import SchedulingInfo from '../components/schedule/schedulingSetting/SchedulingInfo';
import ScheduleList from '../components/schedule/schedulingSetting/ScheduleList';
import FormInfo from '../coms/FormInfo';
import HrmBaseStore from './baseStore';
import * as api from '../apis/schedule';
import {
	i18n
} from '../public/i18n';
import {
	has,
	indexOf,
	findIndex,
	cloneDeep,
	remove
} from 'lodash';
import {
	convertCalendarDate
} from '../util/index';
const {
	TableStore
} = WeaTableNew;

class HrmSchedulingSetting extends HrmBaseStore {
	/********************* unobservable list *********************/
	topBtnAndMenu = () => {
		const btns = [
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rb4hyb`} type='primary' onClick={() => this.getFormInfo()}>{i18n.button.createScheduling()}</Button>,
			// <Button type='primary' onClick={() => this.remove()} disabled={this.multiRemoveable}>{i18n.button.multiRemoveScheduling()}</Button>
		];
		let menus = [{
			key: '1',
			content: i18n.button.create(),
			icon: <i className={this.menuIconCollection.create}/>,
			onClick: () => this.getFormInfo()
			// }, {
			// 	key: '2',
			// 	content: i18n.button.multiRemoveScheduling(),
			// 	icon: <i className={this.menuIconCollection.remove}/>,
			// 	onClick: () => this.remove(),
			// 	disabled: this.multiRemoveable
		}];
		if (this.tabConfig.activeTabKey === '1')
			menus.push({
				key: '3',
				content: i18n.button.columnVisibleSetting(),
				icon: <i className={this.menuIconCollection.setting}/>,
				onClick: () => this.definedColumn(this.table)
			})
		return {
			btns,
			menus: [...menus, ...this.getBasicMenus('HRM_ENGINE_HRM_SCHEDULE_SET')]
		}
	}

	tabConfig = {
		tabs: [{
			color: '#000000',
			groupId: 'personScheduling',
			title: i18n.label.personScheduling,
			viewCondition: '1',
			searchType: ['base', 'advanced'],
			searchKey: 'lastname',
			doSearch: (params) => this.getTableData(params)
		}, {
			color: '#000000',
			groupId: 'dateScheduling',
			title: i18n.label.dateScheduling,
			viewCondition: '2'
		}],
		keyParam: 'viewCondition',
		activeTabKey: '1'
	}

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

	editorDialogRightMenu = [];
	getDialogOpButtons = () => {
		let buttons = [];
		this.editorDialogRightMenu.length = 0;
		if (this.dialogParams.opType === 'create')
			buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6qwl79`} type="primary" op="save" onClick={() => this.save()}>{i18n.button.save()}</Button>);
		else if (this.dialogParams.opType === 'detail')
			buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@i77bm4`} type="primary" op="save" onClick={this.clearScheudling}>{i18n.button.clearScheudling()}</Button>);
		else
			buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@byqf7n`} type="primary" op="remove" onClick={this.onCancelScheudling}>{i18n.button.delete()}</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;
	}

	conditionFormRender = {
		createdateselect: () => {
			return null;
		},
		stype: () => {
			return null;
		}
	}

	selectedSubCompany;
	dateSwitch;
	basicFormField;
	startDate;
	endDate;

	radioGroupParams = {};
	/********************* unobservable list *********************/

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

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

	/********************* observable list *********************/
	@observable refreshMainTab = new Date().getTime();
	@observable refreshRadioGroup = new Date().getTime();
	@observable refreshBasicInfo = new Date().getTime();
	@observable table = new TableStore();
	@observable detailTable = new TableStore();
	@observable detailFormFields = {};
	@observable rowDetail = [];
	@observable selectedRow = {};

	@observable calendarType = 'month';
	@observable currentDay = new Date();
	@observable calendarData = [];

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

	/********************* computed list *********************/
	@computed get multiRemoveable() {
		return this.table.selectedRowKeys.length === 0;
	}
	@computed get multiDetailRemoveable() {
		return this.detailTable.selectedRowKeys.length === 0;
	}
	@computed get rightSelectedCount() {
		let cnt = 0;
		this.detailFormFields.rightitem.map(item => {
			item.checked && cnt++;
		})
		return cnt;
	}
	/********************* computed list *********************/

	/********************* action list *********************/
	initData = () => {
		this.selectedSubCompany = null;
		this.containerInitFinished = {
			...this.containerInitFinished,
			init: true
		}

		this.selectedRow = {};
		this.containerInitFinished.userId = 1;
		this.cloneFormField();
		this.setActiveTab('1');
	}

	cloneFormField = () => {
		api.getSchedulingSettingFormInfo().then(data => {
			if (data.status === '1') {
				data.formField.map(f => {
					f.items.map(item => {
						item.viewAttr = 1;
						item.hasBorder = true;
						item.conditionType = 'INPUT';
						delete item.browserConditionParam;
						delete item.value;
					})
				})
				this.basicFormField = data.formField;
			} else {}
		}, error => {})
	}

	initPersonScheduling = () => {
		api.getSchedulingSettingCondition().then(data => {
			if (data.status === '1') {
				this.setFormData('conditionForm', data.formField);
				this.formTarget.conditionForm.isFormInit && this.formTarget.conditionForm.updateFields({
					createdateselect__createdatefrom__createdateto: {
						value: "3"
					}
				}) && this.getTableData();
				this.refreshMainTab = new Date().getTime();
			}
		})
	}

	@action setActiveTab = (key) => {
		this.tabConfig.activeTabKey = key || this.tabConfig.tabs[0].viewCondition;
		const tabIndex = this.getTabIndex(this.tabConfig.tabs, key);
		if (tabIndex < 0) return;
		switch (key) {
			case '1':
				this.initPersonScheduling();
				break;
			case '2':
				this.calendarType = 'month';
				this.currentDay = this.currentDay || new Date();
				this.startDate = this.moment().month(this.currentDay.getMonth()).startOf('month').format('YYYY-MM-DD');
				this.endDate = this.moment().month(this.currentDay.getMonth()).endOf('month').format('YYYY-MM-DD');
				const params = {
					cmd: 'getContent',
					B: indexOf(this.dateSwitchTypeList, this.calendarType) + 1,
					R: false,
					S: this.startDate,
					E: this.endDate,
					M: this.containerInitFinished.userId,
					U: this.containerInitFinished.userId
				}
				this.selectedSubCompany && Object.assign(params, {
					C: this.selectedSubCompany.id
				})
				this.getCalendarData(params);
				break;
			default:
				break;
		}
	}

	@action onRadioGroupChange = (params) => {
		this.radioGroupParams = params;
		this.formTarget.conditionForm.updateFields({
			createdateselect__createdatefrom__createdateto: {
				value: [params.createdateselect, params.createdatefrom, params.createdateto]
			},
			stype: {
				value: params.stype
			}
		});
		this.formTarget.conditionForm.updateFields({
			stype: {
				value: params.stype
			}
		});
		this.selectedRow = {};
		this.getFormInfo(false, {}, this.getTableData);
	}

	@action treeNodeClick = (event, ids, nodeids, nodes) => {
		const {
			data: nodeData
		} = event.node.props;
		this.selectedSubCompany = nodeData;
		this.getTableData({
			...this.formTarget.conditionForm.getFormParams(),
			subcompanyid: nodeData.id
		});
	}

	getTableData = (params) => {
		if (params == null) {
			const formParams = this.formTarget.conditionForm.getFormParams();
			params = { ...formParams
			}
		}
		this.selectedSubCompany != null && Object.assign(params, {
			subcompanyid: this.selectedSubCompany.id
		});
		const {
			field001,
			field002
		} = this.formTarget.schedulingForm.getFormParams();
		params.startDate = field001;
		params.endDate = field002;
		api.getSchedulingSettingList(params).then(data => {
			if (data.status === '1')
				this.table.getDatas(data.sessionkey, 1);
			else
				message.error(data.message);
			this.rowDetail.length = 0;
		}, error => {
			this.rowDetail.length = 0;
		})
	}

	showDetail = (record, index) => {
		this.selectedRow = record;
		// const formParams = this.formTarget.conditionForm.getFormParams();
		// const schedulingFormParams = this.formTarget.schedulingForm.getFormParams();
		api.saveSchedulingSetting({
			cmd: 'getContent',
			id: record.id,
			...this.radioGroupParams
			// stype: formParams.stype,
			// startDate: schedulingFormParams.field001,
			// endDate: schedulingFormParams.field002
		}).then(data => {
			if (data.status === '1') {
				this.rowDetail = data.content;
			}
		})
	}

	showFormDialog = (title) => {
		this.dialogParams.title = title;
		this.dialogParams.coms = <SchedulingInfo ecId={`${this && this.props && this.props.ecId || ''}_SchedulingInfo@2pbtmf`} store={this} />
		this.dialogParams.style = {
			width: 700,
			height: 650
		}
		this.dialogParams.visible = true;
	}

	@action getFormInfo = (showDialog = true, dateRange = {}, callback) => {
		let params = {};
		if (this.tabConfig.activeTabKey === '1') {
			const formParams = this.formTarget.conditionForm.getFormParams();
			params.dateSelect = formParams.createdateselect;
			params.createDate = formParams.createdatefrom;
			params.createDateto = formParams.createdateto;
		} else {
			params.dateSelect = 6;
			params.createDate = dateRange.startDate || this.startDate;
			params.createDateto = dateRange.endDate || this.endDate;
		}

		api.getSchedulingSettingFormInfo(params).then(data => {
			if (data.status === '1') {
				this.opId = data.id;
				this.setFormData('schedulingForm', data.formField);
				this.refreshBasicInfo = new Date().getTime();
				this.formTarget.schedulingForm.isFormInit && showDialog && this.getPersonDetialList();
				this.dialogParams.opType = 'create';
				showDialog && this.showFormDialog(i18n.button.createScheduling());
				callback && callback();
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	@action scheduleSetting = (resourceId) => {
		let params = {};
		const formParams = this.formTarget.conditionForm.getFormParams();
		params.dateSelect = formParams.createdateselect;
		params.createDate = formParams.createdatefrom;
		params.createDateto = formParams.createdateto;

		api.getSchedulingSettingFormInfo(params).then(data => {
			if (data.status === '1') {
				this.opId = data.id;
				this.setFormData('schedulingForm', data.formField);
				this.refreshBasicInfo = new Date().getTime();
				let params = {
					cmd: 'mInsert',
					field001: this.opId,
					field002: resourceId
				}
				api.saveSchedulingSettingPersonDetial(params).then(data => {
					if (data.status === '1') {
						this.getPersonDetialList();
						this.dialogParams.opType = 'create';
						this.showFormDialog(i18n.label.setSchduleDetail());
					} else {
						message.error(data.message);
					}
				}, error => {})
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	@action editFormInfo = (params) => {
		this.dialogParams.opType = 'detail';
		this.opId = params.id;
		this.setFormData('schedulingForm', this.basicFormField);
		this.formTarget.schedulingForm.updateFields({
			field001: {
				value: params.startDate
			},
			field002: {
				value: params.endDate
			},
			field003: {
				value: params.schedule
			},
		});
		this.refreshBasicInfo = new Date().getTime();
		this.formTarget.schedulingForm.isFormInit && this.getFormDetailList(params);
		this.showFormDialog(i18n.label.setSchduleDetail());
	}

	@action getPersonDetialList = () => {
		api.getSchedulingSettingPersonDetialList({
			id: this.opId
		}).then(data => {
			if (data.status === '1') {
				this.detailTable.getDatas(data.sessionkey, 1);
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	@action getFormDetailList = (params) => {
		api.getSchedulingSettingDetialList({
			id: params.id,
			startDate: params.startDate,
			endDate: params.endDate
		}).then(data => {
			if (data.status === '1') {
				this.detailTable.getDatas(data.sessionkey, 1);
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	@action save = () => {
		const params = {
			id: this.opId,
			cmd: 'save'
		};
		this.formTarget.schedulingForm.validateForm().then(f => {
			if (f.isValid) {
				Object.assign(params, this.formTarget.schedulingForm.getFormParams());
				api.saveSchedulingSetting(params).then(data => {
					if (data.status === '1') {
						this.dialogParams.onCancel();
						message.success(i18n.message.saveSuccess());
						if (this.tabConfig.activeTabKey === '1')
							this.table.getDatas(null, 1);
						else
							this.getCalendarData();
					} else
						message.error(data.message);
				}, error => {});
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		});
	}

	@action multiRemove = (params) => {
		if (params != null) {
			Object.assign(params, {
				cmd: 'delete'
			})
		} else {
			params = {
				cmd: 'delete',
				ids: this.table.selectedRowKeys
			}
		}
		this.confirmInfo({
			content: i18n.confirm.forbidden(),
			onOk: () => {
				api.saveSchedulingSetting(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.deleteSuccess());
						this.table.getDatas(null, 1);
					} else {
						message.error(data.message);
					}
				}, error => {})
			}
		});
	}

	cancelScheduleList = [];
	cancelSchedule = (params) => {
		this.opId = params.id;
		this.cancelScheduleList.length = 0;
		const formParams = this.formTarget.schedulingForm.getFormParams();
		Object.assign(params, {
			startDate: formParams.field001,
			endDate: formParams.field002
		})
		api.getCancelForm(params).then(data => {
			if (data.status === '1') {
				if (data.items && data.items.length > 1) {
					this.cancelScheduleList = data.items;
					this.dialogParams.title = i18n.label.plsSelectNeedCancelSchedule();
					this.dialogParams.opType = 'cancelSchedule';
					this.dialogParams.coms = <ScheduleList ecId={`${this && this.props && this.props.ecId || ''}_ScheduleList@crwh2o`} store={this} items={this.cancelScheduleList}/>;
					const h = data.items.length * 50;
					this.dialogParams.style = {
						width: 500,
						height: h > 400 ? 400 : h
					}
					this.dialogParams.visible = true;
				} else {
					this.onCancelScheudling({
						sIds: data.items[0].value
					});
				}
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	@action onCancelScheudling = (obj) => {
		const formParams = this.formTarget.schedulingForm.getFormParams();
		const params = {
			id: this.opId,
			cmd: 'cancel',
			startDate: formParams.field001,
			endDate: formParams.field002
		}
		if (this.cancelScheduleList.length > 0) {
			let checkedList = [];
			this.cancelScheduleList.map(d => {
				d.checked && checkedList.push(d.value);
			})
			let sIds = checkedList.join(',');
			if (sIds.length === 0) {
				message.error(i8n.label.plsSelectNeedCancelSchedule());
				return;
			}
			Object.assign(params, {
				sIds
			})
		} else {
			Object.assign(params, obj);
		}

		this.confirmInfo({
			content: i18n.confirm.checkCancelSchedule(),
			onOk: () => {
				api.saveSchedulingSetting(params).then(data => {
					if (data.status === '1') {
						this.dialogParams.onCancel();
						message.success(i18n.message.opSuccess());
						this.table.getDatas(null, 1);
					} else {
						message.error(data.message);
					}
				}, error => {})
			}
		});
	}

	removeDetail = (params) => {
		let content;
		if (params != null) {
			content = i18n.confirm.delete();
		} else {
			content = i18n.confirm.deleteSelected();
		}
		this.confirmInfo({
			content,
			onOk: () => {
				const apiMethod = this.dialogParams.opType === 'create' ? 'saveSchedulingSettingPersonDetial' : 'saveSchedulingSettingDetial';
				api[apiMethod]({
					cmd: 'delete',
					ids: params != null ? params.id : this.detailTable.selectedRowKeys
				}).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.deleteSuccess());
						this.detailTable.getDatas(null, 1);
						if (this.tabConfig.activeTabKey === '2')
							this.getCalendarData();
					} else {
						message.error(data.message);
					}
				}, error => {})
			}
		});
	}

	@action saveDetail = (ids, names, datas) => {
		if (ids.length == 0)
			return;
		const formParams = this.formTarget.schedulingForm.getFormParams();
		let params = {
			cmd: 'mInsert',
			field001: this.opId,
			field002: ids
		}
		this.dialogParams.opType != 'create' && Object.assign(params, {
			sId: this.opId,
			startDate: formParams.field001,
			endDate: formParams.field002
		})
		api.saveSchedulingSettingPersonDetial(params).then(data => {
			if (data.status === '1') {
				// message.success(i18n.message.saveSuccess());
				if (this.dialogParams.opType === 'create')
					this.getPersonDetialList()
				else {
					this.getFormDetailList({
						id: this.opId,
						startDate: formParams.field001,
						endDate: formParams.field002
					});
					this.getCalendarData();
				}
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	onDateSwitchChange = (type, day, range) => {
		if (type != this.calendarType) {
			this.calendarType = type;
			this.currentDay = new Date();
		} else {
			this.currentDay = new Date(this.moment(range[0]).format('YYYY/MM/DD HH:mm:ss'));
		}

		this.startDate = this.moment(range[0]).format('YYYY-MM-DD');
		this.endDate = this.moment(range[type === 'day' ? 0 : 1]).format('YYYY-MM-DD');
		this.getCalendarData();
	}

	getCalendarData = () => {
		this.calendarData.length = 0;
		const params = {
			cmd: 'getContent',
			B: indexOf(this.dateSwitchTypeList, this.calendarType) + 1,
			R: false,
			S: this.startDate,
			E: this.endDate,
			M: this.containerInitFinished.userId,
			U: this.containerInitFinished.userId
		}
		this.selectedSubCompany && Object.assign(params, {
			C: this.selectedSubCompany.id
		})
		api.getCalendarData(params).then(data => {
			if (data.status === '1') {
				this.calendarData = data.calendar;
			} else {
				message.error(data.message);
			}

			this.refreshMainTab = new Date().getTime();
		}, error => {})
	}

	changeView = (date) => {
		const ymd = convertCalendarDate(date);
		const reg = new RegExp('-', "g")
		const t = ymd.replace(reg, '/');
		this.calendarType = 'month';
		this.currentDay = new Date(t);
		this.startDate = this.moment(this.currentDay).startOf('month').format('YYYY-MM-DD');
		this.endDate = this.moment(this.currentDay).endOf('month').format('YYYY-MM-DD');
		this.getCalendarData();
	}

	yearDateCellRender = (date) => {
		const d = date.getDayOfMonth();
		const ymd = convertCalendarDate(date);
		const datas = this.toJS(this.calendarData);
		const index = findIndex(datas, {
			date: ymd
		});
		return (
			<div>
				<div>{d}</div>
				{
					index >= 0 &&
					<div className='bottomTag' style={{backgroundColor: datas[index].bgColor}}></div>
				}
				{
					index >= 0 && has(datas[index], 'title') &&
					<div className='workTips' title={d.tips} style={{color: datas[index].titleColor}}>{datas[index].title}</div>
				}
			</div>
		)
	}

	monthDateCellRender = (date) => {
		const d = date.getDayOfMonth();
		const ymd = convertCalendarDate(date);
		const datas = this.toJS(this.calendarData);
		const index = findIndex(datas, {
			date: ymd
		});
		return (
			<div>
				{
					index > 0 && <div className='workTips' style={{color: datas[index].titleColor}}>{datas[index].title}</div>
				}
				{
					index > 0 && 
					<div className='list'>
						<WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@ns3ay6`} height={'100%'}>
						{
							datas[index].datas && datas[index].datas.length > 0 ? datas[index].datas.map(d => {
								return (
									<div className='schedul' 
										title={d.tips} 
										style={{backgroundColor: d.bgColor}}
										onClick={() => this.editFormInfo({id: d.id, startDate: ymd, endDate: ymd, schedule: d.tips})}>
										{d.title}
									</div>
								)
							})
							:
							<div className='empty' onClick={() => this.getFormInfo(true, {startDate: ymd, endDate: ymd})}></div>
						}
						</WeaNewScroll>
					</div>
				}
			</div>
		)
	}

	@action clearScheudling = () => {
		const formParams = this.formTarget.schedulingForm.getFormParams();
		let params = {
			cmd: 'clean',
			sId: this.opId,
			startDate: formParams.field001,
			endDate: formParams.field002
		}
		api.saveSchedulingSettingPersonDetial(params).then(data => {
			if (data.status === '1') {
				this.dialogParams.onCancel();
				message.success(i18n.message.opSuccess());
				this.getCalendarData();
			} else {
				message.error(data.message);
			}
		}, error => {})
	}
	/********************* action list *********************/
}

export const hrmSchedulingSetting = new HrmSchedulingSetting();