<script setup lang="ts">
/**
 * 文件职责：商品列表主区域。
 * 1. 根据视图模式渲染卡片或列表。
 * 2. 透出勾选、分页、编辑、详情、删除、状态动作事件。
 */
import type { ProductListItemDto, ProductStatus } from '#/api/product';
import type {
  ProductPaginationChangePayload,
  ProductViewMode,
} from '#/views/product/list/types';

import {
  Checkbox,
  Dropdown,
  Empty,
  Menu,
  Pagination,
  Popconfirm,
  Spin,
  Tag,
} from 'ant-design-vue';

import {
  formatCurrency,
  formatStockText,
  resolveStatusMeta,
  resolveStockClass,
} from '../composables/product-list-page/helpers';

interface Props {
  allChecked: boolean;
  indeterminate: boolean;
  isLoading: boolean;
  page: number;
  pageSize: number;
  pageSizeOptions: string[];
  rows: ProductListItemDto[];
  selectedProductIds: string[];
  total: number;
  viewMode: ProductViewMode;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (
    event: 'changeStatus',
    payload: { item: ProductListItemDto; status: ProductStatus },
  ): void;
  (event: 'delete', item: ProductListItemDto): void;
  (event: 'detail', item: ProductListItemDto): void;
  (event: 'edit', item: ProductListItemDto): void;
  (event: 'quickEdit', item: ProductListItemDto): void;
  (event: 'pageChange', payload: ProductPaginationChangePayload): void;
  (event: 'soldout', item: ProductListItemDto): void;
  (
    event: 'toggleSelect',
    payload: { checked: boolean; productId: string },
  ): void;
  (event: 'toggleSelectAll', checked: boolean): void;
}>();

/** 当前商品是否被勾选。 */
function isChecked(productId: string) {
  return props.selectedProductIds.includes(productId);
}

/** 解析“更多”动作菜单。 */
function getMoreActionOptions(item: ProductListItemDto) {
  const actions: Array<{ key: string; label: string }> = [
    { key: 'quick_edit', label: '快速编辑' },
  ];
  if (item.status === 'on_sale') {
    actions.push({ key: 'off', label: '下架' });
  } else {
    actions.push({ key: 'on', label: '上架' });
  }
  actions.push({ key: 'soldout', label: '沽清' });
  return actions;
}

/** 执行“更多”菜单动作。 */
function handleMoreAction(
  item: ProductListItemDto,
  payload: { key: number | string },
) {
  const key = String(payload.key);
  if (key === 'quick_edit') {
    emit('quickEdit', item);
    return;
  }
  if (key === 'on') {
    emit('changeStatus', { item, status: 'on_sale' });
    return;
  }
  if (key === 'off') {
    emit('changeStatus', { item, status: 'off_shelf' });
    return;
  }
  if (key === 'soldout') {
    emit('soldout', item);
  }
}

/** 解析商品展示图。 */
function resolveImageUrl(item: ProductListItemDto) {
  return String(item.imageUrl || '').trim();
}

/** 解析图片占位首字。 */
function resolveImageFallbackText(item: ProductListItemDto) {
  const name = String(item.name || '').trim();
  return name ? name.slice(0, 1) : '?';
}

/** 处理单项勾选变化。 */
function handleSingleCheck(productId: string, event: unknown) {
  const checked = Boolean(
    (event as null | { target?: { checked?: boolean } })?.target?.checked,
  );
  emit('toggleSelect', { productId, checked });
}

/** 处理全选变化。 */
function handleCheckAll(event: unknown) {
  const checked = Boolean(
    (event as null | { target?: { checked?: boolean } })?.target?.checked,
  );
  emit('toggleSelectAll', checked);
}

/** 处理分页变化。 */
function handlePageChange(page: number, pageSize: number) {
  emit('pageChange', { page, pageSize });
}

/** 处理分页尺寸变化。 */
function handlePageSizeChange(current: number, size: number) {
  emit('pageChange', { page: current, pageSize: size });
}
</script>

