<template>
  <UModal v-model:open="open" title="编辑标品">
    <template #body>
      <UForm
        @submit="onSubmit"
        :state="biddingItemEditState"
        :schema="biddingItemEditSchema"
      >
        <UFormField label="起拍价" name="startPrice">
          <UInput
            v-model.number="biddingItemEditState.startPrice"
            type="number"
          />
        </UFormField>

        <UFormField label="备注" name="remarks">
          <UTextarea v-model="biddingItemEditState.remarks" />
        </UFormField>

        <UButton type="submit" label="保存" color="primary" class="mt-4" />
      </UForm>
    </template>
  </UModal>
</template>

<script lang="ts" setup>
import type { FormSubmitEvent } from "@nuxt/ui";
import * as z from "zod";

const biddingItemEditForm = ref();
const currentId = ref<number>(0);
const open = ref<boolean>(false);

const toast = useToast();

const { biddingItems, editBiddingItem } = useBiddingItems();

const biddingItemEditSchema = z.object({
  startPrice: z.number().min(0, "起拍价不能少于 RM 0").default(0),
  remarks: z.string().optional(),
});

type BiddingItemEditSchema = z.output<typeof biddingItemEditSchema>;

const biddingItemEditState = reactive<BiddingItem & BiddingItemEditSchema>({
  id: 0,
  name: "",
  imageUrl: "",
  startPrice: 0,
  remarks: "",
});

const openModal = (biddingItem: BiddingItem) => {
  Object.assign(biddingItemEditState, biddingItem); // 👈 一次性复制所有字段
  currentId.value = biddingItem.id;
  open.value = true;
};

const onSubmit = async (event: FormSubmitEvent<BiddingItemEditSchema>) => {
  const updatedItem: BiddingItem = {
    ...biddingItemEditState, // 👈 这里直接复用已有字段
    startPrice: event.data.startPrice,
    remarks: event.data.remarks ?? "",
  };

  editBiddingItem(updatedItem);
  toast.add({
    title: "已保存修改",
    description: `${updatedItem.name} 的信息已更新`,
    color: "success",
  });

  open.value = false;
};

defineExpose({ openModal });
</script>

<style></style>
