<template>
  <div class="bc-search" data-weiling-mobile-ui-bc-search>
    <WlPopover
      overlay
      :offset="[0, 10]"
      v-model="popOverVisible"
      placement="bottom-start"
      :actions="popOverActions"
      @select="onPopOverSelect"
    >
      <template v-slot:reference>
        <div class="dropdown">
          <div class="text">{{ popOverValue }}</div>
          <div class="icon"></div>
        </div>
      </template>
    </WlPopover>
    <div class="search-wrap">
      <WlSearch
        v-model="searchValue"
        :needBorder="false"
        :placeholder="placeholder"
        @onChange="onSearchChange"
        @onClear="onClear"
      />
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: "BCSearch",
};
</script>

<script lang="ts" setup>
import { PopoverAction } from "vant";
import { watchEffect, ref, toRaw } from "vue";
import WlSearch from "@mobileUI/components/WlSearch/src/index.vue";
import WlPopover from "@mobileUI/components/WlPopover/src/index.vue";

type Props = {
  filterOptions?: PopoverAction[];
  groupBtnVisible?: boolean;
  placeholder?: string;
};

const props = withDefaults(defineProps<Props>(), {
  filterOptions: () => [],
  groupBtnVisible: false,
  placeholder: "",
});

const searchValue = ref("");
const popOverValue = ref("全部");
const popOverVisible = ref(false);
const popOverActions = ref(null);
const emit = defineEmits<{
  (e: "onChange", val: string);
  (e: "onMaterialTypeChange", val: PopoverAction);
  (e: "onClear");
}>();
const onSearchChange = (val) => emit("onChange", val);
const onClear = () => {
  emit("onClear");
};

const onPopOverSelect = (val: PopoverAction) => {
  popOverActions.value.forEach((res) => (res.className = ""));
  const idx = popOverActions.value.findIndex((res) => res.value === val.value);
  popOverActions.value[idx].className = "popover-active";
  popOverValue.value = val.text;
  emit("onMaterialTypeChange", toRaw(val));
};

watchEffect(() => {
  //给第一个添加默认选中的样式
  popOverActions.value = props.filterOptions.reduce((acc, item, index) => {
    if (index === 0) {
      acc.push({ ...item, className: "popover-active" });
    } else {
      acc.push(item);
    }
    return acc;
  }, []);
});
</script>

<style lang="scss">
.bc-search[data-weiling-mobile-ui-bc-search] {
  @extend %flex-middle;
  background-color: #f6f6f6;
  border-radius: j(10);
  overflow: hidden;

  .dropdown {
    cursor: pointer;
    padding-left: j(10);
    @extend %flex-middle;
    @include halfBorder("right", #e3e3e3);

    .text {
      font-weight: 500;
      font-size: 15px;
      color: var(--wl-text-color-secondary-2);
    }

    .icon {
      display: inline-block;
      margin: 0 j(12) 0 j(6);
      @include arrow("down", var(--wl-text-color-secondary-2));
    }
  }

  .search-wrap {
    flex: 1;
    width: 100%;
  }
}
</style>
