<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import type { FamilyPriceOverrideRow, ProductFamily } from '@/types'
import { productFamiliesApi } from '@/api/product-families'

const props = defineProps<{ family: ProductFamily }>()
const emit = defineEmits<{ (e: 'changed'): void }>()

const matrix = computed(() => props.family.priceMatrix)

// (工艺 × 物流) 组合页签
const combos = computed(() => {
  const m = matrix.value
  if (!m) return []
  const out: Array<{ craft: string; logistics: string }> = []
  for (const craft of m.crafts) {
    for (const logistics of m.logistics) {
      if (m.rows.some((r) => r.craft === craft && r.logistics === logistics)) {
        out.push({ craft, logistics })
      }
    }
  }
  return out
})
const activeCombo = ref('')
watch(
  combos,
  (list) => {
    if (list.length && !list.some((c) => `${c.craft}|${c.logistics}` === activeCombo.value)) {
      activeCombo.value = `${list[0].craft}|${list[0].logistics}`
    }
  },
  { immediate: true },
)

const currentCraft = computed(() => activeCombo.value.split('|')[0] ?? '')
const currentLogistics = computed(() => activeCombo.value.split('|')[1] ?? '')

// 当前组合下的矩阵：行=尺码，列=颜色
const sizeNames = computed(() => matrix.value?.sizes.map((s) => ({ key: s.key, name: s.name ?? s.key })) ?? [])
const colorKeys = computed(() => matrix.value?.colors.map((c) => ({ key: c.key, name: c.name ?? c.key })) ?? [])

function rowOf(sizeKey: string, colorKey: string) {
  return matrix.value?.rows.find(
    (r) => r.sizeId === sizeKey && r.colorId === colorKey && r.craft === currentCraft.value && r.logistics === currentLogistics.value,
  )
}

const editing = ref<Record<string, number>>({})

function startEdit(sizeKey: string, colorKey: string) {
  const row = rowOf(sizeKey, colorKey)
  if (!row) return
  editing.value[`${sizeKey}|${colorKey}`] = Number(row.price)
}

async function saveEdit(sizeKey: string, colorKey: string) {
  const key = `${sizeKey}|${colorKey}`
  const value = editing.value[key]
  const row = rowOf(sizeKey, colorKey)
  if (row === undefined || value === undefined || Number.isNaN(value)) return
  if (Math.abs(value - Number(row.price)) < 0.0001) return
  try {
    await productFamiliesApi.putOverrides(props.family.id, [
      { sizeId: sizeKey, colorId: colorKey, craft: currentCraft.value, logistics: currentLogistics.value, price: value },
    ])
    ElMessage.success('已改价')
    emit('changed')
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message ?? '改价失败')
  } finally {
    delete editing.value[key]
  }
}

async function removeOverride(o: FamilyPriceOverrideRow) {
  try {
    await productFamiliesApi.deleteOverrides(props.family.id, [
      { sizeId: o.sizeId, colorId: o.colorId, craft: o.craft, logistics: o.logistics },
    ])
    ElMessage.success('已恢复推导价')
    emit('changed')
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message ?? '删除失败')
  }
}
</script>

