<template>
  <button
    v-if="visible"
    type="button"
    class="vm-crud-toolbar__btn is-primary"
    @click="onClick"
  >
    <i class="ri-add-line" />
    {{ crudLabel('add', crud.dict.label) }}
  </button>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useCrud } from './useCrud'
import { crudLabel } from './style'

defineOptions({ name: 'vm-add-btn' })

const props = withDefaults(
  defineProps<{
    /** 打开新增表单时写入的默认值 */
    data?: Record<string, unknown> | (() => Record<string, unknown>)
    /** 回收站中隐藏（默认 true） */
    hideInTrash?: boolean
  }>(),
  {
    hideInTrash: true,
  },
)

const crud = useCrud()

/** 权限来自 service._permission / useCrud.permission */
const visible = computed(() => {
  if (!crud.getPermission('add')) return false
  if (props.hideInTrash && crud.trashMode.value === 'onlyTrashed') return false
  return true
})

function onClick() {
  const raw = props.data
  const defaults = typeof raw === 'function' ? raw() : raw
  crud.rowAdd(defaults && Object.keys(defaults).length ? defaults : {})
}
</script>

<style lang="scss" scoped>
.vm-crud-toolbar__btn {
  display: inline-flex;
  height: 36px;
  align-items: center;
  gap: 4px;
  padding: 0 14px;
  border: none;
  border-radius: 12px;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;

  &.is-primary {
    background: var(--brand);
    color: #fff;

    &:hover {
      background: var(--brand-deep);
    }
  }
}
</style>
