<script setup lang="ts">
import type { BatchPricePreviewRow, BatchScopeType } from '../types';

import { computed } from 'vue';

import { Button, InputNumber, Select, Table } from 'ant-design-vue';

interface Props {
  amount: number;
  amountType: 'fixed' | 'percent';
  categoryOptions: Array<{ label: string; value: string }>;
  direction: 'down' | 'up';
  embedded?: boolean;
  open: boolean;
  previewItems: BatchPricePreviewRow[];
  previewLoading: boolean;
  previewTotal: number;
  productOptions: Array<{ label: string; value: string }>;
  scopeCategoryIds: string[];
  scopeProductIds: string[];
  scopeType: BatchScopeType;
  submitting: boolean;
}

interface Emits {
  (event: 'close'): void;
  (event: 'preview'): void;
  (event: 'submit'): void;
  (event: 'update:amount', value: number): void;
  (event: 'update:amountType', value: 'fixed' | 'percent'): void;
  (event: 'update:direction', value: 'down' | 'up'): void;
  (event: 'update:scopeCategoryIds', value: string[]): void;
  (event: 'update:scopeProductIds', value: string[]): void;
  (event: 'update:scopeType', value: BatchScopeType): void;
}

const props = withDefaults(defineProps<Props>(), {
  embedded: false,
});
const emit = defineEmits<Emits>();

const scopePills = [
  { label: '全部商品', value: 'all' as const },
  { label: '按分类', value: 'category' as const },
  { label: '手动选择', value: 'manual' as const },
];

const directionPills = [
  { label: '涨价', value: 'up' as const },
  { label: '降价', value: 'down' as const },
];

const amountTypePills = [
  { label: '固定金额', value: 'fixed' as const },
  { label: '百分比', value: 'percent' as const },
];

const columns = computed(() => [
  { title: '商品名', dataIndex: 'productName', key: 'productName' },
  {
    title: '原价',
    dataIndex: 'originalPrice',
    key: 'originalPrice',
    width: 130,
  },
  { title: '新价', dataIndex: 'newPrice', key: 'newPrice', width: 130 },
  { title: '变动', dataIndex: 'deltaPrice', key: 'deltaPrice', width: 130 },
]);

function formatMoney(value: number) {
  return `¥${Number(value || 0).toFixed(2)}`;
}

function setScopeType(value: BatchScopeType) {
  emit('update:scopeType', value);
}

function normalizeArray(value: unknown) {
  if (!Array.isArray(value)) {
    return [];
  }
  return value.map(String);
}

function setScopeCategoryIds(value: unknown) {
  emit('update:scopeCategoryIds', normalizeArray(value));
}

function setScopeProductIds(value: unknown) {
  emit('update:scopeProductIds', normalizeArray(value));
}

function setAmount(value: null | number | string) {
  const parsed = Number(value ?? 0);
  emit('update:amount', Number.isFinite(parsed) ? parsed : 0);
}
</script>

<template>
  <section
    v-if="props.open"
    class="pbt-panel"
    :class="{ 'pbt-panel-embedded': props.embedded }"
  >
    <header v-if="!props.embedded" class="pbt-panel-hd">
      <h3>批量调价</h3>
      <button type="button" class="pbt-close" @click="emit('close')">×</button>
    </header>

    <div class="pbt-step">
      <div class="pbt-step-label"><span class="num">1</span> 选择范围</div>
      <div class="pbt-pills">
        <button
          v-for="item in scopePills"
          :key="item.value"
          type="button"
          class="pbt-pill"
          :class="{ active: props.scopeType === item.value }"
          @click="setScopeType(item.value)"
        >
          {{ item.label }}
        </button>
      </div>
      <Select
        v-if="props.scopeType === 'category'"
        mode="multiple"
        :value="props.scopeCategoryIds"
        :options="props.categoryOptions"
        placeholder="选择分类"
        class="pbt-select-wide"
        @update:value="setScopeCategoryIds"
      />
      <Select
        v-if="props.scopeType === 'manual'"
        mode="multiple"
        :value="props.scopeProductIds"
        :options="props.productOptions"
        placeholder="选择商品"
        class="pbt-select-wide"
        @update:value="setScopeProductIds"
      />
    </div>

    <div class="pbt-step">
      <div class="pbt-step-label"><span class="num">2</span> 调价方式</div>
      <!-- 1. 方向与类型选择 -->
      <div class="pbt-adjust-row">
        <div class="pbt-pills">
          <button
            v-for="item in directionPills"
            :key="item.value"
            type="button"
            class="pbt-pill"
            :class="{ active: props.direction === item.value }"
            @click="emit('update:direction', item.value)"
          >
            {{ item.label }}
          </button>
        </div>
        <div class="pbt-pills">
          <button
            v-for="item in amountTypePills"
            :key="item.value"
            type="button"
            class="pbt-pill"
            :class="{ active: props.amountType === item.value }"
            @click="emit('update:amountType', item.value)"
          >
            {{ item.label }}
          </button>
        </div>
      </div>
      <!-- 2. 数值输入与预览 -->
      <div class="pbt-adjust-input">
        <InputNumber
          :value="props.amount"
          :min="0"
          :step="0.1"
          class="pbt-number"
          :addon-after="props.amountType === 'percent' ? '%' : '¥'"
          @update:value="setAmount"
        />
        <Button :loading="props.previewLoading" @click="emit('preview')">
          更新预览
        </Button>
      </div>
    </div>

    <div class="pbt-step">
      <div class="pbt-step-label">
        <span class="num">3</span>
        预览（共 {{ props.previewTotal }} 个商品，展示前 50 条）
      </div>
      <Table
        class="pbt-table"
        size="small"
        :columns="columns"
        :data-source="props.previewItems"
        :pagination="false"
        row-key="productId"
        :loading="props.previewLoading"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'originalPrice'">
            {{ formatMoney(record.originalPrice) }}
          </template>
          <template v-else-if="column.key === 'newPrice'">
            {{ formatMoney(record.newPrice) }}
          </template>
          <template v-else-if="column.key === 'deltaPrice'">
            <span :class="record.deltaPrice >= 0 ? 'up' : 'down'">
              {{ record.deltaPrice >= 0 ? '+' : ''
              }}{{ formatMoney(record.deltaPrice) }}
            </span>
          </template>
        </template>
      </Table>
    </div>

    <footer class="pbt-actions">
      <Button
        type="primary"
        :loading="props.submitting"
        @click="emit('submit')"
      >
        确认调价
      </Button>
      <Button @click="emit('close')">取消</Button>
    </footer>
  </section>
</template>
