<script setup>
const state = reactive({
  showMoreCondition: false,
});
const emit = defineEmits(['doFilter'])
const props = defineProps({
  filterOptions: Array,
  beforeFilter: Function,
  beforeReset: Function,
  showRest: {
    type: Boolean,
    default: false,
  },
  labelWidth: {
    type: String,
  },
  inline: {
    type: Boolean,
    default: true,
  },
  showMoreCondition: {
    type: Boolean,
    default: false,
  },
})
const getFilterParams = () => {
  let filterRes = {};
  props.filterOptions.map(item => {
    filterRes[item.key] = item.customFormatter ? item.customFormatter(item.value) : item.value
  })
  return filterRes;
}
const doFilter = () => {
  if (props.beforeFilter && props.beforeFilter instanceof Function) {
    //判断props.beforeFilter是普通函数还是promise函数
    let beforeFilterRes = props.beforeFilter(getFilterParams())
    if (beforeFilterRes instanceof Promise) {
      beforeFilterRes.then(data => {
        emit('doFilter', data || getFilterParams())
      })
    } else {
      emit('doFilter', beforeFilterRes || getFilterParams())
    }
  } else {
    emit('doFilter', getFilterParams())
  }
}
const clone = (obj) => {
  return typeof obj === 'object' ? JSON.parse(JSON.stringify(obj)) : obj;
}
const clearFilter = () => {
  if (props.beforeReset && props.beforeReset instanceof Function) {
    let beforeResetRes = props.beforeReset(getFilterParams())
    if (beforeResetRes instanceof Promise) {
      beforeResetRes.then(() => {
        reset()
      })
    } else {
      reset()
    }
  } else {
    reset()
  }

}

const reset = () => {
  props.filterOptions.map(item => {
    item.value = clone(item.default) || ''
  })
}

defineExpose({
  doFilter,
  getFilterParams,
  clearFilter
})


</script>

<template>
  <el-row v-if="props.filterOptions && props.filterOptions.length > 0">
    <el-form ref="queryRef" :inline="props.inline" :label-width="props.labelWidth">
      <el-form-item v-show="!item.hide && (state.showMoreCondition || !item.fold)" :label="item.label"
        v-for="(item, index) in props.filterOptions" :key="item.key">
        <component :is="item.tag" v-model="props.filterOptions[index].value" v-bind="item.attribute"
          v-on="item.event || {}"></component>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="doFilter">搜索</el-button>
        <el-button icon="Refresh" @click="clearFilter">重置</el-button>
        <el-button plain type="info" v-if="props.showMoreCondition" icon="Sort"
          @click="state.showMoreCondition = !state.showMoreCondition">{{ state.showMoreCondition ? "收起条件" : "展开条件"
          }}</el-button>
      </el-form-item>
    </el-form>
  </el-row>
</template>

<style scoped></style>
