<template>
  <div class="discount-goods-container">
    <!-- 主容器 -->
    <el-card class="main-container" shadow="never">
      <!-- 搜索和操作栏 -->
      <div class="filter-section">
        <div class="filter-content">
          <el-form :inline="true" :model="queryParams" class="search-form">
            <el-form-item label="代金卷">
              <el-select 
                v-model="queryParams.code_id" 
                placeholder="请选择代金券"
                filterable
                clearable
                style="width: 280px"
              >
                <el-option
                  v-for="item in voucherListOptions"
                  :key="item.id"
                  :label="`${item.name} (¥${(item.amount / 100).toFixed(2)})`"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery" :disabled="!queryParams.code_id">
                <el-icon><Search /></el-icon>查询
              </el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="action-bar">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>新增商品关联
            </el-button>
            <el-button type="success" @click="fetchGoodsList">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
            <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 商品关联列表 -->
      <div class="table-section">
        <!-- 骨架屏 -->
        <div v-if="loading" class="skeleton-container">
          <div v-for="i in 5" :key="i" class="skeleton-row">
            <div class="skeleton-cell skeleton-checkbox"></div>
            <div class="skeleton-cell skeleton-id"></div>
            <div class="skeleton-cell skeleton-discount-id"></div>
            <div class="skeleton-cell skeleton-related-id"></div>
            <div class="skeleton-cell skeleton-name"></div>
            <div class="skeleton-cell skeleton-type"></div>
            <div class="skeleton-cell skeleton-note"></div>
            <div class="skeleton-cell skeleton-price"></div>
            <div class="skeleton-cell skeleton-time"></div>
            <div class="skeleton-cell skeleton-action"></div>
          </div>
        </div>

        <el-table
          v-else
          v-loading="loading"
          :data="goodsList"
          @selection-change="handleSelectionChange"
          style="width: 100%"
          :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="discountId" label="代金券ID" width="120" />
          <el-table-column label="关联对象ID" width="120">
            <template #default="{ row }">
              {{ row.goodId || row.goodGroupId || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="名称" min-width="200">
            <template #default="{ row }">
              {{ row.good?.name || row.goodGroup?.name || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getGoodsTypeTagByRow(row)">
                {{ getGoodsTypeNameByRow(row) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="150">
            <template #default="{ row }">
              {{ row.good?.table || row.goodGroup?.note || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="商品价格" width="120">
            <template #default="{ row }">
              <span v-if="row.good?.price" class="price">¥{{ (row.good.price / 100).toFixed(2) }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.CreatedAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
                <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.count"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 添加/编辑商品关联对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增商品关联' : '编辑商品关联'"
      width="600px"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="代金券" prop="code_id">
          <el-select 
            v-model="form.code_id" 
            placeholder="请选择代金券"
            filterable
            clearable
            :disabled="dialogType === 'edit'"
            style="width: 100%"
          >
            <el-option
              v-for="item in voucherListOptions"
              :key="item.id"
              :label="`${item.name} (¥${(item.amount / 100).toFixed(2)})`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="选择类型" prop="select_type" v-if="dialogType === 'add'">
          <el-radio-group v-model="form.select_type" @change="handleSelectTypeChange">
            <el-radio value="product">商品</el-radio>
            <el-radio value="product_group">商品组</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="选择商品" prop="selected_product" v-if="dialogType === 'add' && form.select_type === 'product'">
          <el-select 
            v-model="form.selected_product" 
            placeholder="请选择商品"
            filterable
            clearable
            style="width: 100%"
            @change="handleProductChange"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="`${item.name} (ID: ${item.id})`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="选择商品组" prop="selected_group" v-if="dialogType === 'add' && form.select_type === 'product_group'">
          <el-select 
            v-model="form.selected_group" 
            placeholder="请选择商品组"
            filterable
            clearable
            style="width: 100%"
            @change="handleProductGroupChange"
          >
            <el-option
              v-for="item in productGroupOptions"
              :key="item.id"
              :label="`${item.name} (ID: ${item.id})`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <!-- 编辑模式显示字段 -->
        <template v-if="dialogType === 'edit'">
          <el-form-item label="关联类型">
            <el-tag :type="form.goods_type === 'product' ? 'primary' : 'warning'">
              {{ form.goods_type === 'product' ? '商品' : '商品组' }}
            </el-tag>
          </el-form-item>
            <el-form-item label="关联对象ID">
              <el-select v-model="form.goods_id" style="width: 100%">
                <template v-if="form.goods_type === 'product'">
                  <el-option v-for="item in productOptions" :key="item.id" :label="`${item.name} (ID: ${item.id})`" :value="item.id" />
                </template>
                <template v-else>
                  <el-option v-for="item in productGroupOptions" :key="item.id" :label="`${item.name} (ID: ${item.id})`" :value="item.id" />
                </template>
              </el-select>
            </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Search, Plus, Refresh } from '@element-plus/icons-vue'
import { 
  getDiscountGoodsList, 
  addDiscountGoods,
  updateDiscountGoods,
  deleteDiscountGoods,
  getDiscountCodeList
} from '@/api/admin/discount'
import {
  getProductList,
  getProductGroupList
} from '@/api/admin/product'

// 查询参数
const queryParams = reactive({
  code_id: '',
  page: 1,
  count: 10
})

// 表单数据
const form = reactive({
  id: undefined,
  code_id: undefined,
  goods_id: undefined,
  goods_name: '',
  goods_type: '',
  select_type: 'product',  // 选择类型：product 或 product_group
  selected_product: undefined,  // 选中的商品ID
  selected_group: undefined  // 选中的商品组ID
})

const formRules = {
  code_id: [
    { required: true, message: '请选择代金券', trigger: 'change' }
  ],
  select_type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  selected_product: [
    { required: true, message: '请选择商品', trigger: 'change' }
  ],
  selected_group: [
    { required: true, message: '请选择商品组', trigger: 'change' }
  ],
  goods_id: [
    { required: true, message: '请输入商品ID', trigger: 'blur' }
  ],
  goods_name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  goods_type: [
    { required: true, message: '请选择商品类型', trigger: 'change' }
  ]
}

// 状态数据
const loading = ref(false)
const goodsList = ref([])
const total = ref(0)
const selectedRows = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const voucherListOptions = ref([])  // 代金券列表选项
const productOptions = ref([])  // 商品列表选项
const productGroupOptions = ref([])  // 商品组列表选项

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取商品类型名称（根据行数据）
const getGoodsTypeNameByRow = (row) => {
  // 判断是否有 goodGroup 对象（选择的是商品组）
  if (row.goodGroup) {
    return '商品组'
  }
  // 判断是否有 good 对象（选择的是商品）
  if (row.good) {
    return '商品'
  }
  return '-'
}

// 获取商品类型标签（根据行数据）
const getGoodsTypeTagByRow = (row) => {
  // 商品组用橙色
  if (row.goodGroup) {
    return 'warning'
  }
  // 商品用蓝色
  if (row.good) {
    return 'primary'
  }
  return 'info'
}

// 获取商品类型名称（兼容旧版）
const getGoodsTypeName = (type) => {
  const typeMap = {
    'product': '商品',
    'product_group': '商品组',
    'cloud_server': '云服务器',
    'cloud_database': '云数据库',
    'cloud_storage': '云存储',
    'cdn': 'CDN',
    'other': '其他'
  }
  return typeMap[type] || type
}

// 获取商品类型标签（兼容旧版）
const getGoodsTypeTag = (type) => {
  const tagMap = {
    'product': 'primary',
    'product_group': 'warning',
    'cloud_server': 'primary',
    'cloud_database': 'success',
    'cloud_storage': 'warning',
    'cdn': 'info',
    'other': 'default'
  }
  return tagMap[type] || 'default'
}

// 获取代金券列表选项
const fetchVoucherListOptions = async () => {
  try {
    const res = await getDiscountCodeList({
      page: 1,
      count: 1000,
      discount_type: 'coupon'
    })
    console.log('获取代金券列表:', res.data)
    if (res.data.code === 200) {
      voucherListOptions.value = res.data.data?.data || []
    }
  } catch (error) {
    console.error('获取代金券列表失败:', error)
    ElMessage.error('获取代金券列表失败')
  }
}

// 获取商品列表
const fetchProductList = async () => {
  try {
    const res = await getProductList({
      page: 1,
      count: 1000
    })
    console.log('获取商品列表:', res.data)
    if (res.data.code === 200) {
      productOptions.value = res.data.data?.data || []
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  }
}

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

// 选择类型变化
const handleSelectTypeChange = (type) => {
  form.selected_product = undefined
  form.selected_group = undefined
  form.goods_id = undefined
  form.goods_name = ''
  form.goods_type = ''
}

// 选择商品变化
const handleProductChange = (productId) => {
  const product = productOptions.value.find(item => item.id === productId)
  if (product) {
    form.goods_id = product.id
    form.goods_name = product.goodsName || product.name || ''
    form.goods_type = 'product'
  }
}

// 选择商品组变化
const handleProductGroupChange = (groupId) => {
  const group = productGroupOptions.value.find(item => item.id === groupId)
  if (group) {
    form.goods_id = group.id
    form.goods_name = group.name || ''
    form.goods_type = 'product_group'
  }
}

// 获取商品关联列表
const fetchGoodsList = async () => {
  if (!queryParams.code_id) {
    ElMessage.warning('请选择代金券进行查询')
    return
  }
  
  loading.value = true
  try {
    const res = await getDiscountGoodsList(queryParams)
    console.log('商品关联列表数据:', res.data)
    if (res.data.code === 200) {
      goodsList.value = res.data.data || []
      total.value = res.data.data?.length || 0
    }
  } catch (error) {
    console.error('获取商品关联列表失败:', error)
    ElMessage.error('获取商品关联列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  fetchGoodsList()
}

// 重置查询
const resetQuery = () => {
  queryParams.code_id = ''
  queryParams.page = 1
  goodsList.value = []
  total.value = 0
}

// 选择项变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页
const handleSizeChange = (size) => {
  queryParams.count = size
  fetchGoodsList()
}

const handleCurrentChange = (page) => {
  queryParams.page = page
  fetchGoodsList()
}

// 新增商品关联
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.assign(form, {
    id: undefined,
    code_id: queryParams.code_id ? Number(queryParams.code_id) : undefined,
    goods_id: undefined,
    goods_name: '',
    goods_type: '',
    select_type: 'product',
    selected_product: undefined,
    selected_group: undefined
  })
  formRef.value?.resetFields()
  
  // 加载商品和商品组列表
  fetchProductList()
  fetchProductGroupList()
}

// 编辑商品关联
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  
  // 判断是商品还是商品组
  let goodsId, goodsName, goodsType
  
  if (row.goodGroup) {
    // 商品组
    goodsId = row.goodGroupId
    goodsName = row.goodGroup.name
    goodsType = 'product_group'
  } else if (row.good) {
    // 商品
    goodsId = row.goodId
    goodsName = row.good.name
    goodsType = 'product'
  }
  
  Object.assign(form, {
    id: row.id,
    code_id: row.discountId,
    goods_id: goodsId,
    goods_name: goodsName,
    goods_type: goodsType
  })
  
  // 加载商品和商品组列表以便编辑
  fetchProductList()
  fetchProductGroupList()
}

// 删除商品关联
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除该商品关联吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteDiscountGoods({ 
        discount_good_id: String(row.id),
        code_id: String(row.discountId)
      })
      console.log('删除响应:', res.data)
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchGoodsList()
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条记录吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    loading.value = true
    try {
      const deletePromises = selectedRows.value.map(row => 
        deleteDiscountGoods({ 
          discount_good_id: String(row.id),
          code_id: String(row.discountId)
        })
      )
      
      const results = await Promise.allSettled(deletePromises)
      
      const successCount = results.filter(r => r.status === 'fulfilled' && r.value?.data?.code === 200).length
      const failCount = results.length - successCount
      
      if (failCount === 0) {
        ElMessage.success(`批量删除成功，共删除 ${successCount} 条记录`)
      } else if (successCount === 0) {
        ElMessage.error(`批量删除失败，所有 ${failCount} 条记录删除失败`)
      } else {
        ElMessage.warning(`批量删除完成，成功 ${successCount} 条，失败 ${failCount} 条`)
      }
      
      fetchGoodsList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除操作异常')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  // 新增模式下的额外验证
  if (dialogType.value === 'add') {
    if (!form.code_id) {
      ElMessage.warning('请选择代金券')
      return
    }
    if (form.select_type === 'product' && !form.selected_product) {
      ElMessage.warning('请选择商品')
      return
    }
    if (form.select_type === 'product_group' && !form.selected_group) {
      ElMessage.warning('请选择商品组')
      return
    }
    if (!form.goods_id || !form.goods_name || !form.goods_type) {
      ElMessage.warning('请先选择商品或商品组')
      return
    }
  }
  
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          code_id: String(form.code_id)
        }
        
        // 根据选择类型决定传 good_id 还是 good_group_id
        if (dialogType.value === 'add') {
          if (form.select_type === 'product') {
            // 选择的是商品，传 good_id
            submitData.good_ids = String(form.goods_id)
          } else if (form.select_type === 'product_group') {
            // 选择的是商品组，传 good_group_id
            submitData.good_group_ids = String(form.goods_id)
          }
        } else {
          // 编辑模式：传 discount_good_id
          submitData.discount_good_id = String(form.id)
          
          // 根据 goods_type 判断传 good_id 还是 good_group_id
          if (form.goods_type === 'product') {
            submitData.good_id = String(form.goods_id)
          } else if (form.goods_type === 'product_group') {
            submitData.good_group_id = String(form.goods_id)
          } else {
            // 其他类型默认使用 good_id
            submitData.good_id = String(form.goods_id)
          }
        }
        
        console.log('提交商品关联数据:', submitData)
        
        let res
        if (dialogType.value === 'add') {
          res = await addDiscountGoods(submitData)
        } else {
          res = await updateDiscountGoods(submitData)
        }
        
        console.log('提交响应:', res.data)
        if (res.data.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
          dialogVisible.value = false
          fetchGoodsList()
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

// 初始化
onMounted(() => {
  fetchVoucherListOptions()
  if (queryParams.code_id) {
    fetchGoodsList()
  }
})
</script>

<style scoped>
.discount-goods-container {
  padding: 0;
}

.main-container {
  border: 1px solid #e1e8ed;
  background: #ffffff;
}

.filter-section {
  padding: 0;
  border-bottom: 1px solid #e1e8ed;
  background: #fafbfc;
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  gap: 20px;
  flex-wrap: wrap;
}

.search-form {
  margin: 0;
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
}

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

.action-bar {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.table-section {
  padding: 0;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 14px;
}

.pagination {
  margin-top: 20px;
  padding: 16px 20px;
  border-top: 1px solid #e1e8ed;
  background: #fafbfc;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 0;
}

/* 表格样式优化 */
:deep(.el-table) {
  border: none;
  color: #2c3e50;
}

:deep(.el-table__header) {
  background: #f8f9fa;
}

:deep(.el-table th) {
  background: #f8f9fa !important;
  border-bottom: 2px solid #e1e8ed;
  color: #2c3e50;
  font-weight: 600;
  font-size: 13px;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f2f5;
  color: #34495e;
}

:deep(.el-table tr:hover > td) {
  background-color: #f8f9fa !important;
}

:deep(.el-card__body) {
  padding: 0;
}

/* 骨架屏样式 */
.skeleton-container {
  padding: 20px;
}

.skeleton-row {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  gap: 16px;
}

.skeleton-row:last-child {
  border-bottom: none;
}

.skeleton-cell {
  height: 20px;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s ease-in-out infinite;
  border-radius: 4px;
}

.skeleton-checkbox { width: 55px; }
.skeleton-id { width: 80px; }
.skeleton-discount-id { width: 120px; }
.skeleton-related-id { width: 120px; }
.skeleton-name { width: 200px; }
.skeleton-type { width: 120px; }
.skeleton-note { width: 150px; }
.skeleton-price { width: 120px; }
.skeleton-time { width: 180px; }
.skeleton-action { width: 200px; height: 32px; }

@keyframes skeleton-loading {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}
</style>