<template>
  <Spin :spinning="props.isLoading">
    <Empty v-if="props.rows.length === 0" description="暂无商品，请先添加" />

    <div v-else class="product-list-section">
      <div v-if="props.viewMode === 'card'" class="product-card-grid">
        <article
          v-for="item in props.rows"
          :key="item.id"
          class="product-card-item"
          :class="{
            'is-soldout': item.status === 'sold_out',
            'is-offshelf': item.status === 'off_shelf',
          }"
        >
          <div
            class="product-card-status-ribbon"
            :style="{ background: resolveStatusMeta(item.status).color }"
          >
            {{ resolveStatusMeta(item.status).label }}
          </div>

          <Checkbox
            class="product-card-check"
            :checked="isChecked(item.id)"
            @change="(event) => handleSingleCheck(item.id, event)"
          />

          <div class="product-card-cover">
            <img
              v-if="resolveImageUrl(item)"
              :src="resolveImageUrl(item)"
              :alt="item.name"
              class="product-cover-image"
            />
            <span v-else>{{ resolveImageFallbackText(item) }}</span>
          </div>

          <div class="product-card-body">
            <div class="product-card-name">{{ item.name }}</div>
            <div class="product-card-subtitle">{{ item.subtitle || '--' }}</div>
            <div class="product-card-spu">{{ item.spuCode }}</div>

            <div class="product-card-price-row">
              <span class="price-now">{{ formatCurrency(item.price) }}</span>
              <span v-if="item.originalPrice" class="price-old">
                {{ formatCurrency(item.originalPrice) }}
              </span>
            </div>

            <div class="product-card-meta">
              <span
                :class="
                  item.kind === 'combo' ? '' : resolveStockClass(item.stock)
                "
              >
                {{ item.kind === 'combo' ? '—' : formatStockText(item.stock) }}
              </span>
              <span>月销 {{ item.salesMonthly }}</span>
            </div>

            <div class="product-card-tags">
              <Tag v-for="tag in item.tags" :key="`${item.id}-${tag}`">
                {{ tag }}
              </Tag>
            </div>
          </div>

          <div class="product-card-footer">
            <button
              type="button"
              class="product-link-btn"
              @click="emit('edit', item)"
            >
              编辑
            </button>
            <button
              type="button"
              class="product-link-btn"
              @click="emit('detail', item)"
            >
              详情
            </button>
            <Popconfirm
              title="确认删除该商品吗？"
              ok-text="确认"
              cancel-text="取消"
              @confirm="emit('delete', item)"
            >
              <button type="button" class="product-link-btn danger">
                删除
              </button>
            </Popconfirm>
            <Dropdown :trigger="['click']">
              <button type="button" class="product-link-btn">更多</button>
              <template #overlay>
                <Menu @click="(payload) => handleMoreAction(item, payload)">
                  <Menu.Item
                    v-for="action in getMoreActionOptions(item)"
                    :key="action.key"
                  >
                    {{ action.label }}
                  </Menu.Item>
                </Menu>
              </template>
            </Dropdown>
          </div>

          <div v-if="item.status === 'sold_out'" class="product-card-mask">
            售罄
          </div>
        </article>
      </div>

      <div v-else class="product-list-table">
        <div class="product-list-header">
          <span class="cell check-cell">
            <Checkbox
              :checked="props.allChecked"
              :indeterminate="props.indeterminate"
              @change="(event) => handleCheckAll(event)"
            />
          </span>
          <span class="cell">图片</span>
          <span class="cell">商品信息</span>
          <span class="cell">分类</span>
          <span class="cell">价格</span>
          <span class="cell">库存</span>
          <span class="cell">销量</span>
          <span class="cell">标签</span>
          <span class="cell">状态</span>
          <span class="cell">操作</span>
        </div>

        <div
          v-for="item in props.rows"
          :key="item.id"
          class="product-list-row"
          :class="{
            'is-soldout': item.status === 'sold_out',
            'is-offshelf': item.status === 'off_shelf',
          }"
        >
          <span class="cell check-cell">
            <Checkbox
              :checked="isChecked(item.id)"
              @change="(event) => handleSingleCheck(item.id, event)"
            />
          </span>

          <span class="cell image-cell">
            <span class="list-cover">
              <img
                v-if="resolveImageUrl(item)"
                :src="resolveImageUrl(item)"
                :alt="item.name"
                class="list-cover-image"
              />
              <span v-else>{{ resolveImageFallbackText(item) }}</span>
            </span>
          </span>

          <span class="cell info-cell">
            <span class="name">{{ item.name }}</span>
            <span class="subtitle">{{ item.subtitle || '--' }}</span>
            <span class="spu">{{ item.spuCode }}</span>
          </span>

          <span class="cell">{{ item.categoryName || '--' }}</span>

          <span class="cell price-cell">
            <span class="price-now">{{ formatCurrency(item.price) }}</span>
            <span v-if="item.originalPrice" class="price-old">
              {{ formatCurrency(item.originalPrice) }}
            </span>
          </span>

          <span class="cell">
            <span
              :class="
                item.kind === 'combo' ? '' : resolveStockClass(item.stock)
              "
            >
              {{ item.kind === 'combo' ? '—' : formatStockText(item.stock) }}
            </span>
          </span>

          <span class="cell">月销 {{ item.salesMonthly }}</span>

          <span class="cell tags-cell">
            <Tag v-for="tag in item.tags" :key="`${item.id}-${tag}`">
              {{ tag }}
            </Tag>
          </span>

          <span class="cell">
            <span
              class="product-status-pill"
              :class="resolveStatusMeta(item.status).badgeClass"
            >
              {{ resolveStatusMeta(item.status).label }}
            </span>
          </span>

          <span class="cell actions-cell">
            <button
              type="button"
              class="product-link-btn"
              @click="emit('edit', item)"
            >
              编辑
            </button>
            <button
              type="button"
              class="product-link-btn"
              @click="emit('detail', item)"
            >
              详情
            </button>
            <Popconfirm
              title="确认删除该商品吗？"
              ok-text="确认"
              cancel-text="取消"
              @confirm="emit('delete', item)"
            >
              <button type="button" class="product-link-btn danger">
                删除
              </button>
            </Popconfirm>
            <Dropdown :trigger="['click']">
              <button type="button" class="product-link-btn">更多</button>
              <template #overlay>
                <Menu @click="(payload) => handleMoreAction(item, payload)">
                  <Menu.Item
                    v-for="action in getMoreActionOptions(item)"
                    :key="action.key"
                  >
                    {{ action.label }}
                  </Menu.Item>
                </Menu>
              </template>
            </Dropdown>
          </span>
        </div>
      </div>

      <div class="product-pagination">
        <Pagination
          :current="props.page"
          :page-size="props.pageSize"
          :total="props.total"
          :page-size-options="props.pageSizeOptions"
          show-size-changer
          @change="handlePageChange"
          @show-size-change="handlePageSizeChange"
        />
      </div>
    </div>
  </Spin>
</template>
