<script setup lang="ts">
/**
 * 文件职责：商品批量工具页面。
 * 1. 提供批量调价、批量上下架、批量移动分类能力。
 * 2. 提供批量同步门店、导入导出能力（Mock 回执）。
 */
import type { ProductBatchScopeDto } from '#/api/product';
import type { StoreListItemDto } from '#/api/store';

import { computed, onMounted, ref, watch } from 'vue';

import { Page } from '@vben/common-ui';

import {
  Alert,
  Button,
  Card,
  Empty,
  InputNumber,
  message,
  Select,
  Space,
  Tabs,
} from 'ant-design-vue';

import {
  batchAdjustProductPriceApi,
  batchExportProductApi,
  batchImportProductApi,
  batchMoveProductCategoryApi,
  batchSwitchProductSaleApi,
  batchSyncProductStoreApi,
  getProductCategoryManageListApi,
  searchProductPickerApi,
} from '#/api/product';
import { getStoreListApi } from '#/api/store';

type ScopeType = 'all' | 'category' | 'selected';

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

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

const stores = ref<StoreListItemDto[]>([]);
const selectedStoreId = ref('');
const isStoreLoading = ref(false);

const isCategoryLoading = ref(false);
const categoryOptions = ref<CategoryOption[]>([]);
const productOptions = ref<ProductOption[]>([]);
const isProductLoading = ref(false);

const scopeType = ref<ScopeType>('all');
const scopeCategoryId = ref('');
const scopeProductIds = ref<string[]>([]);

const priceMode = ref<'decrease' | 'increase' | 'set'>('increase');
const priceAmount = ref(1);
const saleAction = ref<'off' | 'on'>('off');
const moveTargetCategoryId = ref('');
const syncTargetStoreIds = ref<string[]>([]);
const syncProductIds = ref<string[]>([]);
const activeTab = ref('price');

const isSubmitting = ref(false);
const latestResultText = ref('');

const storeOptions = computed(() =>
  stores.value.map((item) => ({
    label: item.name,
    value: item.id,
  })),
);

const targetStoreOptions = computed(() =>
  stores.value
    .filter((item) => item.id !== selectedStoreId.value)
    .map((item) => ({
      label: item.name,
      value: item.id,
    })),
);

/** 加载门店列表。 */
async function loadStores() {
  isStoreLoading.value = true;
  try {
    const result = await getStoreListApi({
      page: 1,
      pageSize: 200,
    });
    stores.value = result.items ?? [];
    if (stores.value.length === 0) {
      selectedStoreId.value = '';
      return;
    }
    const hasSelected = stores.value.some(
      (item) => item.id === selectedStoreId.value,
    );
    if (!hasSelected) {
      selectedStoreId.value = stores.value[0]?.id ?? '';
    }
  } catch (error) {
    console.error(error);
    message.error('加载门店失败');
  } finally {
    isStoreLoading.value = false;
  }
}

/** 加载分类与商品选择器数据。 */
async function reloadScopeData() {
  if (!selectedStoreId.value) {
    categoryOptions.value = [];
    productOptions.value = [];
    return;
  }

  isCategoryLoading.value = true;
  isProductLoading.value = true;
  try {
    const [categories, products] = await Promise.all([
      getProductCategoryManageListApi({
        storeId: selectedStoreId.value,
      }),
      searchProductPickerApi({
        storeId: selectedStoreId.value,
        limit: 500,
      }),
    ]);

    categoryOptions.value = categories.map((item) => ({
      label: item.name,
      value: item.id,
    }));
    productOptions.value = products.map((item) => ({
      label: `${item.name}（${item.spuCode}）`,
      value: item.id,
    }));

    if (
      moveTargetCategoryId.value &&
      !categoryOptions.value.some(
        (item) => item.value === moveTargetCategoryId.value,
      )
    ) {
      moveTargetCategoryId.value = '';
    }
  } catch (error) {
    console.error(error);
    categoryOptions.value = [];
    productOptions.value = [];
    message.error('加载批量工具数据失败');
  } finally {
    isCategoryLoading.value = false;
    isProductLoading.value = false;
  }
}

/** 构建批量范围。 */
function buildScope(): ProductBatchScopeDto {
  if (scopeType.value === 'category') {
    return {
      type: 'category',
      categoryId: scopeCategoryId.value || undefined,
    };
  }
  if (scopeType.value === 'selected') {
    return {
      type: 'selected',
      productIds: [...scopeProductIds.value],
    };
  }
  return { type: 'all' };
}

