<template>
  <el-dialog
    v-model="visible"
    title="赠送优惠券"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
    @open="handleOpen"
  >
    <div class="user-info" v-if="user">
      <el-avatar :src="user.avatar" :size="40">
        <el-icon><User /></el-icon>
      </el-avatar>
      <div class="user-detail">
        <div class="nickname">{{ user.nickname || '-' }}</div>
        <div class="uid">UID: {{ user.uid }}</div>
      </div>
    </div>

    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
      <!-- 优惠券选择 -->
      <el-form-item label="选择优惠券" prop="couponId">
        <el-select
          v-model="formData.couponId"
          placeholder="请选择优惠券"
          style="width: 100%"
          filterable
          :loading="couponLoading"
        >
          <el-option
            v-for="coupon in couponList"
            :key="coupon.id"
            :label="coupon.title"
            :value="coupon.id"
          >
            <div class="coupon-option">
              <span class="coupon-title">{{ coupon.title }}</span>
              <span class="coupon-value">
                满{{ coupon.minPrice }}减{{ coupon.discountPrice }}
              </span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 选中优惠券详情 -->
      <el-form-item label="优惠券详情" v-if="selectedCoupon">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="名称">{{ selectedCoupon.title }}</el-descriptions-item>
          <el-descriptions-item label="类型">{{ couponTypeText }}</el-descriptions-item>
          <el-descriptions-item label="面值">
            满{{ selectedCoupon.minPrice }}减{{ selectedCoupon.discountPrice }}
          </el-descriptions-item>
          <el-descriptions-item label="有效期">{{ selectedCoupon.validDays }}天</el-descriptions-item>
        </el-descriptions>
      </el-form-item>

      <!-- 赠送数量 -->
      <el-form-item label="赠送数量" prop="quantity">
        <el-input-number
          v-model="formData.quantity"
          :min="1"
          :max="maxQuantity"
          style="width: 200px"
        />
        <span class="quantity-tip" v-if="selectedCoupon?.stock">
          （最多可赠送 {{ selectedCoupon.stock }} 张）
        </span>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定赠送</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { User } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { giftCoupon, type UserListItem, type GiftCouponRequest } from '@/api/business/user'
import { request, type ApiResponse } from '@/utils/request'

// 优惠券类型定义
interface CouponTemplate {
  id: number
  title: string
  type: number      // 1-新人优惠券 2-权益优惠券 3-满减优惠券
  discountPrice: number  // 优惠金额（后端字段名）
  minPrice: number       // 最低消费（后端字段名）
  validDays: number      // 有效天数
  stock: number | null   // 库存（可能没有此字段）
  status: number
}

interface Props {
  modelValue: boolean
  user: UserListItem | null
}

const props = defineProps<Props>()

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

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const couponLoading = ref(false)
const couponList = ref<CouponTemplate[]>([])

const formData = reactive<GiftCouponRequest>({
  couponId: 0,
  quantity: 1
})

// 表单验证规则
const formRules: FormRules = {
  couponId: [{ required: true, message: '请选择优惠券', trigger: 'change' }],
  quantity: [
    { required: true, message: '请输入赠送数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ]
}

// 选中的优惠券
const selectedCoupon = computed(() => {
  return couponList.value.find(c => c.id === formData.couponId)
})

// 优惠券类型文本
const couponTypeText = computed(() => {
  if (!selectedCoupon.value) return ''
  const types: Record<number, string> = { 1: '新人优惠券', 2: '权益优惠券', 3: '满减优惠券' }
  return types[selectedCoupon.value.type] || '未知'
})

// 最大可赠送数量
const maxQuantity = computed(() => {
  return 999
})

// 加载优惠券列表
const loadCouponList = async () => {
  couponLoading.value = true
  try {
    // 调用优惠券模板列表API
    // 数据库中 status=0 表示启用
    const res: ApiResponse<CouponTemplate[]> = await request({
      url: '/admin/business/coupons/templates',
      method: 'get',
      params: { status: 0 }  // status=0 表示启用的优惠券
    })
    couponList.value = res.data || []
  } catch (error) {
    console.error('加载优惠券列表失败', error)
    couponList.value = []
  } finally {
    couponLoading.value = false
  }
}

// 对话框打开时
const handleOpen = () => {
  formData.couponId = 0
  formData.quantity = 1
  formRef.value?.resetFields()
  loadCouponList()
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
}

// 提交表单
const handleSubmit = async () => {
  if (!props.user) {
    ElMessage.warning('用户信息不存在')
    return
  }

  const valid = await formRef.value?.validate()
  if (!valid) return

  submitLoading.value = true
  try {
    await giftCoupon(props.user.id, formData)
    ElMessage.success('赠送成功')
    emit('success')
    handleClose()
  } catch (error: any) {
    ElMessage.error(error.message || '赠送失败')
  } finally {
    submitLoading.value = false
  }
}

// 监听优惠券选择变化，重置数量
watch(() => formData.couponId, () => {
  formData.quantity = 1
})
</script>

<style scoped>
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.user-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.nickname {
  font-weight: 500;
  font-size: 14px;
}

.uid {
  font-size: 12px;
  color: #909399;
}

.coupon-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.coupon-title {
  flex: 1;
}

.coupon-value {
  color: #e6a23c;
  font-size: 12px;
}

.quantity-tip {
  margin-left: 12px;
  color: #909399;
  font-size: 12px;
}
</style>
