<script setup lang="ts">
import type { Dayjs } from 'dayjs';

/**
 * 文件职责：商品添加/编辑抽屉。
 * 1. 展示商品核心信息与上架方式表单。
 * 2. 通过回调更新父级状态并触发提交。
 */
import type { ProductEditorFormState } from '../types';

import {
  Button,
  DatePicker,
  Drawer,
  Input,
  InputNumber,
  Radio,
  Select,
} from 'ant-design-vue';
import dayjs from 'dayjs';

interface CategoryOption {
  label: string;
  value: string;
}

interface Props {
  categoryOptions: CategoryOption[];
  form: ProductEditorFormState;
  isSaving: boolean;
  onSetCategoryId: (value: string) => void;
  onSetDescription: (value: string) => void;
  onSetKind: (value: 'combo' | 'single') => void;
  onSetName: (value: string) => void;
  onSetOriginalPrice: (value: null | number) => void;
  onSetPrice: (value: number) => void;
  onSetShelfMode: (value: 'draft' | 'now' | 'scheduled') => void;
  onSetStock: (value: number) => void;
  onSetSubtitle: (value: string) => void;
  onSetTagsText: (value: string) => void;
  onSetTimedOnShelfAt: (value: string) => void;
  open: boolean;
  showDetailLink: boolean;
  submitText: string;
  title: string;
}

const props = defineProps<Props>();

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

/** 数值输入归一化。 */
function toNumber(value: null | number | string, fallback = 0) {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : fallback;
}

/** 解析商品类型。 */
function handleKindChange(value: unknown) {
  if (value === 'combo' || value === 'single') {
    props.onSetKind(value);
  }
}

/** 解析分类选择。 */
function handleCategoryChange(value: unknown) {
  if (typeof value === 'number' || typeof value === 'string') {
    props.onSetCategoryId(String(value));
  }
}

/** 解析上架方式。 */
function handleShelfModeChange(value: unknown) {
  if (value === 'draft' || value === 'now' || value === 'scheduled') {
    props.onSetShelfMode(value);
  }
}

/** 解析定时上架时间。 */
function handleTimedOnShelfAtChange(value: Dayjs | null | undefined) {
  if (!value || !dayjs(value).isValid()) {
    props.onSetTimedOnShelfAt('');
    return;
  }
  props.onSetTimedOnShelfAt(dayjs(value).format('YYYY-MM-DD HH:mm:ss'));
}
</script>

<template>
  <Drawer
    class="product-editor-drawer"
    :open="props.open"
    :title="props.title"
    :width="560"
    :mask-closable="true"
    @update:open="(value) => emit('update:open', value)"
  >
    <div class="product-drawer-section">
      <div class="product-drawer-section-title">商品类型</div>
      <Radio.Group
        :value="props.form.kind"
        class="product-kind-radio-group"
        @update:value="(value) => handleKindChange(value)"
      >
        <Radio.Button value="single">单品</Radio.Button>
        <Radio.Button value="combo">套餐</Radio.Button>
      </Radio.Group>
    </div>

    <div class="product-drawer-section">
      <div class="product-drawer-section-title">商品信息</div>
      <div class="drawer-form-grid">
        <div class="drawer-form-item full">
          <label class="drawer-form-label required">商品名称</label>
          <Input
            :value="props.form.name"
            placeholder="请输入商品名称"
            @update:value="(value) => props.onSetName(String(value || ''))"
          />
        </div>

        <div class="drawer-form-item">
          <label class="drawer-form-label required">分类</label>
          <Select
            :value="props.form.categoryId"
            :options="props.categoryOptions"
            placeholder="请选择分类"
            @update:value="(value) => handleCategoryChange(value)"
          />
        </div>

        <div class="drawer-form-item">
          <label class="drawer-form-label">副标题</label>
          <Input
            :value="props.form.subtitle"
            placeholder="选填"
            @update:value="(value) => props.onSetSubtitle(String(value || ''))"
          />
        </div>

        <div class="drawer-form-item full">
          <label class="drawer-form-label">商品简介</label>
          <Input.TextArea
            :value="props.form.description"
            :rows="3"
            :maxlength="120"
            placeholder="请输入商品简介"
            @update:value="
              (value) => props.onSetDescription(String(value || ''))
            "
          />
        </div>
      </div>
    </div>

    <div class="product-drawer-section">
      <div class="product-drawer-section-title">价格与库存</div>
      <div class="drawer-form-grid">
        <div class="drawer-form-item">
          <label class="drawer-form-label required">售价</label>
          <InputNumber
            :value="props.form.price"
            class="full-width"
            :min="0"
            :precision="2"
            :step="1"
            :controls="false"
            @update:value="
              (value) => props.onSetPrice(toNumber(value, props.form.price))
            "
          />
        </div>

        <div class="drawer-form-item">
          <label class="drawer-form-label">原价</label>
          <InputNumber
            :value="props.form.originalPrice ?? undefined"
            class="full-width"
            :min="0"
            :precision="2"
            :step="1"
            :controls="false"
            placeholder="选填"
            @update:value="
              (value) =>
                props.onSetOriginalPrice(
                  value === null || value === undefined
                    ? null
                    : toNumber(value, 0),
                )
            "
          />
        </div>

        <div class="drawer-form-item">
          <label class="drawer-form-label required">库存</label>
          <InputNumber
            :value="props.form.stock"
            class="full-width"
            :min="0"
            :precision="0"
            :step="1"
            :controls="false"
            @update:value="
              (value) => props.onSetStock(toNumber(value, props.form.stock))
            "
          />
        </div>

        <div class="drawer-form-item">
          <label class="drawer-form-label">标签</label>
          <Input
            :value="props.form.tagsText"
            placeholder="多个标签用英文逗号分隔"
            @update:value="(value) => props.onSetTagsText(String(value || ''))"
          />
        </div>
      </div>
    </div>

    <div class="product-drawer-section">
      <div class="product-drawer-section-title">上架方式</div>
      <Radio.Group
        :value="props.form.shelfMode"
        class="product-shelf-radio-group"
        @update:value="(value) => handleShelfModeChange(value)"
      >
        <Radio class="shelf-radio-item" value="draft">存为草稿</Radio>
        <Radio class="shelf-radio-item" value="now">立即上架</Radio>
        <Radio class="shelf-radio-item" value="scheduled">定时上架</Radio>
      </Radio.Group>

      <div v-if="props.form.shelfMode === 'scheduled'" class="shelf-time-row">
        <DatePicker
          :value="
            props.form.timedOnShelfAt
              ? dayjs(props.form.timedOnShelfAt)
              : undefined
          "
          class="full-width"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择上架时间"
          @update:value="
            (value) =>
              handleTimedOnShelfAtChange(value as Dayjs | null | undefined)
          "
        />
      </div>
    </div>

    <template #footer>
      <div class="product-drawer-footer">
        <Button v-if="props.showDetailLink" type="link" @click="emit('detail')">
          前往详情页
        </Button>
        <div class="product-drawer-footer-right">
          <Button @click="emit('update:open', false)">取消</Button>
          <Button
            type="primary"
            :loading="props.isSaving"
            @click="emit('submit')"
          >
            {{ props.submitText }}
          </Button>
        </div>
      </div>
    </template>
  </Drawer>
</template>