<template>
  <div class="pop">
    <el-tabs v-model="activeCombo" type="card">
      <el-tab-pane
        v-for="c in combos"
        :key="`${c.craft}|${c.logistics}`"
        :name="`${c.craft}|${c.logistics}`"
        :label="`${c.craft} · ${c.logistics}`"
      />
    </el-tabs>

    <div class="pop-matrix-wrap">
      <table class="pop-matrix">
        <thead>
          <tr>
            <th class="pop-corner">尺码 \ 颜色</th>
            <th v-for="c in colorKeys" :key="c.key">{{ c.name }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="s in sizeNames" :key="s.key">
            <th class="pop-size">{{ s.name }}</th>
            <td v-for="c in colorKeys" :key="c.key" :class="{ 'pop-na': !rowOf(s.key, c.key) }">
              <template v-if="rowOf(s.key, c.key)">
                <el-input-number
                  v-if="editing[`${s.key}|${c.key}`] !== undefined"
                  :model-value="editing[`${s.key}|${c.key}`]"
                  :min="0.01"
                  :precision="2"
                  :controls="false"
                  size="small"
                  autofocus
                  @update:model-value="(v: number | undefined) => (editing[`${s.key}|${c.key}`] = v ?? 0)"
                  @blur="saveEdit(s.key, c.key)"
                  @keyup.enter="saveEdit(s.key, c.key)"
                />
                <span
                  v-else
                  class="pop-price"
                  :class="{ 'pop-manual': rowOf(s.key, c.key)!.manual }"
                  :title="rowOf(s.key, c.key)!.manual ? '人工改价' : '推导价（点击改价）'"
                  @click="startEdit(s.key, c.key)"
                >
                  ¥{{ rowOf(s.key, c.key)!.price }}
                  <el-tag v-if="rowOf(s.key, c.key)!.manual" size="small" type="warning">改</el-tag>
                </span>
              </template>
              <span v-else class="pop-na-text">—</span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <template v-if="family.priceOverrides.length">
      <h4 class="pop-sub">已设人工价（{{ family.priceOverrides.length }}）</h4>
      <el-table :data="family.priceOverrides" size="small" border max-height="220">
        <el-table-column label="尺码" width="90">
          <template #default="{ row }">
            {{ matrix?.sizes.find((s) => s.key === row.sizeId)?.name ?? row.sizeId }}
          </template>
        </el-table-column>
        <el-table-column label="颜色" width="110">
          <template #default="{ row }">
            {{ matrix?.colors.find((c) => c.key === row.colorId)?.name ?? row.colorId }}
          </template>
        </el-table-column>
        <el-table-column prop="craft" label="工艺" width="100" />
        <el-table-column prop="logistics" label="物流" width="110" />
        <el-table-column prop="price" label="人工价" width="90" align="right" />
        <el-table-column label="推导价" width="90" align="right">
          <template #default="{ row }">{{ row.derivedPrice ?? '—' }}</template>
        </el-table-column>
        <el-table-column label="差额" width="90" align="right">
          <template #default="{ row }">
            <span v-if="row.diff" :class="Number(row.diff) > 0 ? 'pop-up' : 'pop-down'">{{ row.diff }}</span>
            <span v-else>—</span>
          </template>
        </el-table-column>
        <el-table-column prop="note" label="备注" min-width="120" show-overflow-tooltip />
        <el-table-column label="操作" width="70" fixed="right">
          <template #default="{ row }: any">
            <el-button link type="danger" :icon="Delete" @click="removeOverride(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </div>
</template>

<style scoped>
.pop { display: flex; flex-direction: column; gap: 10px; }
.pop-matrix-wrap { overflow: auto; max-height: 360px; border: 1px solid var(--el-border-color-lighter); }
.pop-matrix { border-collapse: collapse; font-size: 12px; }
.pop-matrix th, .pop-matrix td { border: 1px solid var(--el-border-color-lighter); padding: 4px 10px; text-align: center; min-width: 72px; }
.pop-matrix thead th, .pop-size { background: var(--el-fill-color-light); font-weight: 600; }
.pop-corner { position: sticky; left: 0; z-index: 2; background: var(--el-fill-color-light); }
.pop-size { position: sticky; left: 0; z-index: 1; }
.pop-price { cursor: pointer; display: inline-flex; align-items: center; gap: 4px; }
.pop-manual { color: var(--el-color-warning); font-weight: 600; }
.pop-na { background: var(--el-fill-color-blank); }
.pop-na-text { color: var(--el-text-color-placeholder); }
.pop-up { color: var(--el-color-danger); }
.pop-down { color: var(--el-color-success); }
.pop-sub { margin: 4px 0 0; }
</style>
