<script setup lang="ts">
import type {
  FullReductionPickerCategoryItem,
  FullReductionPickerProductItem,
  FullReductionScopeForm,
} from '../types';

/**
 * 文件职责：满减活动二级范围选择抽屉。
 * 1. 支持分类/商品选择、搜索、筛选与全选。
 * 2. 输出统一 scope 结果供主抽屉回填。
 */
import type { ProductStatus } from '#/api/product';

import { computed } from 'vue';

import {
  Button,
  Drawer,
  Empty,
  Input,
  Radio,
  Select,
  Spin,
} from 'ant-design-vue';

import { formatCurrency } from '../composables/full-reduction-page/helpers';

const props = defineProps<{
  allowAll: boolean;
  categories: FullReductionPickerCategoryItem[];
  categoryFilterId: string;
  keyword: string;
  loading: boolean;
  open: boolean;
  products: FullReductionPickerProductItem[];
  scope: FullReductionScopeForm;
  title: string;
}>();

const emit = defineEmits<{
  (event: 'close'): void;
  (event: 'search'): void;
  (event: 'setCategoryFilterId', value: string): void;
  (event: 'setCategoryIds', value: string[]): void;
  (event: 'setKeyword', value: string): void;
  (event: 'setProductIds', value: string[]): void;
  (event: 'setScopeType', value: FullReductionScopeForm['scopeType']): void;
  (event: 'submit'): void;
}>();

const categoryOptions = computed(() => [
  { label: '全部分类', value: '' },
  ...props.categories.map((item) => ({
    label: item.name,
    value: item.id,
  })),
]);

const filteredCategories = computed(() => {
  const keyword = props.keyword.trim().toLowerCase();
  if (!keyword) {
    return props.categories;
  }
  return props.categories.filter((item) =>
    item.name.toLowerCase().includes(keyword),
  );
});

const filteredProducts = computed(() => {
  const keyword = props.keyword.trim().toLowerCase();
  if (!keyword) {
    return props.products;
  }

  return props.products.filter(
    (item) =>
      item.name.toLowerCase().includes(keyword) ||
      item.spuCode.toLowerCase().includes(keyword),
  );
});

const isCategoryMode = computed(() => props.scope.scopeType === 'category');
const isProductMode = computed(() => props.scope.scopeType === 'product');

const selectedCount = computed(() => {
  if (props.scope.scopeType === 'category') {
    return props.scope.categoryIds.length;
  }
  if (props.scope.scopeType === 'product') {
    return props.scope.productIds.length;
  }
  return 0;
});

const categoryAllChecked = computed(
  () =>
    filteredCategories.value.length > 0 &&
    filteredCategories.value.every((item) =>
      props.scope.categoryIds.includes(item.id),
    ),
);

const productAllChecked = computed(
  () =>
    filteredProducts.value.length > 0 &&
    filteredProducts.value.every((item) =>
      props.scope.productIds.includes(item.id),
    ),
);

function setScopeType(value: unknown) {
  if (value === 'all' || value === 'category' || value === 'product') {
    emit('setScopeType', value);
  }
}

function setKeyword(value: string) {
  emit('setKeyword', value);
}

function setCategoryFilterId(value: unknown) {
  emit('setCategoryFilterId', String(value ?? ''));
}

function toggleCategory(id: string) {
  if (props.scope.categoryIds.includes(id)) {
    emit(
      'setCategoryIds',
      props.scope.categoryIds.filter((item) => item !== id),
    );
    return;
  }
  emit('setCategoryIds', [...props.scope.categoryIds, id]);
}

function toggleProduct(id: string) {
  if (props.scope.productIds.includes(id)) {
    emit(
      'setProductIds',
      props.scope.productIds.filter((item) => item !== id),
    );
    return;
  }
  emit('setProductIds', [...props.scope.productIds, id]);
}

function toggleAllCategories() {
  if (categoryAllChecked.value) {
    const visibleIds = new Set(filteredCategories.value.map((item) => item.id));
    emit(
      'setCategoryIds',
      props.scope.categoryIds.filter((id) => !visibleIds.has(id)),
    );
    return;
  }

  const merged = new Set(props.scope.categoryIds);
  for (const item of filteredCategories.value) {
    merged.add(item.id);
  }
  emit('setCategoryIds', [...merged]);
}

function toggleAllProducts() {
  if (productAllChecked.value) {
    const visibleIds = new Set(filteredProducts.value.map((item) => item.id));
    emit(
      'setProductIds',
      props.scope.productIds.filter((id) => !visibleIds.has(id)),
    );
    return;
  }

  const merged = new Set(props.scope.productIds);
  for (const item of filteredProducts.value) {
    merged.add(item.id);
  }
  emit('setProductIds', [...merged]);
}

