<template>
  <div class="vm-adv-search">
    <Button size="sm" variant="outline" class="h-8" @click="open = true">
      <i class="ri-filter-3-line" />
      {{ crudLabel('advSearch', crud.dict.label) }}
    </Button>
    <Dialog :open="open" @update:open="onOpenChange">
      <DialogContent
        shell="crud"
        class="vm-adv-search__dialog"
        @pointer-down-outside="preventDialogOutsideClose"
        @focus-outside="preventDialogOutsideClose"
        @interact-outside="preventDialogOutsideClose"
      >
        <DialogHeader class="vm-crud-shell__head">
          <DialogTitle class="vm-crud-shell__title">
            {{ crudLabel('advSearch', crud.dict.label) }}
          </DialogTitle>
        </DialogHeader>
        <div class="vm-crud-shell__body">
          <vm-form v-model="form" :items="items" />
        </div>
        <DialogFooter class="vm-crud-shell__foot">
          <button
            type="button"
            class="vm-crud-shell__btn is-ghost"
            @click="reset"
          >
            {{ crudLabel('reset', crud.dict.label) }}
          </button>
          <button
            type="button"
            class="vm-crud-shell__btn is-primary"
            @click="search"
          >
            {{ crudLabel('search', crud.dict.label) }}
          </button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { preventDialogOutsideClose } from '../lib/dialog-float'
import { useCrud } from './useCrud'
import { crudLabel } from './style'
import type { CrudFormItem } from '../../../typings/admin/comm/crud'
defineOptions({ name: 'vm-adv-search' })

const props = withDefaults(
  defineProps<{
    items?: CrudFormItem[]
  }>(),
  { items: () => [] },
)

const crud = useCrud()
const open = ref(false)
const form = ref<Record<string, unknown>>({})

function onOpenChange(v: boolean) {
  open.value = v
}

function search() {
  const payload: Record<string, unknown> = {}
  for (const it of props.items) {
    const v = form.value[it.prop]
    if (v !== '' && v != null) payload[it.prop] = v
  }
  crud.setParams(payload, true)
  open.value = false
}

function reset() {
  const next: Record<string, unknown> = {}
  for (const it of props.items) next[it.prop] = ''
  form.value = next
  crud.resetParams()
}
</script>