/** 校验范围入参是否可用。 */
function validateScope() {
  if (scopeType.value === 'category' && !scopeCategoryId.value) {
    message.warning('请选择范围分类');
    return false;
  }
  if (scopeType.value === 'selected' && scopeProductIds.value.length === 0) {
    message.warning('请选择至少一个商品');
    return false;
  }
  return true;
}

/** 批量调价。 */
async function submitPriceAdjust() {
  if (!selectedStoreId.value) return;
  if (!validateScope()) return;
  if (priceAmount.value < 0) {
    message.warning('调价金额不能小于 0');
    return;
  }

  isSubmitting.value = true;
  try {
    const result = await batchAdjustProductPriceApi({
      storeId: selectedStoreId.value,
      scope: buildScope(),
      mode: priceMode.value,
      amount: priceAmount.value,
    });
    latestResultText.value = `调价完成：成功 ${result.successCount} / 总计 ${result.totalCount}`;
    message.success('批量调价成功');
  } catch (error) {
    console.error(error);
  } finally {
    isSubmitting.value = false;
  }
}

/** 批量上下架。 */
async function submitSaleSwitch() {
  if (!selectedStoreId.value) return;
  if (!validateScope()) return;

  isSubmitting.value = true;
  try {
    const result = await batchSwitchProductSaleApi({
      storeId: selectedStoreId.value,
      scope: buildScope(),
      action: saleAction.value,
    });
    latestResultText.value = `上下架完成：成功 ${result.successCount} / 总计 ${result.totalCount}`;
    message.success('批量上下架成功');
  } catch (error) {
    console.error(error);
  } finally {
    isSubmitting.value = false;
  }
}

/** 批量移动分类。 */
async function submitMoveCategory() {
  if (!selectedStoreId.value) return;
  if (!validateScope()) return;
  if (!moveTargetCategoryId.value) {
    message.warning('请选择目标分类');
    return;
  }

  isSubmitting.value = true;
  try {
    const result = await batchMoveProductCategoryApi({
      storeId: selectedStoreId.value,
      scope: buildScope(),
      targetCategoryId: moveTargetCategoryId.value,
    });
    latestResultText.value = `移动分类完成：成功 ${result.successCount} / 总计 ${result.totalCount}`;
    message.success('批量移动分类成功');
  } catch (error) {
    console.error(error);
  } finally {
    isSubmitting.value = false;
  }
}

/** 批量同步门店。 */
async function submitSyncStore() {
  if (!selectedStoreId.value) return;
  if (syncTargetStoreIds.value.length === 0) {
    message.warning('请选择目标门店');
    return;
  }
  if (syncProductIds.value.length === 0) {
    message.warning('请选择要同步的商品');
    return;
  }

  isSubmitting.value = true;
  try {
    const result = await batchSyncProductStoreApi({
      sourceStoreId: selectedStoreId.value,
      targetStoreIds: [...syncTargetStoreIds.value],
      productIds: [...syncProductIds.value],
    });
    latestResultText.value = `同步完成：成功 ${result.successCount} / 总计 ${result.totalCount}`;
    message.success('批量同步成功');
  } catch (error) {
    console.error(error);
  } finally {
    isSubmitting.value = false;
  }
}

/** 批量导入。 */
async function submitImport() {
  if (!selectedStoreId.value) return;
  if (!validateScope()) return;

  isSubmitting.value = true;
  try {
    const result = await batchImportProductApi({
      storeId: selectedStoreId.value,
      scope: buildScope(),
    });
    latestResultText.value = `导入完成：文件 ${result.fileName}，成功 ${result.successCount} / 总计 ${result.totalCount}`;
    message.success('批量导入成功');
  } catch (error) {
    console.error(error);
  } finally {
    isSubmitting.value = false;
  }
}

/** 批量导出。 */
async function submitExport() {
  if (!selectedStoreId.value) return;
  if (!validateScope()) return;

  isSubmitting.value = true;
  try {
    const result = await batchExportProductApi({
      storeId: selectedStoreId.value,
      scope: buildScope(),
    });
    latestResultText.value = `导出完成：文件 ${result.fileName}，导出 ${result.successCount} / 总计 ${result.totalCount}`;
    message.success('批量导出成功');
  } catch (error) {
    console.error(error);
  } finally {
    isSubmitting.value = false;
  }
}

watch(selectedStoreId, () => {
  scopeCategoryId.value = '';
  scopeProductIds.value = [];
  moveTargetCategoryId.value = '';
  syncTargetStoreIds.value = [];
  syncProductIds.value = [];
  reloadScopeData();
});

onMounted(loadStores);
</script>

