<!--
 * @Descripttion: 过滤器V2
-->
<template>
	<slot :filterLength="filterObjLength" :openFilter="openFilter">
		<el-badge :value="filterObjLength" type="danger" :hidden="filterObjLength<=0">
			<el-button icon="el-icon-filter" @click="openFilter" v-if="filtermoreLength"></el-button>
		</el-badge>
		<div class="right-panel-search" v-if="filter.length>0">
			<el-form ref="form" :inline="true" :model="data" @submit.prevent="ok">
				<el-form-item :style="{ 'margin-bottom': '0px', 'margin-right': '6px', 'width': getWidth(i) }" v-for="(i,index) in fieldTop" :key="index">
					<x-item  :item="i" v-model="data"></x-item>
				</el-form-item>
				<el-form-item style="margin-bottom:0px;margin-right: 6px;">
					<el-button type="primary" @click="ok">查询</el-button>
				</el-form-item>
			</el-form>
		</div>
	</slot>
	<el-dialog title="过滤器" v-model="dialog" :size="680" append-to-body class="dialogClass">
		<el-scrollbar>
			<div class="x-filter-main">
				<h2>设置过滤条件</h2>
				<div v-if="filter.length<=0"  class="nodata">
					没有默认过滤条件，请点击增加过滤项
				</div>
				<table v-else>
					<colgroup>
						<col width="30">
						<col width="40">
						<col width="140"> 
						<col>
						<col width="110">
					</colgroup>
					<tr v-for="(item,index) in filter" :key="index">
						<td>
							<el-tag :disable-transitions="true" type="info">{{index+1}}</el-tag>
						</td>
						<td>
							<el-icon v-if="!item.selected" class="del" @click="delFilter(index, item)" style="border: 1px solid #e6e6e6;">
								<el-icon-delete />
							</el-icon>
						</td>
						<td>
							<el-select v-model="item.value" @change="fieldChange(item, index)" :disabled="item.selected">
								<el-option v-for="field in optionsList" :key="field.name" :label="field.label" :value="field.name" :disabled="isDisabled(field.name)"> </el-option>
							</el-select>
						</td>
						<td>
							<x-item v-model="data" :item="item"></x-item>
						</td>
						<td v-if="item.operators && item.operators.length>0">
							<el-select v-model="item.operator" placeholder="运算符">
								<el-option v-for="ope in item.operators || operator" :key="ope.value" v-bind="ope"></el-option>
							</el-select>
						</td>
					</tr>
				</table>
				<el-button type="primary" text icon="el-icon-plus" @click="addFilter">增加过滤项</el-button>
			</div>
			<my ref="my" :data="myFilter" :filterName="filterName" @selectMyfilter="selectMyfilter"></my>
		</el-scrollbar>
		<template #footer>
		    <span class="dialog-footer">
		    	<el-button type="primary" @click="ok" :disabled="filter.length<=0">立即过滤</el-button>
		    	<el-button type="primary" plain @click="saveMy" :disabled="filter.length<=0">另存为常用</el-button>
		    	<el-button @click="clear">清空过滤</el-button>
		    </span>
		</template>
	</el-dialog> 
</template>

