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

export default class FormStore {
	constructor(api, rootStore) {
		this.api = api;
		this.rootStore = rootStore
	}

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

	//自定义渲染
	get otherComponents() {
		const mark = this.getFormMark();
		return this.rootStore[`${mark}OtherComponents`];
	}

	get customRenderedElements(){
		return this.rootStore.customRenderedElements;
	}

	@computed get customRenderItem(){
         const obj = []
        this.conditions.forEach(c => c.items.forEach(item => {
            const [key] = item.domkey
            if (this.customRenderKeyList.includes(key)) {
                obj[key] = item
            }
        }))
        return obj
    }

	@action fetchForm = (params = {}, exportDatas, afterInit) => {
		//控制页面、弹框出现loading态
		this.loading = true;
		//清空表单数据
		this.form = new WeaForm();

		return this.api(params).then(datas => {
			//将接口返回的数据抛出去
			exportDatas && exportDatas(datas);

			const conditions = this.getCondition(datas);

			if (this.isCustomRender) { //是否自定义渲染
				this.conditions = conditions;
				this.form.initFormFields(conditions, afterInit);
			} else {
				this.form.setCondition(conditions);
			}

			this.loading = false;

		})
	}

	//校验表单
	validateForm = (form) => {
		return new Promise((resolve, reject) => {
			form.validateForm().then(f => {
				if (f.isValid) {
					resolve();
				} else {
					f.showErrors();
				}
			})
		})
	}

	//收集所有ViewAttr为3的表单元素对应的key值
	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
	}

	//收集不需要校验的表单元素对应的key值
	collectHideFormFieldKeys = (showFormFieldKeys) => {
		const viewAttr3keys = this.collectViewAttr3keys();
		return viewAttr3keys.filter(key => !showFormFieldKeys.includes(key));
	}

	//处理后端接口参数名混乱的问题
	getCondition = (datas) => {
		let c = [];
		Object.keys(datas).forEach(key => {
			if (key.includes('condition')) {
				c = datas[key];
			}
		})
		return c;
	}

	//修改表单元素，触发的回调函数
	handleFormChange = (datas) => {
		this.rootStore.handleFormChange && this.rootStore.handleFormChange(datas);
	}

	//获取表单的标识
	getFormMark = () => {
		return (this.formMark !== undefined) ? this.formMark : '';
	}

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

	//config包括：searchGroupProps、comProps、customRenderKeyList、linkageConfigs、isCustomRender、formMark等
	setFormConfig = (config) => {
		Object.keys(config).forEach(key => {
			this[key] = config[key];
		})
	}

}