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

/**
 * 文件职责：商品沽清抽屉。
 * 1. 配置沽清方式、恢复时间、可售数量与通知选项。
 * 2. 透出提交流程与关闭事件。
 */
import type { ProductSoldoutFormState } from '../types';

import type { ProductListItemDto, ProductSoldoutMode } from '#/api/product';

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

import { resolveStatusMeta } from '../composables/product-list-page/helpers';

interface Props {
  form: ProductSoldoutFormState;
  isSaving: boolean;
  onSetMode: (value: ProductSoldoutMode) => void;
  onSetNotifyManager: (value: boolean) => void;
  onSetReason: (value: string) => void;
  onSetRecoverAt: (value: string) => void;
  onSetRemainStock: (value: number) => void;
  onSetSyncToPlatform: (value: boolean) => void;
  open: boolean;
  product: null | ProductListItemDto;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (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 handleModeChange(value: unknown) {
  if (value === 'today' || value === 'timed' || value === 'permanent') {
    props.onSetMode(value);
  }
}

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

<template>
  <Drawer
    class="product-soldout-drawer"
    :open="props.open"
    title="商品沽清"
    :width="460"
    :mask-closable="true"
    @update:open="(value) => emit('update:open', value)"
  >
    <div v-if="props.product" class="product-soldout-card">
      <div class="product-quick-cover">
        {{ props.product.name.slice(0, 1) }}
      </div>
      <div class="product-quick-meta">
        <div class="name">{{ props.product.name }}</div>
        <div class="sub">{{ props.product.spuCode }}</div>
      </div>
      <span
        class="product-status-pill"
        :class="resolveStatusMeta(props.product.status).badgeClass"
      >
        {{ resolveStatusMeta(props.product.status).label }}
      </span>
    </div>

    <div class="product-drawer-section">
      <div class="product-drawer-section-title">沽清方式</div>
      <Radio.Group
        :value="props.form.mode"
        class="soldout-mode-group"
        @update:value="(value) => handleModeChange(value)"
      >
        <Radio class="soldout-mode-item" value="today">今日沽清</Radio>
        <Radio class="soldout-mode-item" value="timed">定时沽清</Radio>
        <Radio class="soldout-mode-item" value="permanent">永久沽清</Radio>
      </Radio.Group>

      <DatePicker
        v-if="props.form.mode === 'timed'"
        :value="props.form.recoverAt ? dayjs(props.form.recoverAt) : undefined"
        class="full-width"
        show-time
        format="YYYY-MM-DD HH:mm:ss"
        placeholder="请选择恢复时间"
        @update:value="
          (value) => handleRecoverAtChange(value as Dayjs | null | undefined)
        "
      />
    </div>

    <div class="product-drawer-section">
      <div class="product-drawer-section-title">剩余可售</div>
      <div class="drawer-form-item compact">
        <InputNumber
          :value="props.form.remainStock"
          :min="0"
          :precision="0"
          :step="1"
          :controls="false"
          class="stock-input"
          @update:value="
            (value) =>
              props.onSetRemainStock(toNumber(value, props.form.remainStock))
          "
        />
        <span class="unit">份</span>
      </div>
      <div class="hint">设为 0 表示完全沽清，不再接单</div>
    </div>

    <div class="product-drawer-section">
      <div class="product-drawer-section-title">沽清原因</div>
      <Input.TextArea
        :value="props.form.reason"
        :rows="3"
        :maxlength="120"
        placeholder="选填，如：食材用完、设备检修等"
        @update:value="(value) => props.onSetReason(String(value || ''))"
      />
    </div>

    <div class="product-drawer-section">
      <div class="product-drawer-section-title">通知设置</div>
      <div class="switch-row">
        <Switch
          :checked="props.form.syncToPlatform"
          @update:checked="(value) => props.onSetSyncToPlatform(Boolean(value))"
        />
        <span>同步通知外卖平台</span>
      </div>
      <div class="switch-row">
        <Switch
          :checked="props.form.notifyManager"
          @update:checked="(value) => props.onSetNotifyManager(Boolean(value))"
        />
        <span>通知店长（短信提醒）</span>
      </div>
    </div>

    <template #footer>
      <div class="product-drawer-footer">
        <div class="product-drawer-footer-right">
          <Button @click="emit('update:open', false)">取消</Button>
          <Button
            danger
            type="primary"
            :loading="props.isSaving"
            @click="emit('submit')"
          >
            确认沽清
          </Button>
        </div>
      </div>
    </template>
  </Drawer>
</template>
