<template>
	<div class="rmc_criteria_form_special">
		<operators v-if="operatorsList.length > 0" 
				:fieldId="criteria.FIELD_ID" 
				:index="index" 
				:queries="operatorsList" 
				:selected="selectedOp" 
				@changeOp=" e => changeOperator(e)"
				:criteriaTitle="criteria.TITLE">
		</operators>
        <div class="rmc_search_special_container" v-if="html" v-html="html"></div>
	</div>
</template>

<script>
import operators from "./operators.vue";
export default {
	name: "criteriaFormSpecial",
    props : ['criteria', 'searchData', 'index', 'showfieldvars'],
	data: function(){
		return {
			html: "",
			operatorsList: [],
			selectedOp: "EQ",
		}
	},
	components : {
		operators
	},
	mounted: function(){
		this.getSpecialField()
	},
	watch: {
		criteria: function(newVal,oldVal) {
			if (newVal.FIELD_ID != oldVal.FIELD_ID) {
				this.operatorsList = [];
				this.html = "";
				this.getSpecialField();
			}
		}
	},
	created: function(){
		if ("undefined" !== typeof this.searchData[this.index] && (this.searchData[this.index].SEARCH == this.criteria.FIELD_ID)) {
	    	if(this.searchData[this.index] && this.searchData[this.index].OP){
	            for (var i = 0; i < this.criteria.QUERIES.length; i++) {
	                var operator = this.criteria.QUERIES[i];
	                if (this.searchData[this.index].OP == operator['OPERATOR']) {
	                	this.selectedOp = this.searchData[this.index].OP;
	                }
	            }
	    	}
		}
	},
	computed: {
	    name: function() {
	        return `field_${this.index}_${this.criteria.FIELD_ID}`;
	    },
		inputId : function() {
			return `field_${this.index}_${this.criteria.FIELD_ID}`;
		},
		hiddenData: function(){
			var data = [];
			if (this.searchData[this.index]) {
				data.push({value: this.searchData[this.index].FIELD, name: this.name });
			}
			return data;
		}
	},
	methods: {
		getSpecialField: function(){
			if(this.criteria.RESPONSIVE){
				var data = new FormData();
				for(let input of this.hiddenData){
					if (Array.isArray(input.value) || typeof input.value === 'object') {
						data.append(input.name, JSON.stringify(input.value));
					} else {
						data.append(input.name, input.value);
					}
				}
				this.flag = true;
				fetch("./ajax.php?module=ajax&categ=search_field&sub=special&type="+ this.criteria.TYPE +"&n=" + this.index, {
					method: 'POST',
					body: data
				}).then((response)=> {
					if (response.ok) {
						response.json().then((result)=> {
						    this.html = result.input;
							if (result.op) {
								for (const operator in result.op) {
									this.operatorsList.push({OPERATOR: operator, LABEL: result.op[operator]});
								}
							}
					    });
					} else {
						console.error("Error search special ajax");
					}
					this.flag = false;
				}).catch((error) => {
					console.error(error.message);
					this.flag = false;
				});
			}
		}
	}
}
</script>