<template>
  <div class="flex flex-row gap-2">
    <p class="w-14 min-w-14 pt-2">SELECT</p>
    <div class="flex flex-row flex-wrap gap-2 items-center">
      <p
        class="rounded-md shadow-sm relative block w-fit px-3 py-2 border border-gray-300 text-gray-900 rounded-b-md sm:text-sm"
        :class="value == '*' ? 'border-gray-600 bg-gray-200' : ''"
        @click="value = '*'"
      >
        *
      </p>
      <p
        v-for="col in columns"
        :key="col.column"
        class="rounded-md shadow-sm relative block w-fit px-3 py-2 border border-gray-300 text-gray-900 rounded-b-md sm:text-sm"
        :class="value.includes(col.column) ? 'border-gray-600 bg-gray-200' : ''"
        @click="value = [col.column]"
      >
        {{ foreignColumns?.includes(col.column) ? "FK:" : "" }} {{ col.column }}:{{ col.type }}
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, type PropType } from "vue";
import { mapActions, mapState } from "pinia";
import { useQueryBuilderStore } from "@/stores/admin/club/queryBuilder";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    table: {
      type: String,
      default: "",
    },
    modelValue: {
      type: [Array, String] as PropType<"*" | Array<string>>,
      default: "*",
    },
  },
  emits: ["update:model-value"],
  data() {
    return {};
  },
  computed: {
    ...mapState(useQueryBuilderStore, ["tableMetas"]),
    activeTable() {
      return this.tableMetas.find((tm) => tm.tableName == this.table);
    },
    columns() {
      return this.activeTable?.columns?.filter((c) => !this.foreignColumns?.includes(c.column));
    },
    foreignColumns() {
      return this.activeTable?.relations.map((r) => r.column);
    },
    value: {
      get() {
        return this.modelValue;
      },
      set(val: "*" | Array<string>) {
        let tmp = this.modelValue;
        if (val == "*") {
          tmp = val;
        } else {
          if (Array.isArray(tmp)) {
            let index = tmp.findIndex((t) => t == val[0]);
            if (index == -1) tmp.push(val[0]);
            else tmp.splice(index, 1);
          } else {
            tmp = val;
          }
        }
        if (tmp != "*" && tmp.length == 0) {
          tmp = "*";
        }
        this.$emit("update:model-value", tmp);
      },
    },
  },
});
</script>
