<script setup lang="ts">
/**
 * 文件职责：堂食区域新增/编辑抽屉。
 * 1. 展示区域基础字段。
 * 2. 通过回调更新父级状态并提交。
 */
import type { DineInAreaFormState } from '#/views/store/dine-in/types';

import { Button, Drawer, Input, InputNumber } from 'ant-design-vue';

interface Props {
  form: DineInAreaFormState;
  isSaving: boolean;
  onSetDescription: (value: string) => void;
  onSetName: (value: string) => void;
  onSetSort: (value: number) => void;
  open: boolean;
  submitText: string;
  title: string;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (event: 'submit'): void;
  (event: 'update:open', value: boolean): void;
}>();

function readInputValue(event: Event) {
  const target = event.target as HTMLInputElement | HTMLTextAreaElement | null;
  return target?.value ?? '';
}

function toNumber(value: null | number | string, fallback = 1) {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : fallback;
}
</script>

<template>
  <Drawer
    class="dinein-area-drawer-wrap"
    :open="props.open"
    :title="props.title"
    :width="460"
    :mask-closable="true"
    @update:open="(value) => emit('update:open', value)"
  >
    <div class="drawer-form-block">
      <label class="drawer-form-label required">区域名称</label>
      <Input
        :value="props.form.name"
        :maxlength="20"
        placeholder="如：大厅、包间、露台"
        @input="(event) => props.onSetName(readInputValue(event))"
      />
    </div>

    <div class="drawer-form-block">
      <label class="drawer-form-label">区域描述</label>
      <Input.TextArea
        :value="props.form.description"
        :maxlength="120"
        :rows="3"
        placeholder="可选，如：主要用餐区域，可容纳约48人"
        @input="(event) => props.onSetDescription(readInputValue(event))"
      />
    </div>

    <div class="drawer-form-block">
      <label class="drawer-form-label">排序</label>
      <div class="drawer-input-with-unit">
        <InputNumber
          :value="props.form.sort"
          :min="1"
          :precision="0"
          :controls="false"
          class="drawer-input"
          @update:value="(value) => props.onSetSort(toNumber(value, 1))"
        />
        <span class="drawer-form-hint">数字越小越靠前</span>
      </div>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <Button @click="emit('update:open', false)">取消</Button>
        <Button
          type="primary"
          :loading="props.isSaving"
          @click="emit('submit')"
        >
          {{ props.form.id ? '保存修改' : '新增并保存' }}
        </Button>
      </div>
    </template>
  </Drawer>
</template>
