<template>
  <div class="discount-code-container">
    <!-- 主容器 -->
    <el-card class="main-container" shadow="never">
      <!-- 搜索和操作栏 -->
      <div class="filter-section">
        <div class="filter-content">
          <div class="action-bar">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>新增优惠码
            </el-button>
            <el-button type="success" @click="fetchDiscountList">
              <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-code"></div>
            <div class="skeleton-cell skeleton-name"></div>
            <div class="skeleton-cell skeleton-type"></div>
            <div class="skeleton-cell skeleton-value"></div>
            <div class="skeleton-cell skeleton-min"></div>
            <div class="skeleton-cell skeleton-max"></div>
            <div class="skeleton-cell skeleton-times"></div>
            <div class="skeleton-cell skeleton-action"></div>
          </div>
        </div>

        <el-table
          v-else
          v-loading="loading"
          :data="discountList"
          @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="code" label="优惠码" min-width="150" />
          <el-table-column prop="name" label="名称" min-width="180" />
          <el-table-column label="优惠类型" width="120">
            <template #default="{ row }">
              <el-tag :type="row.percentage ? 'success' : 'primary'">
                {{ row.percentage ? '百分比折扣' : '固定金额' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="优惠值" width="120">
            <template #default="{ row }">
              <span v-if="row.percentage" class="discount-value">{{ (row.percentage / 100).toFixed(0) }}%</span>
              <span v-else class="amount">¥{{ (row.amount / 100).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="最低消费" width="120">
            <template #default="{ row }">
              ¥{{ (row.minAmount / 100).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="最大抵扣" width="120">
            <template #default="{ row }">
              <span v-if="row.maxAmount">¥{{ (row.maxAmount / 100).toFixed(2) }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="maxTimes" label="最大使用次数" width="120" />
          <el-table-column prop="userTimes" label="单用户次数" width="120" />
          <el-table-column label="可叠加" width="100" align="center">
            <template #default="{ row }">
              <el-icon v-if="row.canStacking" color="#67c23a" :size="20"><SuccessFilled /></el-icon>
              <el-icon v-else color="#f56c6c" :size="20"><CircleCloseFilled /></el-icon>
            </template>
          </el-table-column>
          <el-table-column label="续费可用" width="100" align="center">
            <template #default="{ row }">
              <el-icon v-if="row.renew" color="#67c23a" :size="20"><SuccessFilled /></el-icon>
              <el-icon v-else color="#f56c6c" :size="20"><CircleCloseFilled /></el-icon>
            </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="success" link @click="handleView(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="700px"
      append-to-body
    >
      <el-form
        ref="discountFormRef"
        :model="discountForm"
        :rules="discountRules"
        label-width="140px"
      >
        <el-form-item label="优惠码" prop="code">
          <el-input v-model="discountForm.code" placeholder="请输入优惠码" />
        </el-form-item>
        <el-form-item label="优惠码名称" prop="name">
          <el-input v-model="discountForm.name" placeholder="请输入优惠码名称" />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="discountForm.note" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="优惠类型" prop="discount_mode">
          <el-radio-group v-model="discountForm.discount_mode">
            <el-radio label="amount">固定金额</el-radio>
            <el-radio label="percentage">百分比折扣</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="discountForm.discount_mode === 'amount'" label="优惠金额" prop="amount">
          <div class="unit-input-row">
            <el-input-number v-model="discountForm.amount" :min="0" :precision="2" :step="0.01" placeholder="请输入优惠金额" style="flex:1" />
            <span class="unit-text">元</span>
          </div>
        </el-form-item>
        <el-form-item v-if="discountForm.discount_mode === 'percentage'" label="优惠百分比(%)" prop="percentage">
          <el-input-number v-model="discountForm.percentage" :min="0" :max="100" :precision="0" placeholder="请输入百分比(1-100)" style="width: 100%" />
        </el-form-item>
        <el-form-item label="最低消费" prop="min_amount">
          <div class="unit-input-row">
            <el-input-number v-model="discountForm.min_amount" :min="0" :precision="2" :step="0.01" placeholder="满多少可使用" style="flex:1" />
            <span class="unit-text">元</span>
          </div>
        </el-form-item>
        <el-form-item label="最大抵扣" prop="max_amount">
          <div class="unit-input-row">
            <el-input-number v-model="discountForm.max_amount" :min="0" :precision="2" :step="0.01" placeholder="0表示无限制" style="flex:1" />
            <span class="unit-text">元</span>
          </div>
        </el-form-item>
        <el-form-item label="最大使用次数" prop="max_times">
          <el-input-number v-model="discountForm.max_times" :min="0" placeholder="0表示无限制" style="width: 100%" />
        </el-form-item>
        <el-form-item label="单用户最大次数" prop="user_times">
          <el-input-number v-model="discountForm.user_times" :min="0" placeholder="0表示无限制" style="width: 100%" />
        </el-form-item>
        <el-form-item label="有效期" prop="timeRange">
          <el-date-picker
            v-model="discountForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :teleported="true"
            popper-class="discount-date-picker"
            placement="top-start"
            :editable="true"
            :clearable="true"
            style="width: 100%"
            @keyup.enter="handleDatePickerEnter"
          />
        </el-form-item>
        <el-form-item label="续费可用" prop="renew">
          <el-switch v-model="discountForm.renew" active-text="是" inactive-text="否" />
        </el-form-item>
        <el-form-item label="同类型可叠加" prop="can_stacking">
          <el-switch v-model="discountForm.can_stacking" active-text="是" inactive-text="否" />
        </el-form-item>
        <el-form-item label="其他类型可叠加" prop="can_combine">
          <el-switch v-model="discountForm.can_combine" active-text="是" inactive-text="否" />
        </el-form-item>
      </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>

    <!-- 详情查看对话框 -->
    <DiscountDetailDialog
      v-model="detailDialogVisible"
      type="code"
      :detail-data="currentDetail"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Search, Refresh, SuccessFilled, CircleCloseFilled } from '@element-plus/icons-vue'
import { 
  getDiscountCodeList, 
  getDiscountCodeDetail, 
  createDiscountCode, 
  updateDiscountCode, 
  deleteDiscountCode 
} from '@/api/admin/discount'
import { timeToTimestamp } from '@/utils/tool'
import DiscountDetailDialog from '@/components/marketing/DiscountDetailDialog.vue'

// 查询参数
const queryParams = reactive({
  discount_type: 'code',  // 固定为code表示优惠码
  page: 1,
  count: 10
})

// 优惠码表单
const discountForm = reactive({
  code_id: undefined,
  discount_type: 'code',  // 固定为code
  code: '',
  name: '',
  note: '',
  discount_mode: 'amount',  // amount 或 percentage
  amount: 0,
  percentage: 0,
  min_amount: 0,
  max_amount: 0,
  max_times: 0,
  user_times: 0,
  timeRange: [],
  renew: false,
  can_stacking: false,
  can_combine: false
})

const discountRules = {
  code: [
    { required: true, message: '请输入优惠码', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入优惠码名称', trigger: 'blur' }
  ],
  discount_mode: [
    { required: true, message: '请选择优惠类型', trigger: 'change' }
  ]
}

// 状态数据
const loading = ref(false)
const discountList = ref([])
const total = ref(0)
const selectedRows = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const discountFormRef = ref(null)
const detailDialogVisible = ref(false)
const currentDetail = ref(null)

// 获取优惠码列表
const fetchDiscountList = async () => {
  loading.value = true
  try {
    const res = await getDiscountCodeList(queryParams)
    console.log('优惠码列表数据:', res.data)
    if (res.data.code === 200) {
      discountList.value = res.data.data?.data || []
      total.value = res.data.data?.all_count || 0
    }
  } catch (error) {
    console.error('获取优惠码列表失败:', error)
    ElMessage.error('获取优惠码列表失败')
  } finally {
    loading.value = false
  }
}

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

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

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

// 新增优惠码
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.assign(discountForm, {
    code_id: undefined,
    discount_type: 'code',
    code: '',
    name: '',
    note: '',
    discount_mode: 'amount',
    amount: 0,
    percentage: 0,
    min_amount: 0,
    max_amount: 0,
    max_times: 0,
    user_times: 0,
    timeRange: [],
    renew: false,
    can_stacking: false,
    can_combine: false
  })
  discountFormRef.value?.resetFields()
}

// 编辑优惠码
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  
  // 转换日期字符串为日期选择器格式
  const startTime = row.startTime ? new Date(row.startTime).toLocaleString('zh-CN', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'}).replace(/\//g, '-') : ''
  const endTime = row.endTime ? new Date(row.endTime).toLocaleString('zh-CN', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'}).replace(/\//g, '-') : ''
  
  Object.assign(discountForm, {
    code_id: row.id,
    discount_type: 'code',
    code: row.code,
    name: row.name,
    note: row.note || '',
    discount_mode: row.percentage ? 'percentage' : 'amount',
    amount: row.amount ? row.amount / 100 : 0,
    percentage: row.percentage ? row.percentage / 100 : 0,
    min_amount: row.minAmount ? row.minAmount / 100 : 0,
    max_amount: row.maxAmount ? row.maxAmount / 100 : 0,
    max_times: row.maxTimes || 0,
    user_times: row.userTimes || 0,
    timeRange: startTime && endTime ? [startTime, endTime] : [],
    renew: row.renew || false,
    can_stacking: row.canStacking || false,
    can_combine: row.canCombine || false
  })
}

// 查看优惠码详情
const handleView = async (row) => {
  try {
    const res = await getDiscountCodeDetail({ code_id: row.id })
    console.log('优惠码详情:', res.data)
    if (res.data.code === 200) {
      currentDetail.value = res.data.data
      detailDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取优惠码详情失败:', error)
    ElMessage.error('获取优惠码详情失败')
  }
}

// 删除优惠码
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除优惠码 ${row.code} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteDiscountCode({ code_id: row.id })
      console.log('删除响应:', res.data)
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchDiscountList()
      }
    } 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 => 
        deleteDiscountCode({ code_id: row.id })
      )
      
      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} 条`)
      }
      
      fetchDiscountList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除操作异常')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 处理日期选择器回车事件
const handleDatePickerEnter = (event) => {
  // 回车键确认日期选择
  const datePicker = event.target.closest('.el-date-editor')
  if (datePicker) {
    // 触发失焦事件，确认日期选择
    event.target.blur()
  }
}

// 提交表单
const submitForm = () => {
  discountFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          discount_type: 'code',
          code: discountForm.code,
          name: discountForm.name,
          note: discountForm.note,
          min_amount: Math.round(discountForm.min_amount * 100),
          max_amount: Math.round(discountForm.max_amount * 100),
          max_times: discountForm.max_times || 0,
          user_times: discountForm.user_times || 0,
          renew: discountForm.renew,
          can_stacking: discountForm.can_stacking,
          can_combine: discountForm.can_combine
        }
        
        // 根据优惠类型设置amount或percentage
        if (discountForm.discount_mode === 'percentage') {
          submitData.percentage = Math.round(discountForm.percentage * 100)
          submitData.amount = 0
        } else {
          submitData.amount = Math.round(discountForm.amount * 100)
          submitData.percentage = 0
        }
        
        // 处理时间（转换为秒级时间戳）
        if (discountForm.timeRange && discountForm.timeRange.length === 2) {
          submitData.start_time = timeToTimestamp(discountForm.timeRange[0])
          submitData.end_time = timeToTimestamp(discountForm.timeRange[1])
        } else {
          submitData.start_time = ''
          submitData.end_time = ''
        }
        
        // 如果是编辑，添加code_id
        if (dialogType.value === 'edit') {
          submitData.code_id = discountForm.code_id
        }

        console.log('提交优惠码数据:', submitData)

        let res
        if (dialogType.value === 'add') {
          res = await createDiscountCode(submitData)
        } else {
          res = await updateDiscountCode(submitData)
        }
        
        console.log('提交响应:', res.data)
        if (res.data.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
          dialogVisible.value = false
          fetchDiscountList()
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

// 初始化
onMounted(() => {
  fetchDiscountList()
})
</script>

<style scoped>
.discount-code-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: flex-end;
  align-items: center;
  padding: 16px 20px;
  gap: 20px;
  flex-wrap: wrap;
}

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

.table-section {
  padding: 0;
}

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

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

.discount-value {
  color: #67c23a;
  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-code { width: 150px; }
.skeleton-name { width: 180px; }
.skeleton-type { width: 120px; }
.skeleton-value { width: 120px; }
.skeleton-min { width: 120px; }
.skeleton-max { width: 120px; }
.skeleton-times { width: 120px; }
.skeleton-action { width: 200px; height: 32px; }

@keyframes skeleton-loading {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

.unit-input-row { display: flex; align-items: center; gap: 6px; width: 100%; }
.unit-text { font-size: 13px; color: #606266; flex-shrink: 0; white-space: nowrap; }
</style>

<style>
/* 时间选择器弹出层样式 - 非 scoped */
.discount-date-picker {
  z-index: 9999 !important;
}

.discount-date-picker .el-picker-panel {
  max-width: 90vw;
}
</style>
