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

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

import {
	WeaForm,
} from 'comsMobx';

import {
	message
} from 'antd';

export class HrmSingleMajorStore {
	@observable majorId = '';
	@observable date = '';
	@observable major = {
		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.major.authorized = hasRight;
				this.getMajorForm();
			} else {
				message.error(rs.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	@action
	getMajorForm = () => {
		this.resetMajorForm();
		let params = {
			specialityid: this.majorId,
		}
		Api.getMajorForm(params).then(rs => {
			const {
				api_status,
				condition,
			} = rs;

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

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

	@action
	setMajorId = (id) => {
		this.majorId = id;
	}

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

}