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

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

import {
	WeaForm,
} from 'comsMobx';

import {
	message
} from 'antd';

export class HrmSingleEducationFormStore {
	@observable educationId = '';
	@observable date = '';
	@observable education = {
		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.education.authorized = hasRight;
				this.getEducationForm();
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	getEducationForm = () => {
		this.resetEducationForm();
		let params = {
			eduid: this.educationId,
		}
		Api.getEducationForm(params).then(rs => {
			const {
				api_status,
				condition,
			} = rs;

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

	@action
	saveEducationForm = () => {
		this.education.form.validateForm().then(f => {
			if (f.isValid) {
				let params = {
					...this.education.form.getFormParams(),
					id: this.educationId
				};
				Api.saveEducationForm(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
	resetEducationForm = () => {
		this.education.loading = true;
		this.education.form = new WeaForm();
	}

	@action
	setEducationId = (id) => {
		this.educationId = id;
	}

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

}