<template>
  <el-dialog
    v-model="visible"
    title="选择商品组"
    width="800px"
    append-to-body
    @close="handleClose"
  >
    <div class="group-selector">
      <!-- 搜索筛选区域 -->
      <div class="filter-section">
        <el-form :inline="true" class="search-form">
          <el-form-item>
            <el-input
              v-model="keyword"
              placeholder="搜索商品组名称"
              clearable
              style="width: 220px"
              @keyup.enter="handleSearch"
              @clear="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
            <el-button @click="handleReset" :icon="Refresh">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 商品组列表表格 -->
      <el-table
        v-loading="loading"
        :data="groupList"
        highlight-current-row
        @current-change="handleCurrentChange"
        style="width: 100%"
        :height="350"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="商品组名称" min-width="180" show-overflow-tooltip />
        <el-table-column label="父级ID" width="80" align="center">
          <template #default="{ row }">
            {{ row.parentId || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="标签" min-width="120">
          <template #default="{ row }">
            <el-tag v-if="row.tag" size="small" type="info">{{ row.tag?.name || row.tag }}</el-tag>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.disable ? 'danger' : 'success'" size="small">
              {{ row.disable ? '禁用' : '启用' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="searchParams.page"
          v-model:page-size="searchParams.count"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>

      <el-empty v-if="groupList.length === 0 && !loading" description="暂无商品组数据" />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleConfirm"
          :disabled="!selectedGroup"
        >
          确定选择
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getProductGroupList } from '@/api/admin/product'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  // 当前已选中的商品组ID（用于回显）
  currentGroupId: {
    type: [String, Number],
    default: ''
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'confirm'])

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const groupList = ref([])
const total = ref(0)
const selectedGroup = ref(null)
const keyword = ref('')

// 搜索参数
const searchParams = reactive({
  page: 1,
  count: 10
})

// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    selectedGroup.value = null
    keyword.value = ''
    searchParams.page = 1
    fetchGroupList()
  }
})

// 监听 visible 变化
watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 获取商品组列表
const fetchGroupList = async () => {
  loading.value = true
  groupList.value = []
  try {
    const params = {
      page: searchParams.page,
      count: searchParams.count
    }
    if (keyword.value.trim()) {
      params.keyword = keyword.value.trim()
    }
    const res = await getProductGroupList(params)
    const body = res?.data
    if (body?.code === 200 && body?.data) {
      const inner = body.data
      const items = Array.isArray(inner) ? inner : (inner.data || inner.list || [])
      // 过滤掉已删除的
      groupList.value = items.filter(item => !item.delete)
      total.value = inner.all_count ?? inner.total ?? groupList.value.length

      // 如果有当前选中的商品组ID，自动选中
      if (props.currentGroupId) {
        const current = groupList.value.find(
          g => g.id === Number(props.currentGroupId)
        )
        if (current) {
          selectedGroup.value = current
        }
      }
    } else {
      ElMessage.error(body?.message || '获取商品组列表失败')
    }
  } catch (error) {
    console.error('获取商品组列表失败:', error)
    ElMessage.error('获取商品组列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchParams.page = 1
  fetchGroupList()
}

// 重置搜索
const handleReset = () => {
  keyword.value = ''
  searchParams.page = 1
  fetchGroupList()
}

// 分页处理
const handleSizeChange = (size) => {
  searchParams.count = size
  searchParams.page = 1
  fetchGroupList()
}

const handlePageChange = (page) => {
  searchParams.page = page
  fetchGroupList()
}

// 选择商品组
const handleCurrentChange = (row) => {
  selectedGroup.value = row
}

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (selectedGroup.value && row.id === selectedGroup.value.id) {
    return 'selected-row'
  }
  return ''
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  selectedGroup.value = null
  groupList.value = []
  keyword.value = ''
  searchParams.page = 1
  total.value = 0
}

// 确认选择
const handleConfirm = () => {
  if (selectedGroup.value) {
    emit('confirm', selectedGroup.value)
    handleClose()
  } else {
    ElMessage.warning('请选择一个商品组')
  }
}
</script>

<style scoped>
.group-selector {
  min-height: 420px;
}

.filter-section {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 12px;
}

.text-muted {
  color: #c0c4cc;
  font-size: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 表格样式 */
:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.selected-row) {
  background-color: var(--el-color-primary-light-9) !important;
}

:deep(.selected-row td) {
  background-color: var(--el-color-primary-light-9) !important;
}

:deep(.el-table__body tr.current-row > td) {
  background-color: var(--el-color-primary-light-8) !important;
}
</style>
