<template>
  <el-dialog
    v-model="dialogVisible"
    title="广告类型管理"
    width="650px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="type-dialog-content">
      <!-- 添加类型按钮 -->
      <div class="action-bar">
        <el-button type="primary" size="small" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加类型
        </el-button>
      </div>

      <!-- 类型列表 -->
      <el-table :data="typeList" v-loading="loading" border stripe size="small">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        
        <el-table-column prop="name" label="类型名称" min-width="150">
          <template #default="{ row }">
            <template v-if="editingId === row.id">
              <el-input
                v-model="editForm.name"
                size="small"
                placeholder="请输入类型名称"
                @keyup.enter="handleSaveEdit(row)"
              />
            </template>
            <template v-else>
              {{ row.name }}
            </template>
          </template>
        </el-table-column>
        
        <el-table-column prop="sort" label="排序" width="120" align="center">
          <template #default="{ row }">
            <template v-if="editingId === row.id">
              <el-input-number
                v-model="editForm.sort"
                size="small"
                :min="0"
                :max="9999"
                controls-position="right"
              />
            </template>
            <template v-else>
              {{ row.sort }}
            </template>
          </template>
        </el-table-column>
        
        <el-table-column prop="advertCount" label="广告数量" width="100" align="center">
          <template #default="{ row }">
            <el-tag size="small" :type="row.advertCount > 0 ? 'success' : 'info'">
              {{ row.advertCount }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <template v-if="editingId === row.id">
              <el-button type="success" link size="small" @click="handleSaveEdit(row)">
                保存
              </el-button>
              <el-button type="info" link size="small" @click="handleCancelEdit">
                取消
              </el-button>
            </template>
            <template v-else>
              <el-button type="primary" link size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="danger" link size="small" @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增类型表单 -->
      <div v-if="showAddForm" class="add-form">
        <AdvertTypeForm
          ref="addFormRef"
          v-model="addForm"
          @submit="handleAddSubmit"
          @cancel="handleAddCancel"
        />
      </div>
    </div>

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import AdvertTypeForm from './AdvertTypeForm.vue'
import {
  getAdvertTypes,
  createAdvertType,
  updateAdvertType,
  deleteAdvertType,
  type AdvertTypeResponse,
  type AdvertTypeCreateRequest
} from '@/api/business/advert'

const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'refresh'): void
}>()

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 列表数据
const loading = ref(false)
const typeList = ref<AdvertTypeResponse[]>([])

// 新增表单
const showAddForm = ref(false)
const addFormRef = ref()
const addForm = reactive<AdvertTypeCreateRequest>({
  name: '',
  sort: 0
})

// 编辑状态
const editingId = ref<number | null>(null)
const editForm = reactive<AdvertTypeCreateRequest>({
  name: '',
  sort: 0
})

// 获取类型列表
const fetchTypes = async () => {
  loading.value = true
  try {
    const res = await getAdvertTypes()
    typeList.value = res.data
  } finally {
    loading.value = false
  }
}

// 监听弹窗打开
watch(() => props.modelValue, (visible) => {
  if (visible) {
    fetchTypes()
  }
})

// 显示新增表单
const handleAdd = () => {
  showAddForm.value = true
  addForm.name = ''
  addForm.sort = 0
}

// 提交新增
const handleAddSubmit = async () => {
  if (!addForm.name.trim()) {
    ElMessage.warning('请输入类型名称')
    return
  }

  // 检查名称是否重复
  const exists = typeList.value.some(t => t.name === addForm.name.trim())
  if (exists) {
    ElMessage.warning('类型名称已存在')
    return
  }

  try {
    await createAdvertType({
      name: addForm.name.trim(),
      sort: addForm.sort
    })
    ElMessage.success('添加成功')
    showAddForm.value = false
    fetchTypes()
    emit('refresh')
  } catch {
    // 错误处理
  }
}

// 取消新增
const handleAddCancel = () => {
  showAddForm.value = false
}

// 开始编辑
const handleEdit = (row: AdvertTypeResponse) => {
  editingId.value = row.id
  editForm.name = row.name
  editForm.sort = row.sort
}

// 保存编辑
const handleSaveEdit = async (row: AdvertTypeResponse) => {
  if (!editForm.name.trim()) {
    ElMessage.warning('请输入类型名称')
    return
  }

  // 检查名称是否重复（排除自身）
  const exists = typeList.value.some(t => t.name === editForm.name.trim() && t.id !== row.id)
  if (exists) {
    ElMessage.warning('类型名称已存在')
    return
  }

  try {
    await updateAdvertType(row.id, {
      name: editForm.name.trim(),
      sort: editForm.sort
    })
    ElMessage.success('更新成功')
    editingId.value = null
    fetchTypes()
    emit('refresh')
  } catch {
    // 错误处理
  }
}

// 取消编辑
const handleCancelEdit = () => {
  editingId.value = null
}

// 删除类型
const handleDelete = async (row: AdvertTypeResponse) => {
  // 检查是否有关联广告
  if (row.advertCount > 0) {
    ElMessage.warning(`该类型下有 ${row.advertCount} 个广告，无法删除`)
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除类型 "${row.name}" 吗？`,
      '删除确认',
      { type: 'warning' }
    )
    await deleteAdvertType(row.id)
    ElMessage.success('删除成功')
    fetchTypes()
    emit('refresh')
  } catch {
    // 取消操作
  }
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  showAddForm.value = false
  editingId.value = null
}
</script>

<style scoped>
.type-dialog-content {
  min-height: 200px;
}

.action-bar {
  margin-bottom: 16px;
}

.add-form {
  margin-top: 16px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
}
</style>
