<template>
  <div class="memory-page">
    <!-- Stats row -->
    <div class="stats-row animate-in">
      <div class="stat-card">
        <div class="stat-icon" style="background: rgba(99,102,241,0.1)">
          <el-icon :size="20" color="#6366f1"><Memo /></el-icon>
        </div>
        <div class="stat-info">
          <span class="stat-value">{{ total }}</span>
          <span class="stat-label">总记录</span>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background: rgba(16,185,129,0.1)">
          <el-icon :size="20" color="#10b981"><CircleCheck /></el-icon>
        </div>
        <div class="stat-info">
          <span class="stat-value">{{ highConfidence }}</span>
          <span class="stat-label">高可信 (&gt;50)</span>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background: rgba(245,158,11,0.1)">
          <el-icon :size="20" color="#f59e0b"><Warning /></el-icon>
        </div>
        <div class="stat-info">
          <span class="stat-value">{{ mediumConfidence }}</span>
          <span class="stat-label">中可信 (10~50)</span>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background: rgba(239,68,68,0.1)">
          <el-icon :size="20" color="#ef4444"><Warning /></el-icon>
        </div>
        <div class="stat-info">
          <span class="stat-value">{{ lowConfidence }}</span>
          <span class="stat-label">低可信 (&lt;10)</span>
        </div>
      </div>
    </div>

    <!-- Main table card -->
    <div class="card animate-in animate-in-delay-1">
      <div class="card-head">
        <h3>商品记忆库</h3>
        <div class="card-actions">
          <el-input
            v-model="search"
            placeholder="搜索条码或名称..."
            clearable
            style="width: 240px"
            @input="debouncedSearch"
            @clear="loadData"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button size="small" @click="loadData" :icon="Refresh">刷新</el-button>
          <el-button size="small" type="primary" @click="openAdd">新增记录</el-button>
          <el-button size="small" type="warning" plain @click="reimport">重新导入</el-button>
        </div>
      </div>

      <el-table
        :data="items"
        v-loading="loading"
        stripe
        max-height="600"
        size="small"
        class="memory-table"
      >
        <el-table-column prop="barcode" label="条码" width="150" fixed>
          <template #default="{ row }">
            <span class="barcode-cell">{{ row.barcode }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="specification" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column label="均价" width="100">
          <template #default="{ row }">
            <span class="price-cell">{{ row.avg_price != null ? row.avg_price.toFixed(4) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="价格范围" width="140">
          <template #default="{ row }">
            <span v-if="row.price_count > 0" class="price-range">
              {{ row.min_price?.toFixed(2) }}~{{ row.max_price?.toFixed(2) }}
            </span>
            <span v-else class="text-muted">--</span>
          </template>
        </el-table-column>
        <el-table-column label="记录次数" width="90" align="center">
          <template #default="{ row }">
            <span :class="row.price_count > 3 ? 'count-high' : 'count-low'">{{ row.price_count || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="可信度" width="90" align="center">
          <template #default="{ row }">
            <span class="confidence-badge" :class="confCls(row.confidence)">
              {{ row.confidence }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="来源" width="75" align="center" />
        <el-table-column prop="use_count" label="出现" width="60" align="center" />
        <el-table-column label="操作" width="130" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="editItem(row)">编辑</el-button>
            <el-button type="danger" link size="small" @click="deleteItem(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-bar">
        <span class="pagination-info">共 {{ total }} 条记录</span>
        <el-pagination
          v-model:current-page="page"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          @current-change="loadData"
        />
      </div>
    </div>

    <!-- Edit dialog -->
    <el-dialog v-model="showEdit" :title="isAdd ? '新增记忆记录' : '编辑记忆记录'" width="480px" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="条码">
          <el-input v-model="editForm.barcode" :disabled="!isAdd" />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="规格">
          <el-input v-model="editForm.specification" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="editForm.unit" />
        </el-form-item>
        <el-form-item label="单价">
          <el-input-number v-model="editForm.price" :precision="4" :step="0.01" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="置信度">
          <el-slider v-model="editForm.confidence" :max="100" show-input />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEdit = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Memo, CircleCheck, Warning } from '@element-plus/icons-vue'
import api from '../api'
import { useDebounce } from '../composables/useDebounce'

const loading = ref(false)
const search = ref('')
const items = ref<any[]>([])
const page = ref(1)
const pageSize = ref(50)
const total = ref(0)

// Confidence stats from server-side (not just current page)
const confidenceStats = reactive({ high: 0, medium: 0, low: 0, total: 0 })
const highConfidence = computed(() => confidenceStats.high)
const mediumConfidence = computed(() => confidenceStats.medium)
const lowConfidence = computed(() => confidenceStats.low)

const showEdit = ref(false)
const isAdd = ref(false)
const editForm = reactive({
  barcode: '',
  name: '',
  specification: '',
  unit: '',
  price: 0,
  confidence: 50,
})

function confCls(c: number) {
  if (c > 50) return 'high'
  if (c >= 10) return 'mid'
  return 'low'
}

async function loadData() {
  loading.value = true
  try {
    const res = await api.get('/memory', {
      params: { search: search.value, page: page.value, page_size: pageSize.value },
    })
    items.value = res.data.items
    total.value = res.data.total
    // Update confidence stats from API response if available
    if (res.data.stats) {
      confidenceStats.high = res.data.stats.high || 0
      confidenceStats.medium = res.data.stats.medium || 0
      confidenceStats.low = res.data.stats.low || 0
      confidenceStats.total = res.data.stats.total || 0
    } else {
      // Fallback: stats not available from server, default to 0
      confidenceStats.high = 0
      confidenceStats.medium = 0
      confidenceStats.low = 0
      confidenceStats.total = 0
    }
  } catch (err: any) {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

// Debounced search
const { debounced: debouncedSearch, cancel: cancelSearch } = useDebounce(() => {
  page.value = 1
  loadData()
}, 400)

function openAdd() {
  isAdd.value = true
  editForm.barcode = ''
  editForm.name = ''
  editForm.specification = ''
  editForm.unit = ''
  editForm.price = 0
  editForm.confidence = 50
  showEdit.value = true
}

function editItem(row: any) {
  isAdd.value = false
  editForm.barcode = row.barcode
  editForm.name = row.name || ''
  editForm.specification = row.specification || ''
  editForm.unit = row.unit || ''
  editForm.price = row.price || 0
  editForm.confidence = row.confidence || 0
  showEdit.value = true
}

async function saveEdit() {
  if (!editForm.barcode) {
    ElMessage.warning('请输入条码')
    return
  }
  try {
    if (isAdd.value) {
      await api.post('/memory', {
        barcode: editForm.barcode,
        name: editForm.name,
        specification: editForm.specification,
        unit: editForm.unit,
        price: editForm.price,
        confidence: editForm.confidence,
      })
      ElMessage.success('添加成功')
    } else {
      await api.put(`/memory/${editForm.barcode}`, {
        name: editForm.name,
        specification: editForm.specification,
        unit: editForm.unit,
        price: editForm.price,
        confidence: editForm.confidence,
      })
      ElMessage.success('保存成功')
    }
    showEdit.value = false
    loadData()
  } catch (err: any) {
    ElMessage.error(err.response?.data?.detail || '保存失败')
  }
}

async function deleteItem(row: any) {
  try {
    await ElMessageBox.confirm(`确定删除 ${row.barcode} 的记忆记录？`, '确认')
    await api.delete(`/memory/${row.barcode}`)
    ElMessage.success('已删除')
    loadData()
  } catch (err: any) {
    if (err !== 'cancel') ElMessage.error('删除失败')
  }
}

async function reimport() {
  try {
    await ElMessageBox.confirm('将从模板文件重新导入商品数据，确定继续？', '确认')
    loading.value = true
    const res = await api.post('/memory/reimport')
    ElMessage.success(res.data.message)
    loadData()
  } catch (err: any) {
    if (err !== 'cancel') {
      ElMessage.error(err.response?.data?.detail || '导入失败')
    }
  } finally {
    loading.value = false
  }
}

onMounted(loadData)
onUnmounted(cancelSearch)
</script>

<style scoped>
.memory-page {
  width: 100%;
}

/* ── Stats row ── */
.stats-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 18px 20px;
  background: #fff;
  border-radius: 12px;
  border: 1px solid var(--border-light);
  transition: all 0.2s var(--ease-out);
}

.stat-card:hover {
  box-shadow: var(--shadow-md);
  transform: translateY(-2px);
}

.stat-icon {
  width: 44px;
  height: 44px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.stat-value {
  display: block;
  font-size: 24px;
  font-weight: 700;
  color: var(--text-primary);
  line-height: 1;
}

.stat-label {
  font-size: 13px;
  color: var(--text-secondary);
  margin-top: 2px;
}

/* ── Card ── */
.card {
  background: #fff;
  border: 1px solid var(--border-light);
  border-radius: 12px;
  padding: 20px;
  transition: box-shadow 0.2s;
}

.card:hover {
  box-shadow: var(--shadow-md);
}

.card-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.card-head h3 {
  font-size: 15px;
  font-weight: 600;
  color: var(--text-primary);
}

.card-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

/* ── Table ── */
.memory-table {
  border-radius: 10px;
  overflow: hidden;
}

.barcode-cell {
  font-family: var(--font-mono);
  font-size: 13px;
  color: var(--info);
}

.price-cell {
  font-family: var(--font-mono);
  font-size: 13px;
  font-weight: 500;
  color: var(--text-primary);
}

.confidence-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 600;
  font-family: var(--font-mono);
}

.confidence-badge.high {
  background: rgba(16,185,129,0.1);
  color: #10b981;
}

.confidence-badge.mid {
  background: rgba(245,158,11,0.1);
  color: #f59e0b;
}

.confidence-badge.low {
  background: rgba(239,68,68,0.1);
  color: #ef4444;
}

.price-range {
  font-size: 12px;
  font-family: var(--font-mono);
  color: var(--text-secondary);
}

.count-high {
  font-weight: 600;
  color: var(--success);
}

.count-low {
  color: var(--text-muted);
}

.text-muted {
  color: var(--text-muted);
  font-size: 12px;
}

/* ── Pagination ── */
.pagination-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid var(--border-subtle);
}

.pagination-info {
  font-size: 13px;
  color: var(--text-muted);
}
</style>
