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

export default class FormStore {
	constructor(root) {
		this.root = root
	}
	
	hasTitle = true;
	@observable className = '';

	@observable form = new WeaForm();
	@observable conditions = [];
	@observable loading = false;

	@observable searchGroupProps = {};
	@observable comProps = {};
	@observable customRenderKeyList = [];
	@observable linkageConfigs = [];
	@observable mark = '';
	@observable hasOrderNumber = false;
	@observable labelPres = {};

	get otherComponents() {
		const mark = (this.mark !== undefined) ? this.mark : '';
		return this.root[`${mark}OtherComponents`];
	}

	@action init = (config) => {
		Object.keys(config).forEach(key => {
			this[key] = config[key];
		})
		return this
	}

	@action fetchForm = (params = {}, exportDatas, afterInit) => {
		this.loading = true;
		this.form = new WeaForm();
		
		return this.api(params).then(datas => {

			exportDatas && exportDatas(datas);
			
			const conditions = this.getCondition(datas);
			this.conditions = conditions;
			if (conditions && conditions[0].items) {
				!this.hasTitle &&  this.clearTitle(conditions);
				if (this.isCustomRender) { 
					this.form.initFormFields(conditions, afterInit);
				} else {
					this.form.setCondition(conditions);
				}
			}

			this.loading = false;

		})
	}

	clearTitle  = (conditions) => {
		conditions[0].title = '';
	}

	validateForm = (form) => {
		 form = form || this.form;
		return new Promise((resolve, reject) => {
			form.validateForm().then(f => {
				if (f.isValid) {
					resolve();
				} else {
					reject();
					f.showErrors();
				}
			}).catch(() => {
				reject();
			})
		})
	}

	collectViewAttr3keys = (conditions) => {
		let keys = [];
		this.conditions.forEach(c => {
			c.items.forEach(item => {
				const {
					viewAttr,
					domkey
				} = item;

				if (viewAttr === 3) {
					let key;
					if (domkey.length > 1) {
						key = domkey.join('__');
					} else {
						key = domkey[0];
					}
					keys.push(key);
				}
			})
		})
		return keys
	}

	collectHideFormFieldKeys = (showFormFieldKeys) => {
		const viewAttr3keys = this.collectViewAttr3keys();
		return viewAttr3keys.filter(key => !showFormFieldKeys.includes(key));
	}

	getCondition = (datas) => {
		if (datas.items) {
			datas.title = '';
			return [datas];
		}else{
			let c = [];
			Object.keys(datas).forEach(key => {
				if (key.includes('condition')) {
					c = datas[key];
				}
			})
			return c;
		}
		
	}

	handleFormChange = (datas) => {
		this.root.handleFormChange && this.root.handleFormChange(datas);
	}

	setCustomRenderKeyList = (customRenderKeyList) => {
		this.customRenderKeyList = customRenderKeyList;
	}

}