<script>
	import config from "@/config/filterBar"
	import my from './my'

	export default {
		name: 'filterBar',
		components: {
			my
		},
		props: {
			filterName: { type: String, default: "" },
			modelValue: [String, Number, Boolean, Date, Object, Array],
			options: { type: Object, default: () => {} }
		},
		emits: ['filterChange'],
		data() {
			return {
				dialog: false,
				operator: config.operator,
				fields: this.options,
				filter: [],
				myFilter: [],
				fieldTop: [],
				defaultValue: Object.assign({}, this.modelValue),
				defaultField: [].concat(this.options),
				filterObjLength: 0,
				filtermoreLength: 0,
				saveLoading: false,
				data: this.modelValue,
				optionsList: [],
			}
		},
		watch:{
			data(val){
				this.$emit("update:modelValue", val)
			}
		},
		computed: {
			filterObj(){
				const obj = {}
				this.filter.forEach((item) => {
					if (this.data[item.name] === undefined || this.data[item.name] === '' || JSON.stringify(this.data[item.name]) === '') {
					  return ; // 跳过当前迭代，继续下一次迭代
					}
					if (item.options && item.options.items && item.options.items.length>0) {
						const foundItem = item.options.items.find(o => o.value === this.data[item.name]);
						if (foundItem?.operator) {
							item.operator = foundItem.operator;
						}
					}

					obj[item.name] = item.operator ? this.data[item.name]+`${config.separator}${item.operator}` : this.data[item.name]
				})
				return obj
			},
			getWidth() {
		    	return function(item) {
		      		return item.width ? item.width+'px' : 'auto';
		    	}
		  	}
		},
		mounted(){


			//默认显示的过滤项
			this.fields.forEach((item) => {


				if(item.selected){
					item.options.placeholder = item.options.placeholder ? item.options.placeholder : item.label;
					item.options.clearable = true;
					this.fieldTop.push(item)
					item.value = item.name;
					this.filter.push(item)
				}else{

					this.filtermoreLength++
				}
			})
			this.optionsList = [].concat(this.fields);
		},
		methods: {
			fieldChange(o, index){
				const foundObject = this.defaultField.find(obj => obj.name === o.value);
				this.data[o.name] = '';
				this.filter[index] = Object.assign(foundObject, {value:o.value});
			},
			isDisabled(key){
				if(this.filter.some(item => item.name === key && !item.repeat)){
					return true
				}
				return false
			},
			//打开过滤器
			openFilter(){
				this.dialog = true
			},
			//增加过滤项
			addFilter(){
				//下一组新增过滤
				var filterArr = this.fields.filter(field => !this.filter.some(item => field.name == item.name && !item.repeat))
				if(this.fields.length<=0 || filterArr.length<=0){
					this.$message.warning('无过滤项了');
					return false
				}
				const filterNum = filterArr[0]
				filterNum.value = filterNum.name;
				this.filter.push(filterNum)
			},
			//删除过滤项
			delFilter(index, o){
				this.filter.splice(index, 1)
				this.data[o.name] = '';
			},
			//立即过滤
			ok(){
				this.filterObjLength = Object.keys(this.filterObj).length
				this.$emit('filterChange',this.filterObj)
				this.dialog = false
			},
			//清空过滤
			clear(){
				Object.keys(this.data).forEach(key => {
				  this.data[key] = this.data[key] === this.defaultValue[key] ? this.defaultValue[key] : '';
				});
				this.filterObjLength = 0
				this.$emit('filterChange',this.filterObj)
			},
			//选择常用过滤
			selectMyfilter(item){
				//常用过滤回显当前过滤项
				this.filter = []
				this.fields.forEach((field) => {
					var filterValue = item.filterObj[field.value]
					if(filterValue){
						field.operator = filterValue.split("|")[1]
						var value = filterValue.split("|")[0]
						if(field.component=='select' && field.options.multiple){
							value = value.split(",")
						}else if(field.component=='daterange'){
							value = value.split(",")
						}

						this.data[field.name] = value;
						this.filter.push(field)
					}
				})
				this.filterObjLength = Object.keys(item.filterObj).length
				this.$emit('filterChange',item.filterObj)
				this.dialog = false
			},
			//保存常用
			saveMy(){
				this.$prompt('常用过滤名称', '另存为常用', {
					inputPlaceholder: '请输入识别度较高的常用过滤名称',
					inputPattern: /\S/,
					inputErrorMessage: '名称不能为空'
				})
				.then(async ({ value }) => {
					this.saveLoading = true
					const saveObj = {
						title: value,
						filterObj: this.filterObj
					}
					try {
						var save = await config.saveMy(this.filterName, saveObj)
					}catch (error) {
						this.saveLoading = false
						console.log(error);
						return false
					}
					if(!save){
						return false
					}

					this.myFilter.push(saveObj)
					this.$message.success(`${this.filterName} 保存常用成功`)
					this.saveLoading = false
				})
				.catch(() => {
					//
				})
			},
		}
	}
</script>

<style>
	.tabs-label {padding:0 20px;}

	.dialogClass .el-dialog__body {
	  	margin: 10px 20px;
	   	padding: 0;
	}
	.dialogClass .el-dialog__footer {
	  text-align: right;
	}
	.nodata {height:46px;line-height: 46px;margin:15px 0;border: 1px dashed #e6e6e6;color: #999;text-align: center;border-radius: 3px;}
	.x-filter-main {background: #fff; padding-top: 0px}
	.x-filter-main h2 {font-size: 12px;color: #999;font-weight: normal;}
	.x-filter-main table {width: 100%;margin: 10px 0;}
	.x-filter-main table tr {}
	.x-filter-main table td {padding:5px 10px 5px 0;}
	.x-filter-main table td:deep(.el-input .el-input__inner)  {vertical-align: top;}
	.x-filter-main table td .el-select {display: block;}
	.x-filter-main table td .el-date-editor.el-input {display: block;width: 100%;}
	.x-filter-main table td .del {background: #fff;color: #999;width: 32px;height: 32px;line-height: 32px;text-align: center;border-radius:50%;font-size: 12px;cursor: pointer;}
	.x-filter-main table td .del:hover {background: #F56C6C;color: #fff;}

	.root {display: flex;height: 100%;flex-direction: column}
	.root:deep(.el-tabs__header) {margin: 0;}
	.root:deep(.el-tabs__content) {flex: 1;background: #f6f8f9;}
	.root:deep(.el-tabs__content) .el-tab-pane{overflow: auto;height:100%;}



	.dark .root:deep(.el-tabs__content) {background: var(--el-bg-color-overlay);}
	.dark .x-filter-main {background: var(--el-bg-color);border-color:var(--el-border-color-light);}
	.dark .x-filter-main table td .del {background: none;}
	.dark .x-filter-main table td .del:hover {background: #F56C6C;}
	.dark .nodata {border-color:var(--el-border-color-light);}
</style>
