import * as mobx from 'mobx';
import * as Api from '../apis/singleWorkNature';

import {
	observable,
	action,
} from 'mobx';

import {
	WeaForm,
} from 'comsMobx';

import {
	message
} from 'antd';

export class HrmSingleWorkNatureFormStore {
	@observable workNatureId = '';
	@observable date = '';
	@observable workNature = {
		condition: [],
		form: new WeaForm(),
		loading: true,
		authorized: false,
	};

	hide;
	setParentHideMthd = (func) => {
		this.hide = func;
	}

	@action
	getRight = () => {
		Api.getRight().then(rs => {
			const {
				api_status,
				hasRight = true
			} = rs;

			if (api_status) {
				this.workNature.authorized = hasRight;
				this.getWorkNatureForm();
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	getWorkNatureForm = () => {
		this.resetWorkNatureForm();
		let params = {
			usekindid: this.workNatureId,
		}
		Api.getWorkNatureForm(params).then(rs => {
			const {
				api_status,
				condition,
			} = rs;

			if (api_status) {
				if (condition) {
					!this.workNature.authorized && this.setFormReadOnly(condition);
					this.workNature.condition = condition;
					this.workNature.form.initFormFields(condition);
				}
			} else {
				message.error(rs.message);
			}
			this.workNature.loading = false;
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	saveWorkNatureForm = () => {
		this.workNature.form.validateForm().then(f => {
			if (f.isValid) {
				let params = {
					...this.workNature.form.getFormParams(),
					id: this.workNatureId
				};
				Api.saveWorkNatureForm(params).then(rs => {
					const {
						api_status,
						sign,
					} = rs;

					if (api_status) {
						sign == '1' ? message.success(rs.message) && this.hide() : message.warning(rs.message);
					} else {
						message.error(rs.message);
					}
				}).catch(error => {
					message.error(error);
				});
			} else {
				f.showErrors();
				this.setDate({
					date: new Date()
				});
			}
		});
	}

	@action
	setFormReadOnly = (condition) => {
		condition.map(c => {
			c.items.forEach(item => {
				item.viewAttr = 1;
			});
		});
	}

	@action
	resetWorkNatureForm = () => {
		this.workNature.loading = true;
		this.workNature.form = new WeaForm();
	}

	@action
	setWorkNatureId = (id) => {
		this.workNatureId = id;
	}

	@action
	setDate = (date) => {
		this.date = date;
	}

}