import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaForm,
	WeaTableNew,
	WeaSwitch
} from 'comsMobx';
import {
	Button,
	message
} from 'antd';
import HrmBaseStore from './baseStore';
import * as api from '../apis/matrix';
import {
	has,
	findIndex,
	cloneDeep
} from 'lodash';
import {
	getColumIndex,
	calColumnIndex
} from '../util/index';
import {
	i18n
} from '../public/i18n';

const {
	TableStore
} = WeaTableNew;

class HrmMatrixFieldSetting extends HrmBaseStore {
	rootStore;
	setRootStore = (rootStore) => {
		this.rootStore = rootStore;
		rootStore.saveField = this.saveField;
	}
	/********************* unobservable list *********************/
	matrixInfo;
	basicData;
	data;
	validInterval;
	needShowDataMaintenance = false;
	/********************* unobservable list *********************/

	/********************* dialog info setting *********************/
	/********************* dialog info setting *********************/

	/********************* observable list *********************/
	@observable _dataList = {condition: [], val: []}
	@computed get dataList(){
		return this._dataList
	}
	set dataList(v){this._dataList = v};

	@observable loading = false;
	/********************* observable list *********************/

	/********************* computed list *********************/
	/********************* computed list *********************/

	/********************* action list *********************/
	@action initData = (matrix) => {
		this.matrixInfo = matrix;
		// this.dataList = {condition: [], val: []};
		this.loading = true;
		api.initFieldData({
			matrixid: matrix.matrixid
		}).then(rs => {
			rs.map((result, index) => {
				if (result.status === '1') {
					switch (index) {
						case 0:
							this.basicData = result;
							break;
						case 1:
							this.data = result;
							this.initTableData();
							this.loading = false;
							break;
					}
				}
			})
		})
	}

	clearDataList = () => {
		// this.dataList.condition.length = 0;
		// this.dataList.val.length = 0;
	}

	initTableData = () => {
		if (this.data.status === '1') {
			this.clearDataList();
			const condition = [], val = [];
			// if (this.data.condition == null) this.data.condition = [];
			(this.data.condition || []).map((record, i) => {
				const data = {
					form: new WeaForm(),
					fields: record.formField,
					data: record,
					index: i
				}
				data.form.initFormFields(data.fields);
				data.form.isFormInit && condition.push(data);
			})
			condition.push({
				data: {
					type: 0,
					condition: true
				}
			});
			// if (this.data.val == null) this.data.val = [];
			(this.data.val || []).map((record, i) => {
				const data = {
					form: new WeaForm(),
					fields: record.formField,
					data: record,
					index: i
				}
				data.form.initFormFields(data.fields);
				data.form.isFormInit && val.push(data);
			})
			val.push({
				data: {
					type: 1,
					condition: false
				}
			});
			this.dataList = {condition, val}
		}
	}

	addField = (condition = true) => {
		let cloneObj;
		const data = {
			form: new WeaForm()
		}
		if (condition) {
			cloneObj = cloneDeep(this.basicData.condition);
		} else {
			cloneObj = cloneDeep(this.basicData.val);
		}
		Object.assign(data, {
			fields: cloneObj[0].formField,
			data: cloneObj[0]
		});
		data.form.initFormFields(data.fields);
		const {condition: conditionList, val} = this.dataList;
		condition ?
			conditionList.splice(conditionList.length - 1, 0, { ...data,
				index: conditionList.length - 1
			}) :
			val.splice(val.length - 1, 0, { ...data,
				index: val.length - 1
			});
		this.dataList = {condition: conditionList, val}
		this.resetScroll(condition);
	}

	removeField = (condition = true, colIndex) => {
		const {condition: conditionList, val} = this.dataList;
		const num = calColumnIndex(colIndex);
		let index = -1;
		if (condition) {
			index = num - 1;
		} else {
			index = num - conditionList.length - 1
		}
		this.confirmInfo({
			content: i18n.confirm.deleteSelected(),
			onOk: () => {
				condition ? conditionList.splice(index, 1) : val.splice(index, 1);
				this.dataList = {condition: conditionList, val}
			}
		});
	}

