<template>
  <div class="bg-filtrate">
    <span class="bg-filtrate-text">{{ name }}：</span>
    <ul class="bg-filtrate-list">
      <li
        v-for="(item, index) in fullOptions"
        :class="{ current: selection.indexOf(item.value) > -1 }"
        :key="'li_' + index"
        @click="selectAction(item)">
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { computed } from "vue";

const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: "",
  },
  isCalc: {
    type: Boolean,
    default: false,
  },
  name: {
    type: String,
    default: "",
  },
  options: {
    type: Array,
    default: () => [],
  },
  optionName: {
    type: String,
    default: "name",
  },
  optionValue: {
    type: String,
    default: "value",
  },
  multiple: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:modelValue"]);

const fullOptions = computed(() => {
  return [
    {
      name: "全部",
      value: "",
    },
    ...props.options.map((item) => {
      return {
        name: item[props.optionName],
        value: item[props.optionValue] + "",
      };
    }),
  ];
});
const selection = computed(() => {
  let value = props.modelValue + "";

  return value.split(",");
});

const selectAction = ({ value, name, sub_cate }) => {
  if (value && props.multiple) {
    let selection = [...props.selection].filter((v) => v !== "");
    let index = selection.findIndex((v) => v === value);

    if (index > -1) {
      selection.splice(index, 1);
    } else {
      selection.push(value);
    }

    emit("update:modelValue", selection.join(","));
  } else {
    emit("update:modelValue", value, name);
  }
};
</script>
