<template>
  <el-dialog
    v-model="visible"
    title="选择商品"
    width="900px"
    append-to-body
    @close="handleClose"
  >
    <div class="product-selector">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <!-- 选择商品 -->
        <el-tab-pane label="选择商品" name="selectProduct">
          <div class="product-list-container">
            <!-- 搜索筛选区域 -->
            <div class="filter-section">
              <el-form :inline="true" :model="searchParams" class="search-form">
                <el-form-item label="商品分组">
                  <el-select
                    v-model="searchParams.good_group_id"
                    placeholder="全部分组"
                    clearable
                    style="width: 150px"
                  >
                    <el-option
                      v-for="item in groupOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="商品标签">
                  <el-select
                    v-model="searchParams.tag"
                    placeholder="全部标签"
                    :clearable="!defaultTag"
                    :disabled="!!defaultTag"
                    style="width: 150px"
                  >
                    <el-option
                      v-for="item in tagOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </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="productList"
              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="100" align="center" />
              <el-table-column label="商品图片" width="80" align="center">
                <template #default="{ row }">
                  <el-image
                    :src="row.image || '/logo.svg'"
                    fit="cover"
                    style="width: 50px; height: 50px; border-radius: 4px;"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="name" label="商品名称" min-width="180" show-overflow-tooltip />
              <el-table-column prop="table" label="所属表" width="120" show-overflow-tooltip />
              <el-table-column label="价格" width="100" align="right">
                <template #default="{ row }">
                  <span class="price">¥{{ (row.price / 100).toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="库存" width="80" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.inventory > 0 ? 'success' : 'danger'" size="small">
                    {{ row.inventory }}
                  </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="productList.length === 0 && !loading" description="暂无商品数据" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleConfirm"
          :disabled="!selectedProduct"
        >
          确定选择
        </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 { getProductList, getProductGroupList, getProductTagList } from '@/api/admin/product'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  // 当前已选中的商品ID（用于回显）
  currentProductId: {
    type: [String, Number],
    default: ''
  },
  // 默认标签过滤（设置后自动锁定该标签）
  defaultTag: {
    type: String,
    default: ''
  }
})

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

// 响应式数据
const visible = ref(false)
const activeTab = ref('selectProduct')
const loading = ref(false)
const productList = ref([])
const groupOptions = ref([])
const tagOptions = ref([])
const total = ref(0)
const selectedProduct = ref(null)

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

// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    activeTab.value = 'selectProduct'
    selectedProduct.value = null
    searchParams.page = 1
    if (props.defaultTag) {
      searchParams.tag = props.defaultTag
    }
    fetchGroupList()
    fetchTagList()
    fetchProductList()
  }
})

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

// 获取商品分组列表
const fetchGroupList = async () => {
  try {
    const res = await getProductGroupList({ page: 1, count: 10 })
    if (res.data.code === 200) {
      groupOptions.value = res.data.data.data || []
    }
  } catch (error) {
    console.error('获取分组列表失败:', error)
  }
}

// 获取商品标签列表
const fetchTagList = async () => {
  try {
    const res = await getProductTagList()
    if (res.data.code === 200) {
      tagOptions.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 获取商品列表
const fetchProductList = async () => {
  loading.value = true
  productList.value = []
  
  try {
    const params = {
      page: searchParams.page,
      count: searchParams.count
    }
    if (searchParams.good_group_id) {
      params.good_group_id = searchParams.good_group_id
    }
    if (searchParams.tag) {
      params.tag = searchParams.tag
    }
    
    const res = await getProductList(params)
    
    if (res.data.code === 200) {
      const allData = res.data.data.data || []
      // 过滤掉已删除的数据（兼容 delete 字段不存在的情况）
      productList.value = allData.filter(item => item.delete !== true)
      total.value = res.data.data.all_count ?? allData.length
      
      // cover 字段直接是图片 URL，无需再请求 file detail
      productList.value.forEach(item => {
        if (item.cover) item.image = item.cover
      })
      
      // 如果有当前选中的商品ID，自动选中
      if (props.currentProductId) {
        const currentProduct = productList.value.find(
          product => product.id === props.currentProductId
        )
        if (currentProduct) {
          selectedProduct.value = currentProduct
        }
      }
    } else {
      ElMessage.error(res.data.msg || '获取商品列表失败')
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 处理标签页切换
const handleTabClick = (tab) => {
  if (tab.paneName === 'selectProduct') {
    fetchProductList()
  }
}

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

// 重置搜索
const handleReset = () => {
  searchParams.good_group_id = ''
  searchParams.tag = props.defaultTag || ''
  searchParams.page = 1
  fetchProductList()
}

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

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

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

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

// 关闭对话框
const handleClose = () => {
  visible.value = false
  selectedProduct.value = null
  productList.value = []
  searchParams.good_group_id = ''
  searchParams.tag = props.defaultTag || ''
  searchParams.page = 1
  total.value = 0
}

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

<style scoped>
.product-selector {
  min-height: 450px;
}

.product-list-container {
  padding: 10px 0;
}

.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;
}

.price {
  color: #f56c6c;
  font-weight: 600;
}

.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;
}

/* 标签页样式 */
:deep(.el-tabs__header) {
  margin-bottom: 16px;
}

:deep(.el-tabs__item) {
  font-size: 15px;
  padding: 0 24px;
}

:deep(.el-tabs__item.is-active) {
  font-weight: 600;
}
</style>