	@action resetScroll = (condition = true) => {
		try{
			// setTimeout(() => {
				const left = $('.matrixFieldSetting').scrollLeft();
				condition && $('.matrixFieldSetting').scrollLeft(left + 150);
				!condition && setTimeout(() => {$('.matrixFieldSetting').scrollLeft(left + 150)}, 200);
			// }, 100)
		}catch(e){
		}
	  }

	checkVal = (obj) => {
		let sameLabelNameCount = 0,
			sameFieldnameCount = 0;
		const keys = Object.keys(this.dataList);
		keys.map(key => {
			this.dataList[key].map((d, i) => {
				if (d.form) {
					const formParams = d.form.getFormParams();
					formParams.labelname === obj.labelname && sameLabelNameCount++;
					formParams.fieldname === obj.fieldname && sameFieldnameCount++;
				}
			})
		});
		if (sameLabelNameCount > 1)
			return 'labelname';
		else if (sameFieldnameCount > 1)
			return 'fieldname';
		return null;
	}

	validFieldData = () => {
		let valid = true;
		if (this.dataList.condition.length === 1 || (this.dataList.condition.length === 1 && this.dataList.val.length === 1)) {
			message.error(i18n.confirm.conditionFieldEmpty());
			return;
		}
		const keys = Object.keys(this.dataList);
		keys.map(key => {
			this.dataList[key].map((d, i) => {
				const {form} = d;
				if(form){
					const formParams = form.getFormParams();
					const {
						labelname,
						fieldname,
						type,
						cusb,
						cusbmulti
					} = formParams;
					if (labelname === '') {
						form.showError('labelname', i18n.message.dataEmpty());
						valid = valid && false;
					} else if (fieldname === '') {
						form.showError('fieldname', i18n.message.dataEmpty());
						valid = valid && false;
					} else if (type === '161' && cusb === '') {
						form.showError('cusb', i18n.message.dataEmpty());
						valid = valid && false;
					} else if (type === '162' && cusbmulti === '') {
						form.showError('cusbmulti', i18n.message.dataEmpty());
						valid = valid && false;
					} else {
						const rs = this.checkVal({
							labelname,
							fieldname
						});
						if (rs != null) {
							form.showError(rs, rs === 'labelname' ? i18n.confirm.displayNameExist() : i18n.confirm.fieldNameExist());
							valid = valid && false;
						}
					}
				}
			})
		});
		valid && this.doSaveField();
	}

	saveField = (showDataMaintenance = false) => {
		this.needShowDataMaintenance = showDataMaintenance;
		this.validFieldData();
	}

	doSaveField = () => {
		let d = [],
			idx = 1;
		const keys = Object.keys(this.dataList);
		keys.map(key => {
			this.dataList[key].map(condition => {
				if (condition.form) {
					const formParams = condition.form.getFormParams();
					condition.form && d.push({
						itemid: condition.data.itemid,
						...formParams,
						type: key === 'condition' ? 0 : 1,
						htmltype: formParams.type,
						iscusttype: formParams.type === '161' ? '1' : formParams.type === '162' ? '2' : '0',
						fieldorder: idx
					}) && idx++;
				}
			})
		})
		const params = {
			data: JSON.stringify({
				matrixid: this.matrixInfo.matrixid,
				data: d
			})
		}
		api.saveField(params).then(data => {
			if (data.status === '1') {
				message.success(i18n.message.saveSuccess());
				if (this.needShowDataMaintenance)
					this.rootStore && this.rootStore.showDataMaintenance(this.matrixInfo);
				else
					this.rootStore && this.rootStore.dialogParams.onCancel();
			} else {
				message.error(data.message);
			}
		})
	}
	/********************* action list *********************/
}

export const hrmMatrixFieldSetting = new HrmMatrixFieldSetting();