<script lang="ts" setup>
import { post } from "@/common/http/request";
import type { SearcherProp } from "./SearchBarType";
import type { PropType } from "vue";
import { Search, Refresh } from "@element-plus/icons-vue";
const props = defineProps({
  searchers: Array as PropType<SearcherProp[]>,
  searchClick: Function,
  resetClick: Function,
});
const searcherParams = defineModel<Record<string, string>>("searcherParams");
function getSelectData(searcher: SearcherProp) {
  if (searcher.selectData !== undefined) {
    return searcher.selectData;
  }
  if (searcher.selectDataUrl !== undefined && searcher.selectDataParse !== undefined) {
    return searcher.selectDataParse(post(searcher.selectDataUrl));
  }
  return {};
}
function searchButtonClick() {
  if (props.searchClick === undefined) return;
  props.searchClick(searcherParams);
}
function reset() {
  searcherParams.value = {};
  if (props.resetClick === undefined) return;
  props.resetClick();
}
</script>
<template>
  <div class="search-bar" v-if="searcherParams !== undefined">
    <div v-for="searcher of searchers" :key="searcher.name" class="searcher-box">
      <el-input v-model="searcherParams[searcher.name]" v-if="searcher.type === 'text'" class="searcher">
        <template #prepend>{{ searcher.placeholder }}</template>
      </el-input>
      <el-select v-model="searcherParams[searcher.name]" v-if="searcher.type === 'select'" class="searcher">
        <template #prefix>{{ searcher.placeholder }}</template>
        <el-option v-for="(value, key) of getSelectData(searcher)" :key="key" :label="value" :value="key"></el-option>
      </el-select>
      <el-date-picker
        v-model="searcherParams[searcher.name]"
        v-if="searcher.type === 'date-range-pick'"
        type="daterange"
        range-separator="-"
        :start-placeholder="$t('_prop.common.startdate')"
        :end-placeholder="$t('_prop.common.enddate')"
        value-format="YYYY-MM-DD"
      ></el-date-picker>
    </div>
    <el-button v-if="searchClick !== undefined" :icon="Search" type="primary" @click="searchButtonClick">
      {{ $t("_button.search") }}
    </el-button>
    <el-button v-if="searchClick !== undefined" :icon="Refresh" @click="reset">{{ $t("_button.reset") }}</el-button>
  </div>
</template>
<style>
.search-bar {
  display: flex;
  padding-right: 20px;
}
.searcher-box {
  padding-left: 5px;
  padding-right: 5px;
}
.searcher {
  width: 285px;
}
</style>
