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

import type { ProductEditorFormState } from '../types';

/**
 * 文件职责：商品添加/编辑抽屉。
 * 1. 展示商品基础字段、套餐分组与上架方式。
 * 2. 通过回调更新父级状态并触发提交。
 */
import type { ProductPickerItemDto } from '#/api/product';

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

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

interface Props {
  categoryOptions: CategoryOption[];
  comboPickerKeyword: string;
  comboPickerLoading: boolean;
  comboPickerOpen: boolean;
  comboPickerProducts: ProductPickerItemDto[];
  comboPickerSelectedIds: string[];
  form: ProductEditorFormState;
  isSaving: boolean;
  onAddComboGroup: () => void;
  onOpenComboGroupPicker: (groupIndex: number) => void;
  onRemoveComboGroup: (groupIndex: number) => void;
  onRemoveComboItem: (groupIndex: number, itemIndex: number) => void;
  onSearchComboPicker: () => void;
  onSetCategoryId: (value: string) => void;
  onSetComboGroupMaxSelect: (groupIndex: number, value: number) => void;
  onSetComboGroupMinSelect: (groupIndex: number, value: number) => void;
  onSetComboGroupName: (groupIndex: number, value: string) => void;
  onSetComboItemQuantity: (
    groupIndex: number,
    itemIndex: number,
    value: number,
  ) => void;
  onSetComboPickerKeyword: (value: string) => void;
  onSetComboPickerOpen: (value: boolean) => 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;
  onSetTimedOnShelfAt: (value: string) => void;
  onSubmitComboPicker: () => void;
  onToggleComboPickerProduct: (productId: 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 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'));
}

function setKind(value: 'combo' | 'single') {
  props.onSetKind(value);
}

function setComboPickerOpen(value: boolean) {
  props.onSetComboPickerOpen(value);
}
</script>

<template>
  <Drawer
    class="product-editor-drawer"
    :open="props.open"
    :title="props.title"
    width="40%"
    :mask-closable="true"
    @update:open="(value) => emit('update:open', value)"
  >
    <div class="product-drawer-section">
      <div class="product-drawer-section-title">商品类型</div>
      <div class="product-kind-pill-group">
        <button
          type="button"
          class="product-kind-pill"
          :class="{ active: props.form.kind === 'single' }"
          @click="setKind('single')"
        >
          单品
        </button>
        <button
          type="button"
          class="product-kind-pill"
          :class="{ active: props.form.kind === 'combo' }"
          @click="setKind('combo')"
        >
          套餐
        </button>
      </div>
      <div class="drawer-field-hint">
        套餐由多个商品组合而成，顾客按分组选择
      </div>
    </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 full">
          <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 required">分类</label>
          <Select
            :value="props.form.categoryId"
            class="full-width"
            :options="props.categoryOptions"
            placeholder="请选择分类"
            @update:value="(value) => handleCategoryChange(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 price-stock-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>
    </div>

    <div v-if="props.form.kind === 'combo'" class="product-drawer-section">
      <div class="product-drawer-section-title">套餐分组</div>
      <div class="drawer-field-hint combo-hint">
        每个分组可包含多个商品，顾客按分组选择
      </div>

      <div class="combo-group-list">
        <div
          v-for="(group, groupIndex) in props.form.comboGroups"
          :key="`combo-group-${groupIndex}`"
          class="combo-group-card"
        >
          <div class="combo-group-head">
            <Input
              :value="group.name"
              placeholder="请输入分组名称"
              @update:value="
                (value) =>
                  props.onSetComboGroupName(groupIndex, String(value || ''))
              "
            />

            <div class="combo-group-range">
              <span>最少</span>
              <InputNumber
                :value="group.minSelect"
                :min="1"
                :precision="0"
                :controls="false"
                class="combo-range-input"
                @update:value="
                  (value) =>
                    props.onSetComboGroupMinSelect(
                      groupIndex,
                      toNumber(value, group.minSelect),
                    )
                "
              />
              <span>最多</span>
              <InputNumber
                :value="group.maxSelect"
                :min="1"
                :precision="0"
                :controls="false"
                class="combo-range-input"
                @update:value="
                  (value) =>
                    props.onSetComboGroupMaxSelect(
                      groupIndex,
                      toNumber(value, group.maxSelect),
                    )
                "
              />
              <span>份</span>
            </div>

            <Button
              type="text"
              danger
              class="combo-remove-group"
              @click="props.onRemoveComboGroup(groupIndex)"
            >
              删除
            </Button>
          </div>

          <div class="combo-item-list">
            <div
              v-for="(item, itemIndex) in group.items"
              :key="`combo-item-${groupIndex}-${item.productId}`"
              class="combo-item-row"
            >
              <span class="combo-item-name">{{ item.productName }}</span>
              <div class="combo-item-actions">
                <span class="combo-item-multiplier">×</span>
                <InputNumber
                  :value="item.quantity"
                  :min="1"
                  :precision="0"
                  :controls="false"
                  class="combo-quantity-input"
                  @update:value="
                    (value) =>
                      props.onSetComboItemQuantity(
                        groupIndex,
                        itemIndex,
                        toNumber(value, item.quantity),
                      )
                  "
                />
                <Button
                  type="text"
                  class="combo-remove-item"
                  @click="props.onRemoveComboItem(groupIndex, itemIndex)"
                >
                  移除
                </Button>
              </div>
            </div>
            <div v-if="group.items.length === 0" class="combo-item-empty">
              暂无商品，请点击下方“添加商品”
            </div>
          </div>

          <Button
            type="link"
            class="combo-add-product"
            @click="props.onOpenComboGroupPicker(groupIndex)"
          >
            + 添加商品
          </Button>
        </div>

        <button
          type="button"
          class="combo-add-group"
          @click="props.onAddComboGroup"
        >
          + 添加分组
        </button>
      </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>

  <Modal
    title="添加商品到分组"
    :open="props.comboPickerOpen"
    ok-text="确认添加"
    cancel-text="取消"
    :confirm-loading="false"
    :ok-button-props="{ disabled: props.comboPickerSelectedIds.length === 0 }"
    @ok="props.onSubmitComboPicker"
    @cancel="setComboPickerOpen(false)"
  >
    <div class="combo-picker-search">
      <Input
        :value="props.comboPickerKeyword"
        allow-clear
        placeholder="搜索商品名称/SPU"
        @update:value="
          (value) => props.onSetComboPickerKeyword(String(value || ''))
        "
        @press-enter="props.onSearchComboPicker"
      />
      <Button @click="props.onSearchComboPicker">搜索</Button>
    </div>

    <div class="combo-picker-list">
      <div v-if="props.comboPickerLoading" class="combo-picker-empty">
        加载中...
      </div>
      <div
        v-else-if="props.comboPickerProducts.length === 0"
        class="combo-picker-empty"
      >
        暂无可选商品
      </div>
      <label
        v-for="product in props.comboPickerProducts"
        v-else
        :key="`combo-picker-${product.id}`"
        class="combo-picker-item"
      >
        <input
          type="checkbox"
          :checked="props.comboPickerSelectedIds.includes(product.id)"
          @change="props.onToggleComboPickerProduct(product.id)"
        />
        <span class="name">{{ product.name }}</span>
        <span class="spu">{{ product.spuCode }}</span>
        <span class="price">¥{{ product.price.toFixed(2) }}</span>
      </label>
    </div>
  </Modal>
</template>
