<template>
  <div>
    <!-- 卡片配置区 -->
    <h3 style="margin-bottom:12px">卡片配置</h3>
    <div style="margin-bottom:12px">
      <el-button type="primary" @click="addCard">+ 新增卡片</el-button>
    </div>
    <el-table :data="cardList" border stripe v-loading="cardLoading" style="margin-bottom:32px" :row-class-name="getCardRowClass">
      <!-- 拖拽手柄列 -->
      <el-table-column label="拖拽" width="48" align="center">
        <template #default="{ row, $index }">
          <i class="el-icon-rank" draggable="true" @dragstart="onCardDragStart($event, $index)" @dragover.prevent @dragenter.prevent @drop="onCardDrop($event, $index)" style="cursor:grab"></i>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="卡片名称" min-width="150" show-overflow-tooltip />
      <el-table-column label="卡片类型" width="120" align="center">
        <template #default="{ row }">
          <el-tag size="small">{{ cardTypeLabel(row.cardType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="metric" label="指标" width="120" show-overflow-tooltip>
        <template #default="{ row }">{{ metricLabel(row.metric) }}</template>
      </el-table-column>
      <el-table-column prop="sortOrder" label="排序" width="80" align="center" sortable />
      <el-table-column label="状态" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.isEnabled ? 'success' : 'danger'" size="small">{{ row.isEnabled ? '启用' : '停用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button link type="primary" @click="editCard(row)">编辑</el-button>
          <el-button link type="primary" @click="toggleCard(row)">{{ row.isEnabled ? '禁用' : '启用' }}</el-button>
          <el-button link type="danger" @click="deleteCard(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-empty v-if="!cardLoading && cardList.length === 0" description="暂无卡片配置，点击新增卡片添加" />

    <!-- 筛选配置区 -->
    <h3 style="margin-bottom:12px">筛选配置</h3>
    <div style="margin-bottom:12px">
      <el-button type="primary" @click="addFilter">+ 新增筛选</el-button>
    </div>
    <el-table :data="filterList" border stripe v-loading="filterLoading">
      <el-table-column prop="screenKey" label="筛选标识" width="120" show-overflow-tooltip />
      <el-table-column label="筛选类型" width="120" align="center">
        <template #default="{ row }">{{ filterTypeLabel(row.filterType) }}</template>
      </el-table-column>
      <el-table-column prop="filterValue" label="筛选值" min-width="150" show-overflow-tooltip />
      <el-table-column label="默认" width="60" align="center">
        <template #default="{ row }">
          <el-tag :type="row.isDefault ? 'success' : 'info'" size="small">{{ row.isDefault ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sortOrder" label="排序" width="80" align="center" sortable />
      <el-table-column label="操作" width="120" align="center">
        <template #default="{ row }">
          <el-button link type="primary" @click="editFilter(row)">编辑</el-button>
          <el-button link type="danger" @click="deleteFilter(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-empty v-if="!filterLoading && filterList.length === 0" description="暂无筛选配置" />

    <!-- 卡片弹窗 -->
    <el-dialog v-model="cardDialogVisible" :title="editingCardId ? '编辑卡片' : '新增卡片'" width="600px" destroy-on-close>
      <el-form ref="cardFormRef" :model="cardForm" :rules="cardRules" label-width="100px">
        <el-form-item label="卡片名称" prop="title"><el-input v-model="cardForm.title" maxlength="100" /></el-form-item>
        <el-form-item label="卡片标识" prop="cardKey"><el-input v-model="cardForm.cardKey" maxlength="50" :disabled="!!editingCardId" /></el-form-item>
        <el-form-item label="卡片类型" prop="cardType">
          <el-select v-model="cardForm.cardType" @change="onCardTypeChange">
            <el-option label="统计数字" value="stat_number" />
            <el-option label="柱状图" value="bar_chart" />
            <el-option label="折线图" value="line_chart" />
            <el-option label="饼图" value="pie_chart" />
            <el-option label="状态网格" value="status_grid" />
            <el-option label="排行榜" value="rank_list" />
          </el-select>
        </el-form-item>
        <el-form-item label="指标" prop="metric">
          <el-select v-model="cardForm.metric" clearable>
            <el-option label="在线数量" value="online_count" />
            <el-option label="零件计数" value="part_count" />
          </el-select>
        </el-form-item>
        <el-form-item label="维度" :required="needsDimension" :prop="needsDimension ? 'dimension' : ''">
          <el-select v-model="cardForm.dimension" clearable>
            <el-option label="车间" value="workshop" />
            <el-option label="工人" value="worker" />
            <el-option label="机床" value="machine" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序号" prop="sortOrder"><el-input-number v-model="cardForm.sortOrder" :min="1" :max="99" /></el-form-item>
        <el-form-item v-if="isChartType" label="图表配置" prop="chartConfig">
          <el-input v-model="cardForm.chartConfig" type="textarea" :rows="4" placeholder='{"xAxis":"workshop","yAxis":"part_count"}' />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cardDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="cardSubmitting" @click="saveCard">保存</el-button>
      </template>
    </el-dialog>

    <!-- 筛选弹窗 -->
    <el-dialog v-model="filterDialogVisible" :title="editingFilterId ? '编辑筛选' : '新增筛选'" width="500px" destroy-on-close>
      <el-form ref="filterFormRef" :model="filterForm" :rules="filterRules" label-width="100px">
        <el-form-item label="筛选标识" prop="screenKey"><el-input v-model="filterForm.screenKey" maxlength="50" /></el-form-item>
        <el-form-item label="筛选类型" prop="filterType">
          <el-select v-model="filterForm.filterType">
            <el-option label="车间" value="workshop" />
            <el-option label="品牌" value="brand" />
          </el-select>
        </el-form-item>
        <el-form-item label="筛选值" prop="filterValue"><el-input v-model="filterForm.filterValue" maxlength="100" /></el-form-item>
        <el-form-item label="默认选中"><el-switch v-model="filterForm.isDefault" /></el-form-item>
        <el-form-item label="排序号" prop="sortOrder"><el-input-number v-model="filterForm.sortOrder" :min="1" :max="99" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="filterDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="filterSubmitting" @click="saveFilter">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import request from '@/utils/request'
import { onBeforeUnmount } from 'vue'
import type { ScreenCard } from '@/types'

// ===== 卡片配置 =====
const cardLoading = ref(false)
const cardList = ref<ScreenCard[]>([])
const cardDialogVisible = ref(false)
const cardSubmitting = ref(false)
const editingCardId = ref<number | null>(null)
const cardFormRef = ref<FormInstance>()
const cardForm = reactive({
  title: '', cardKey: '', cardType: 'stat_number', metric: '', dimension: '', sortOrder: 1, chartConfig: '',
})

const needsDimension = computed(() => ['bar_chart', 'rank_list'].includes(cardForm.cardType))
const isChartType = computed(() => ['bar_chart', 'line_chart', 'pie_chart'].includes(cardForm.cardType))

const cardRules: FormRules = {
  title: [{ required: true, message: '请输入卡片名称', trigger: 'blur' }],
  cardKey: [{ required: true, message: '请输入卡片标识', trigger: 'blur' }],
  cardType: [{ required: true, message: '请选择卡片类型', trigger: 'change' }],
  metric: [{ required: true, message: '请选择指标', trigger: 'change' }],
  sortOrder: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
}

function cardTypeLabel(type: string): string {
  const map: Record<string, string> = { stat_number: '统计数字', bar_chart: '柱状图', line_chart: '折线图', pie_chart: '饼图', status_grid: '状态网格', rank_list: '排行榜' }
  return map[type] || type
}

function metricLabel(metric: string | null): string {
  if (!metric) return '-'
  const map: Record<string, string> = { online_count: '在线数量', part_count: '零件计数' }
  return map[metric] || metric
}

function filterTypeLabel(type: string): string {
  const map: Record<string, string> = { workshop: '车间', brand: '品牌' }
  return map[type] || type
}

function onCardTypeChange() {
  if (!needsDimension.value) cardForm.dimension = ''
  if (!isChartType.value) cardForm.chartConfig = ''
}

async function loadCards() {
  cardLoading.value = true
  try { const r = await request.get('/admin/screen-config') as any; cardList.value = r.data?.items || [] } finally { cardLoading.value = false }
}

// ===== 拖拽排序相关 =====
const draggingCardIndex = ref<number | null>(null)
const dragOverCardIndex = ref<number | null>(null)

function onCardDragStart(e: DragEvent, index: number) {
  draggingCardIndex.value = index
  if (e.dataTransfer) {
    e.dataTransfer.effectAllowed = 'move'
    e.dataTransfer.setData('text/plain', String(index))
  }
}

function onCardDrop(e: DragEvent, targetIndex: number) {
  const from = draggingCardIndex.value
  if (from == null || from === targetIndex) { draggingCardIndex.value = null; dragOverCardIndex.value = null; return }
  const moved = cardList.value.splice(from, 1)[0]
  cardList.value.splice(targetIndex, 0, moved)
  // 重排排序号并提交排序 API
  const payload = cardList.value.map((c, idx) => ({ id: c.id, sortOrder: idx + 1 }))
  request.post('/admin/screen-config/sort', payload).then(() => {
    loadCards()
  }).finally(() => {
    draggingCardIndex.value = null
    dragOverCardIndex.value = null
  })
}

function onCardDragOver(index: number) {
  dragOverCardIndex.value = index
}

function getCardRowClass(params: { row: Record<string,unknown>; rowIndex: number }) {
  return dragOverCardIndex.value === params.rowIndex ? 'drag-over' : ''
}

function addCard() {
  editingCardId.value = null
  Object.assign(cardForm, { title: '', cardKey: '', cardType: 'stat_number', metric: '', dimension: '', sortOrder: cardList.value.length + 1, chartConfig: '' })
  cardDialogVisible.value = true
}

function editCard(row: ScreenCard) {
  editingCardId.value = row.id
  Object.assign(cardForm, {
    title: row.title, cardKey: row.cardKey, cardType: row.cardType, metric: row.metric || '',
    dimension: row.dimension || '', sortOrder: row.sortOrder, chartConfig: row.chartConfig || '',
  })
  cardDialogVisible.value = true
}

async function saveCard() {
  const valid = await cardFormRef.value?.validate().catch(() => false)
  if (!valid) return
  // JSON校验
  if (isChartType.value && cardForm.chartConfig) {
    try { JSON.parse(cardForm.chartConfig) } catch { ElMessage.error('图表配置必须是有效的JSON格式'); return }
  }
  cardSubmitting.value = true
  try {
    const payload: Record<string,unknown> = { ...cardForm, isDefault: false, isEnabled: 1 }
    if (editingCardId.value) {
      await request.put(`/admin/screen-config/${editingCardId.value}`, { ...payload })
    } else {
      await request.post('/admin/screen-config', payload)
    }
    ElMessage.success('保存成功')
    cardDialogVisible.value = false
    loadCards()
  } finally { cardSubmitting.value = false }
}

async function toggleCard(row: ScreenCard) {
  await ElMessageBox.confirm(`确定${row.isEnabled ? '禁用' : '启用'}卡片【${row.title}】？`, '提示', { type: 'warning' })
  await request.put(`/admin/screen-config/${row.id}/toggle`)
  ElMessage.success('操作成功')
  loadCards()
}

async function deleteCard(row: ScreenCard) {
  await ElMessageBox.confirm(`确定删除卡片【${row.title}】？此操作不可恢复。`, '提示', { type: 'warning' })
  await request.delete(`/admin/screen-config/${row.id}`)
  ElMessage.success('已删除')
  loadCards()
}

// ===== 筛选配置 =====
const filterLoading = ref(false)
const filterList = ref<ScreenCard[]>([])
const filterDialogVisible = ref(false)
const filterSubmitting = ref(false)
const editingFilterId = ref<number | null>(null)
const filterFormRef = ref<FormInstance>()
const filterForm = reactive({
  screenKey: '', filterType: 'workshop', filterValue: '', isDefault: false, sortOrder: 1,
})

const filterRules: FormRules = {
  screenKey: [{ required: true, message: '请输入筛选标识', trigger: 'blur' }],
  filterType: [{ required: true, message: '请选择筛选类型', trigger: 'change' }],
  filterValue: [{ required: true, message: '请输入筛选值', trigger: 'blur' }],
  sortOrder: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
}

async function loadFilters() {
  filterLoading.value = true
  try { const r = await request.get('/admin/screen-filter') as any; filterList.value = r.data?.items || [] } finally { filterLoading.value = false }
}

function addFilter() {
  editingFilterId.value = null
  Object.assign(filterForm, { screenKey: 'screen_main', filterType: 'workshop', filterValue: '', isDefault: false, sortOrder: filterList.value.length + 1 })
  filterDialogVisible.value = true
}

function editFilter(row: ScreenCard) {
  editingFilterId.value = row.id
  Object.assign(filterForm, { screenKey: row.screenKey, filterType: row.filterType, filterValue: row.filterValue, isDefault: !!row.isDefault, sortOrder: row.sortOrder })
  filterDialogVisible.value = true
}

async function saveFilter() {
  const valid = await filterFormRef.value?.validate().catch(() => false)
  if (!valid) return
  filterSubmitting.value = true
  try {
    const payload: Record<string,unknown> = { ...filterForm, isDefault: filterForm.isDefault ? 1 : 0 }
    if (editingFilterId.value) {
      await request.put(`/admin/screen-filter/${editingFilterId.value}`, { ...payload })
    } else {
      await request.post('/admin/screen-filter', payload)
    }
    ElMessage.success('保存成功')
    filterDialogVisible.value = false
    loadFilters()
  } finally { filterSubmitting.value = false }
}

async function deleteFilter(row: ScreenCard) {
  await ElMessageBox.confirm(`确定删除该筛选配置？此操作不可恢复。`, '提示', { type: 'warning' })
  await request.delete(`/admin/screen-filter/${row.id}`)
  ElMessage.success('已删除')
  loadFilters()
}

onMounted(() => { loadCards(); loadFilters() })
</script>

<style scoped>
.drag-over {
  outline: 2px dashed #4fc3f7;
  background-color: rgba(76, 195, 247, 0.08);
}
</style>