function resolveProductStatusText(status: ProductStatus) {
  if (status === 'on_sale') {
    return '在售';
  }
  if (status === 'sold_out') {
    return '沽清';
  }
  return '下架';
}

function resolveProductStatusClass(status: ProductStatus) {
  if (status === 'on_sale') {
    return 'mfr-prod-status-on';
  }
  if (status === 'sold_out') {
    return 'mfr-prod-status-soldout';
  }
  return 'mfr-prod-status-off';
}
</script>

<template>
  <Drawer
    :open="open"
    :title="title"
    width="760"
    class="mfr-picker-drawer"
    @close="emit('close')"
  >
    <div class="mfr-picker-toolbar">
      <Radio.Group :value="scope.scopeType" @update:value="setScopeType">
        <Radio.Button v-if="allowAll" value="all">全部商品</Radio.Button>
        <Radio.Button value="category">按分类选择</Radio.Button>
        <Radio.Button value="product">按商品选择</Radio.Button>
      </Radio.Group>

      <template v-if="scope.scopeType !== 'all'">
        <div class="mfr-picker-search">
          <Input
            :value="keyword"
            placeholder="搜索商品名称/SPU"
            allow-clear
            @update:value="setKeyword"
            @press-enter="emit('search')"
          />
        </div>
        <Select
          v-if="isProductMode"
          :value="categoryFilterId"
          :options="categoryOptions"
          class="mfr-picker-category"
          @update:value="setCategoryFilterId"
        />
        <Button v-if="isProductMode" @click="emit('search')">搜索</Button>
        <span class="mfr-picker-count">已选 {{ selectedCount }} 个</span>
      </template>
    </div>

    <Spin :spinning="loading">
      <div v-if="scope.scopeType === 'all'" class="mfr-picker-all">
        当前规则将作用于全部商品
      </div>

      <div v-else class="mfr-picker-body">
        <div
          v-if="
            (isCategoryMode && filteredCategories.length === 0) ||
            (isProductMode && filteredProducts.length === 0)
          "
          class="mfr-picker-empty"
        >
          <Empty description="暂无可选数据" />
        </div>

        <table v-else class="mfr-picker-table">
          <thead>
            <tr v-if="isCategoryMode">
              <th class="mfr-picker-col-check">
                <input
                  type="checkbox"
                  :checked="categoryAllChecked"
                  @change="toggleAllCategories"
                />
              </th>
              <th>分类名称</th>
              <th class="mfr-picker-col-count">商品数</th>
            </tr>

            <tr v-else>
              <th class="mfr-picker-col-check">
                <input
                  type="checkbox"
                  :checked="productAllChecked"
                  @change="toggleAllProducts"
                />
              </th>
              <th>商品</th>
              <th>分类</th>
              <th class="mfr-picker-col-price">售价</th>
              <th class="mfr-picker-col-status">状态</th>
            </tr>
          </thead>

          <tbody v-if="isCategoryMode">
            <tr
              v-for="item in filteredCategories"
              :key="`category-${item.id}`"
              :class="{ checked: scope.categoryIds.includes(item.id) }"
              @click="toggleCategory(item.id)"
            >
              <td class="mfr-picker-col-check">
                <input
                  type="checkbox"
                  :checked="scope.categoryIds.includes(item.id)"
                  @change.stop="toggleCategory(item.id)"
                />
              </td>
              <td>{{ item.name }}</td>
              <td class="mfr-picker-col-count">{{ item.productCount }}</td>
            </tr>
          </tbody>

          <tbody v-else>
            <tr
              v-for="item in filteredProducts"
              :key="`product-${item.id}`"
              :class="{ checked: scope.productIds.includes(item.id) }"
              @click="toggleProduct(item.id)"
            >
              <td class="mfr-picker-col-check">
                <input
                  type="checkbox"
                  :checked="scope.productIds.includes(item.id)"
                  @change.stop="toggleProduct(item.id)"
                />
              </td>
              <td>
                <div class="mfr-picker-product-name">{{ item.name }}</div>
                <div class="mfr-picker-product-spu">{{ item.spuCode }}</div>
              </td>
              <td>{{ item.categoryName }}</td>
              <td class="mfr-picker-col-price">
                {{ formatCurrency(item.price) }}
              </td>
              <td class="mfr-picker-col-status">
                <span
                  class="mfr-prod-status"
                  :class="resolveProductStatusClass(item.status)"
                >
                  {{ resolveProductStatusText(item.status) }}
                </span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </Spin>

    <template #footer>
      <div class="mfr-picker-footer">
        <span class="mfr-picker-footer-info">
          已选择 {{ selectedCount }} 个
        </span>
        <div class="mfr-picker-footer-actions">
          <Button @click="emit('close')">取消</Button>
          <Button type="primary" @click="emit('submit')">确认选择</Button>
        </div>
      </div>
    </template>
  </Drawer>
</template>
