<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'"
        class="searcher"
        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>
    <div class="search-actions" v-if="searchClick !== undefined">
      <el-button :icon="Search" type="primary" @click="searchButtonClick">
        {{ $t("_button.search") }}
      </el-button>
      <el-button :icon="Refresh" @click="reset">{{ $t("_button.reset") }}</el-button>
      <slot name="after-actions"></slot>
    </div>
  </div>
</template>
<style>
.search-bar {
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: flex-start;
  padding-right: 20px;
}

.searcher-box {
  box-sizing: border-box;
  flex: 0 1 400px;
  min-width: 240px;
  max-width: 400px;
}

.searcher {
  box-sizing: border-box;
  width: 100%;
}

.search-actions {
  box-sizing: border-box;
  display: flex;
  flex: 0 0 auto;
  gap: 10px;
  align-items: center;
  padding-left: 5px;
}
</style>