<template>
  <Page title="批量工具" content-class="space-y-4 page-product-batch-tools">
    <Card :bordered="false">
      <Space direction="vertical" style="width: 100%">
        <Space wrap>
          <Select
            v-model:value="selectedStoreId"
            :options="storeOptions"
            :loading="isStoreLoading"
            style="width: 240px"
            placeholder="请选择门店"
          />
          <Select
            v-model:value="scopeType"
            style="width: 160px"
            :options="[
              { label: '全部商品', value: 'all' },
              { label: '按分类', value: 'category' },
              { label: '手动选择', value: 'selected' },
            ]"
          />
          <Select
            v-if="scopeType === 'category'"
            v-model:value="scopeCategoryId"
            :options="categoryOptions"
            :loading="isCategoryLoading"
            style="width: 200px"
            placeholder="选择分类"
          />
          <Select
            v-if="scopeType === 'selected'"
            v-model:value="scopeProductIds"
            mode="multiple"
            :options="productOptions"
            :loading="isProductLoading"
            style="min-width: 360px"
            placeholder="选择商品"
          />
        </Space>
        <Alert
          type="info"
          show-icon
          message="先设定批量范围，再选择具体工具执行。所有结果均为 Mock 回执。"
        />
      </Space>
    </Card>

    <Card v-if="!selectedStoreId" :bordered="false">
      <Empty description="暂无门店，请先创建门店" />
    </Card>

    <template v-else>
      <Card :bordered="false">
        <Tabs v-model:active-key="activeTab">
          <Tabs.TabPane key="price" tab="批量调价">
            <Space wrap>
              <Select
                v-model:value="priceMode"
                style="width: 160px"
                :options="[
                  { label: '统一设价', value: 'set' },
                  { label: '统一涨价', value: 'increase' },
                  { label: '统一降价', value: 'decrease' },
                ]"
              />
              <InputNumber v-model:value="priceAmount" :min="0" :step="0.5" />
              <Button
                type="primary"
                :loading="isSubmitting"
                @click="submitPriceAdjust"
              >
                执行调价
              </Button>
            </Space>
          </Tabs.TabPane>

          <Tabs.TabPane key="sale" tab="批量上下架">
            <Space wrap>
              <Select
                v-model:value="saleAction"
                style="width: 160px"
                :options="[
                  { label: '批量上架', value: 'on' },
                  { label: '批量下架', value: 'off' },
                ]"
              />
              <Button
                type="primary"
                :loading="isSubmitting"
                @click="submitSaleSwitch"
              >
                执行上下架
              </Button>
            </Space>
          </Tabs.TabPane>

          <Tabs.TabPane key="category" tab="批量移动分类">
            <Space wrap>
              <Select
                v-model:value="moveTargetCategoryId"
                :options="categoryOptions"
                :loading="isCategoryLoading"
                style="width: 220px"
                placeholder="目标分类"
              />
              <Button
                type="primary"
                :loading="isSubmitting"
                @click="submitMoveCategory"
              >
                执行移动
              </Button>
            </Space>
          </Tabs.TabPane>

          <Tabs.TabPane key="sync" tab="同步到其他门店">
            <Space direction="vertical" style="width: 100%">
              <Space wrap>
                <Select
                  v-model:value="syncTargetStoreIds"
                  mode="multiple"
                  :options="targetStoreOptions"
                  style="min-width: 300px"
                  placeholder="选择目标门店"
                />
              </Space>
              <Select
                v-model:value="syncProductIds"
                mode="multiple"
                :options="productOptions"
                :loading="isProductLoading"
                placeholder="选择需要同步的商品"
              />
              <Button
                type="primary"
                :loading="isSubmitting"
                @click="submitSyncStore"
              >
                执行同步
              </Button>
            </Space>
          </Tabs.TabPane>

          <Tabs.TabPane key="excel" tab="导入导出">
            <Space wrap>
              <Button :loading="isSubmitting" @click="submitImport">
                导入商品
              </Button>
              <Button
                type="primary"
                :loading="isSubmitting"
                @click="submitExport"
              >
                导出商品
              </Button>
            </Space>
          </Tabs.TabPane>
        </Tabs>
      </Card>

      <Card v-if="latestResultText" :bordered="false">
        <Alert type="success" show-icon :message="latestResultText" />
      </Card>
    </template>
  </Page>
</template>

<style scoped lang="less">
/* 文件职责：批量工具页面样式。 */
.page-product-batch-tools {
  :deep(.ant-tabs-nav) {
    margin-bottom: 18px;
  }
}
</style>
