<template>
  <div class="app-page">
    <!-- 筛选区 -->
    <section class="glass-card section-card">
      <el-form :model="filters" inline class="filter-form">
        <el-form-item label="供应商">
          <el-select v-model="filters.supplier" placeholder="全部" clearable filterable style="width:160px">
            <el-option v-for="s in supplierOptions" :key="s" :label="s" :value="s" />
          </el-select>
        </el-form-item>
        <el-form-item label="SKU">
          <el-input v-model="filters.sku" placeholder="SKU 编码" clearable style="width:160px" @keyup.enter="loadData" />
        </el-form-item>
        <el-form-item label="默认供应商">
          <el-select v-model="filters.isDefault" placeholder="全部" clearable style="width:120px">
            <el-option label="是" :value="true" />
            <el-option label="否" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="全部" clearable style="width:120px">
            <el-option label="启用" value="启用" />
            <el-option label="停用" value="停用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadData">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </section>

    <!-- 工具栏 -->
    <section class="glass-card section-card" style="padding:12px 24px">
      <div class="table-toolbar" style="margin-bottom:0">
        <div class="chip-list">
          <el-button type="primary" @click="openCreate">新增配置</el-button>
        </div>
        <el-button @click="loadData">刷新</el-button>
      </div>
    </section>

    <!-- 列表 -->
    <section class="glass-card section-card">
      <el-table :data="filteredItems" style="width:100%" v-loading="loading">
        <el-table-column prop="supplier" label="供应商" min-width="180" />
        <el-table-column prop="sku" label="SKU" width="140">
          <template #default="{ row }">
            <div>{{ row.sku }}</div>
            <div style="color:var(--cb-text-soft);font-size:12px">{{ row.productTitle }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="leadTime" label="标准交期(天)" width="120" />
        <el-table-column prop="moq" label="MOQ" width="80" />
        <el-table-column prop="unit" label="采购单位" width="90" />
        <el-table-column label="阶梯价" min-width="200">
          <template #default="{ row }">
            <div v-if="row.tierPrices && row.tierPrices.length">
              <div v-for="(tier, idx) in row.tierPrices" :key="idx" class="tier-row">
                {{ tier.from }}~{{ tier.to }} : {{ tier.price }}
              </div>
            </div>
            <span v-else style="color:var(--cb-text-soft)">--</span>
          </template>
        </el-table-column>
        <el-table-column prop="isDefault" label="默认供应商" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.isDefault" type="success" size="small">默认</el-tag>
            <span v-else style="color:var(--cb-text-soft)">--</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getCapabilityStatus(row.status).type" size="small">{{ getCapabilityStatus(row.status).label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="openEdit(row)">编辑</el-button>
            <el-button link type="primary" @click="setDefault(row)" :disabled="row.isDefault">设为默认</el-button>
            <el-button link type="danger" @click="toggleStatus(row)">{{ row.status === '启用' ? '停用' : '启用' }}</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
      </el-table>
      <div style="display:flex;justify-content:flex-end;margin-top:16px" v-if="total > 0">
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :total="total" :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next" @size-change="loadData" @current-change="loadData" />
      </div>
    </section>

    <!-- 新建/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑供货配置' : '新增供货配置'" width="700px" destroy-on-close>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="110px" label-position="right">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplier">
              <el-select v-model="formData.supplier" placeholder="请选择供应商" filterable style="width:100%">
                <el-option v-for="s in supplierOptions" :key="s" :label="s" :value="s" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="SKU" prop="sku">
              <el-input v-model="formData.sku" placeholder="SKU 编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="标准交期" prop="leadTime">
              <el-input-number v-model="formData.leadTime" :min="0" :max="365" controls-position="right" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="MOQ" prop="moq">
              <el-input-number v-model="formData.moq" :min="0" :max="999999" controls-position="right" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购单位" prop="unit">
              <el-select v-model="formData.unit" placeholder="单位" style="width:100%">
                <el-option label="件" value="件" />
                <el-option label="箱" value="箱" />
                <el-option label="套" value="套" />
                <el-option label="个" value="个" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="币种" prop="currency">
              <el-select v-model="formData.currency" placeholder="币种" style="width:100%">
                <el-option label="CNY" value="CNY" />
                <el-option label="USD" value="USD" />
                <el-option label="EUR" value="EUR" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 阶梯价 -->
        <el-divider content-position="left">阶梯价格</el-divider>
        <div v-for="(tier, idx) in formData.tierPrices" :key="idx" style="margin-bottom:8px">
          <el-row :gutter="8" align="middle">
            <el-col :span="6">
              <el-input-number v-model="tier.from" :min="0" controls-position="right" placeholder="起始量" style="width:100%" />
            </el-col>
            <el-col :span="6">
              <el-input-number v-model="tier.to" :min="0" controls-position="right" placeholder="结束量" style="width:100%" />
            </el-col>
            <el-col :span="6">
              <el-input v-model="tier.price" placeholder="单价" />
            </el-col>
            <el-col :span="6">
              <el-button link type="danger" @click="removeTier(idx)" :disabled="formData.tierPrices.length <= 1">删除</el-button>
            </el-col>
          </el-row>
        </div>
        <el-button type="primary" link @click="addTier" style="margin-bottom:12px">+ 添加阶梯</el-button>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { api } from '@/api/services';
import type { SupplyCapabilityItem } from '@/types/page';
import { getCapabilityStatus } from '@/utils/enumMappings';

const items = ref<SupplyCapabilityItem[]>([]);
const loading = ref(false);
const page = ref(1);
const pageSize = ref(10);
const dialogVisible = ref(false);
const isEdit = ref(false);
const editId = ref('');
const submitting = ref(false);
const formRef = ref<FormInstance>();

const supplierOptions = ref<string[]>([]);

const filters = ref({
  supplier: '',
  sku: '',
  isDefault: null as boolean | null,
  status: ''
});

interface TierPrice {
  from: number;
  to: number;
  price: string;
}

interface FormState {
  supplier: string;
  sku: string;
  leadTime: number;
  moq: number;
  unit: string;
  currency: string;
  tierPrices: TierPrice[];
  remark: string;
}

const defaultFormData = (): FormState => ({
  supplier: '',
  sku: '',
  leadTime: 0,
  moq: 0,
  unit: '件',
  currency: 'CNY',
  tierPrices: [{ from: 1, to: 100, price: '' }],
  remark: ''
});

const formData = reactive<FormState>(defaultFormData());

const formRules: FormRules = {
  supplier: [{ required: true, message: '请选择供应商', trigger: 'change' }],
  sku: [{ required: true, message: '请输入 SKU', trigger: 'blur' }],
  leadTime: [{ required: true, message: '请输入交期', trigger: 'blur' }],
  moq: [{ required: true, message: '请输入 MOQ', trigger: 'blur' }],
  unit: [{ required: true, message: '请选择单位', trigger: 'change' }],
  currency: [{ required: true, message: '请选择币种', trigger: 'change' }]
};

const filteredItems = computed(() => {
  return items.value.filter((item) => {
    if (filters.value.supplier && item.supplier !== filters.value.supplier) return false;
    if (filters.value.sku && !item.sku.includes(filters.value.sku)) return false;
    if (filters.value.isDefault !== null && item.isDefault !== filters.value.isDefault) return false;
    if (filters.value.status && item.status !== filters.value.status) return false;
    return true;
  });
});

const total = computed(() => filteredItems.value.length);

const loadData = async () => {
  loading.value = true;
  try {
    const [capRes, supplierRes] = await Promise.all([
      api.getSupplyCapabilities(),
      api.getSuppliers()
    ] as const);
    items.value = capRes.items ?? [];
    supplierOptions.value = (supplierRes.items ?? []).map((s: any) => s.name);
  } finally {
    loading.value = false;
  }
};

const resetFilters = () => {
  filters.value = { supplier: '', sku: '', isDefault: null, status: '' };
};

const addTier = () => {
  const last = formData.tierPrices[formData.tierPrices.length - 1];
  formData.tierPrices.push({ from: last?.to ? last.to + 1 : 1, to: 0, price: '' });
};

const removeTier = (idx: number) => {
  formData.tierPrices.splice(idx, 1);
};

const openCreate = () => {
  isEdit.value = false;
  editId.value = '';
  Object.assign(formData, defaultFormData());
  dialogVisible.value = true;
};

const openEdit = (row: SupplyCapabilityItem) => {
  isEdit.value = true;
  editId.value = row.id;
  Object.assign(formData, {
    supplier: row.supplier,
    sku: row.sku,
    leadTime: row.leadTime,
    moq: row.moq,
    unit: row.unit,
    currency: 'CNY',
    tierPrices: row.tierPrices && row.tierPrices.length
      ? row.tierPrices.map((t) => ({ from: t.from, to: t.to, price: t.price }))
      : [{ from: 1, to: 100, price: '' }],
    remark: ''
  });
  dialogVisible.value = true;
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate();

  if (formData.leadTime < 0) {
    ElMessage.warning('标准交期不能为负数');
    return;
  }
  if (formData.moq < 0) {
    ElMessage.warning('MOQ 不能为负数');
    return;
  }

  submitting.value = true;
  try {
    const payload: Partial<SupplyCapabilityItem> = {
      supplier: formData.supplier,
      sku: formData.sku,
      leadTime: formData.leadTime,
      moq: formData.moq,
      unit: formData.unit,
      tierPrices: formData.tierPrices.map((t) => ({ from: t.from, to: t.to, price: t.price }))
    };

    if (isEdit.value) {
      await api.updateSupplyCapability(Number(editId.value), payload);
      ElMessage.success('供货配置更新成功');
    } else {
      await api.createSupplyCapability(payload);
      ElMessage.success('供货配置创建成功');
    }
    dialogVisible.value = false;
    loadData();
  } finally {
    submitting.value = false;
  }
};

const setDefault = async (row: SupplyCapabilityItem) => {
  try {
    await ElMessageBox.confirm(
      `确认将「${row.supplier}」设为 SKU「${row.sku}」的默认供应商？此操作将清除该 SKU 的其他默认供应商设置。`,
      '设为默认',
      { type: 'info' }
    );

    // Clear existing defaults for the same SKU
    const sameSkuDefaults = items.value.filter(
      (item) => item.sku === row.sku && item.isDefault && item.id !== row.id
    );
    for (const item of sameSkuDefaults) {
      await api.updateSupplyCapability(Number(item.id), { isDefault: false } as Partial<SupplyCapabilityItem>);
    }

    // Set the new default
    await api.updateSupplyCapability(Number(row.id), { isDefault: true } as Partial<SupplyCapabilityItem>);
    ElMessage.success('已设为默认供应商');
    loadData();
  } catch {
    // cancelled
  }
};

const toggleStatus = async (row: SupplyCapabilityItem) => {
  const target = row.status === '启用' ? '停用' : '启用';
  const action = target === '停用' ? '停用' : '启用';

  try {
    await ElMessageBox.confirm(
      `确认${action}「${row.supplier}」对 SKU「${row.sku}」的供货配置？`,
      `${action}确认`,
      { type: target === '停用' ? 'warning' : 'info' }
    );
    await api.updateSupplyCapability(Number(row.id), { status: target } as Partial<SupplyCapabilityItem>);
    ElMessage.success(`${action}成功`);
    loadData();
  } catch {
    // cancelled
  }
};

onMounted(loadData);
</script>

<style scoped>
.filter-form :deep(.el-form-item) { margin-bottom: 0; }
.tier-row { font-size: 13px; color: var(--cb-text-soft); line-height: 1.6; }
</style>
