import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaForm,
	WeaTableNew,
	WeaSwitch
} from 'comsMobx';
import {
	Button,
	message
} from 'antd';
import ShiftsSettingInfo from '../components/schedule/shiftsSetting/ShiftsSettingInfo';
import DetailSetting from '../components/schedule/shiftsSetting/DetailSetting';
import FormInfo from '../coms/FormInfo';
import HrmBaseStore from './baseStore';
import * as api from '../apis/schedule';
import {
	i18n
} from '../public/i18n';
import {
	cloneDeep,
	indexOf
} from 'lodash';
const {
	TableStore
} = WeaTableNew;

class HrmScheduleShiftsSetting extends HrmBaseStore {
	/********************* unobservable list *********************/
	topBtnAndMenu = () => {
		return {
			btns: [
				<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bq2oom`} type='primary' onClick={() => this.getFormInfo()}>{i18n.button.create()}</Button>,
				<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@uoa7zl`} type='primary' onClick={() => this.multiRemove()} disabled={this.multiRemoveable}>{i18n.button.multiDelete()}</Button>
			],
			menus: [{
				key: '1',
				content: i18n.button.create(),
				icon: <i className={this.menuIconCollection.create}/>,
				onClick: () => this.getFormInfo()
			}, {
				key: '2',
				content: i18n.button.multiRemove(),
				icon: <i className={this.menuIconCollection.remove}/>,
				onClick: () => this.multiRemove(),
				disabled: this.multiRemoveable
			}, {
				key: '3',
				content: i18n.button.columnVisibleSetting(),
				icon: <i className={this.menuIconCollection.setting}/>,
				onClick: () => this.definedColumn(this.table)
			}, ...this.getBasicMenus('HRM_ENGINE_HRM_SCHEDULE_SHIFTS_SET')]
		}
	}

	tabConfig = {
		tabs: [{
			color: '#000000',
			groupId: 'roleList',
			title: '',
			viewCondition: '1',
			searchType: ['base', 'advanced'],
			searchKey: 'field001',
			doSearch: (params) => this.getTableData(params)
		}],
		keyParam: 'viewCondition',
		activeTabKey: '1'
	}

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

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

	detailDialogRightMenu = [];
	getDetailDialogOpButtons = () => {
		let buttons = [];
		this.detailDialogRightMenu.length = 0;
		buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@otrm3n`} type="primary" op="save" onClick={() => this.saveDetail()}>{i18n.button.save()}</Button>);

		buttons.map((btn, index) => {
			const {
				props
			} = btn;
			this.detailDialogRightMenu.push({
				key: index.toString(),
				content: props.children,
				icon: <i className={this.menuIconCollection[props.op]}/>,
				onClick: props.onClick
			});
		})

		this.detailDialogParams.moreBtn.datas = this.detailDialogRightMenu;
		return buttons;
	}

	formFields = [];
	selectedSubCompany;
	selectedSchedulingData;
	/********************* unobservable list *********************/

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

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

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

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

	@observable detailDialogParams = {
		...this.dialogPropsDef,
		opType: '',
		onCancel: () => {
			this.detailDialogParams.opType = '';
			this.detailDialogParams.visible = false;
		}
	}
	/********************* 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
		}
		api.initShiftsSettingData().then(rs => {
			rs.map((result, index) => {
				if (result.status === '1') {
					switch (index) {
						case 0:
							this.setFormData('conditionForm', result.formField);
							this.formTarget.conditionForm.isFormInit && this.getTableData();
							break;
						case 1:
							this.formFields = result.formField;
							break;
						case 2:

							this.rowDetail.length = 0;
							this.selectedRow = {};
							this.table = new TableStore();
							this.table.getDatas(result.sessionkey, 1);
							break;
					}
				}
			})
			this.refreshMainTab = new Date().getTime();
		})
	}

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

	getTableData = (params) => {
		params = params || { ...this.formTarget.conditionForm.getFormParams()
		};
		this.selectedSubCompany != null && Object.assign(params, {
			subcompanyid: this.selectedSubCompany.id,
		})
		this.table = new TableStore();
		api.getShiftsSettingList(params).then(data => {
			if (data.status === '1')
				this.table.getDatas(data.sessionkey, 1);
			else
				message.error(data.message);
			this.rowDetail.length = 0;
			this.selectedRow = {};
		}, error => {
			this.rowDetail.length = 0;
			this.selectedRow = {};
		})
	}

	showDetail = (record, index) => {
		this.selectedRow = record;
		api.saveShiftsSetting({
			cmd: 'getContent',
			id: record.id
		}).then(data => {
			if (data.status === '1') {
				this.rowDetail = data.content;
			}
		})
	}

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

	getDetailTableData = (params) => {
		api.getShiftsSettingDetialList(params).then(data => {
			if (data.status === '1')
				this.detailTable.getDatas(data.sessionkey, 1);
			else
				message.error(data.message);
		}, error => {})
	}

	@action getFormInfo = (params) => {
		if (params != null) {
			Object.assign(params, {
				field001: params.id
			})
			this.opId = params.id;
		}
		api.initShiftsSettingFormData(params).then(rs => {
			rs.map((result, index) => {
				if (result.status === '1') {
					switch (index) {
						case 0:
							this.opId = result.id;
							if (this.containerInitFinished.detachable && this.selectedSubCompany != null) {
								result.formField.map(field => {
									field.items.map(item => {
										if (item.domkey[0] === 'field002') {
											item.browserConditionParam.replaceDatas = [{
												id: this.selectedSubCompany.id,
												name: this.selectedSubCompany.name
											}]
										}
									})
								})
							}
							this.setFormData('shiftsSettingForm', result.formField);
							this.formTarget.shiftsSettingForm.isFormInit && this.getDetailTableData({
								field001: this.opId,
								id: this.opId
							});
							this.selectedSchedulingData = this.formTarget.shiftsSettingForm.getFormParams();
							this.refreshBasicInfo = new Date().getTime();
							break;
					}
				}
				this.showFormDialog(i18n.module.shiftsSetting());
			})
		})
	}

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

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

	showDetailSettingDialog = (title) => {
		this.detailDialogParams.title = title;
		this.detailDialogParams.coms = <DetailSetting ecId={`${this && this.props && this.props.ecId || ''}_DetailSetting@rt9llk`} store={this} />
		this.detailDialogParams.style = {
			width: 600,
			height: 450
		}
		this.detailDialogParams.visible = true;
	}

	@action clearDetail = () => {
		if (this.detailTable.datas && this.detailTable.datas.length > 0) {
			this.confirmInfo({
				content: i18n.confirm.changeRotationModel(),
				onOk: () => {
					api.saveShiftsSettingDetial({
						cmd: 'deleteBySet',
						id: this.opId
					}).then(data => {
						if (data.status === '1') {
							this.getDetailTableData({
								field001: this.opId,
								id: this.opId
							});
						} else {
							message.error(data.message);
						}
					}, error => {})
				},
				onCancel: () => {
					this.formTarget.shiftsSettingForm.updateFields({
						field003: {
							value: this.selectedSchedulingData.field003
						}
					})
				}
			});
		}
	}

	addDetail = () => {
		const formParams = this.formTarget.shiftsSettingForm.getFormParams();
		api.getShiftsSettingDetialForm({
			field001: this.opId,
			field003: formParams.field003
		}).then(data => {
			if (data.status === '1') {
				this.detailFormFields = data;
				this.showDetailSettingDialog(i18n.label.shiftsDetail());
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	removeDetail = () => {
		this.confirmInfo({
			content: i18n.confirm.deleteSelected(),
			onOk: () => {
				api.saveShiftsSettingDetial({
					cmd: 'delete',
					ids: this.detailTable.selectedRowKeys
				}).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.deleteSuccess());
						this.detailTable.getDatas(null, 1);
					} else {
						message.error(data.message);
					}
				}, error => {})
			}
		});
	}

	@action saveDetail = () => {
		const formParams = this.formTarget.shiftsSettingForm.getFormParams();
		let params = {
			cmd: 'save',
			field001: this.opId,
			//field003: formParams.field003,
			field004: formParams.field004,
			field005: formParams.field005
		}
		let field002 = [];
		this.detailFormFields.leftitem.map(item => {
			item.checked && field002.push(item.value);
		})
		this.detailFormFields.rightitem.map(item => {
			item.checked && Object.assign(params, {
				[`param${item.name}`]: 1
			});
		})
		params.field002 = field002.join(';');

		if (field002.length === 0) {
			message.error(i18n.message.plsSelectScheduling());
			return;
		} else if (Object.keys(params).length === 6 && indexOf(['0', '1'], params.field003) >= 0) {
			message.error(i18n.label.plsSelectDate());
			return;
		}

		api.checkDetailWorkTime({ ...params,
			arg: this.opId,
			arg1: params.field002,
			type: params.field003
		}).then(data => {
			if (data.status === '1') {
				if (data.result === 0) {
					api.saveShiftsSettingDetial(params).then(data => {
						if (data.status === '1') {
							this.detailDialogParams.onCancel();
							message.success(i18n.message.saveSuccess());
							this.getDetailTableData({
								field001: this.opId,
								id: this.opId
							});
							// this.detailTable.getDatas(null, 1);
						} else {
							message.error(data.message);
						}
					}, error => {})
				} else {
					message.error(data.message)
				}
			} else {
				message.error(data.message)
			}
		}, error => {})
	}
	/********************* action list *********************/
}

export const hrmScheduleShiftsSetting = new HrmScheduleShiftsSetting();