<template>
  <el-dialog
    v-model="dialogVisible"
    title="奖励配置"
    width="700px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="reward-config-container">
      <div class="config-header">
        <span class="config-title">
          配置签到奖励 - {{ signConfig?.title || '' }}
        </span>
        <el-button type="primary" size="small" @click="addReward">
          <el-icon><Plus /></el-icon>添加奖励
        </el-button>
      </div>

      <el-form ref="formRef" :model="formData" label-width="0">
        <div v-if="formData.rewards.length === 0" class="empty-tip">
          暂无奖励配置，请点击"添加奖励"按钮添加
        </div>

        <div v-for="(reward, index) in formData.rewards" :key="index" class="reward-item">
          <el-card shadow="hover" class="reward-card">
            <div class="reward-row">
              <el-form-item
                :prop="`rewards.${index}.rewardType`"
                :rules="[{ required: true, message: '请选择奖励类型', trigger: 'change' }]"
                class="reward-type-item"
              >
                <el-select
                  v-model="reward.rewardType"
                  placeholder="选择奖励类型"
                  style="width: 140px"
                  @change="handleRewardTypeChange(index)"
                >
                  <el-option
                    v-for="(label, value) in RewardTypeLabels"
                    :key="value"
                    :label="label"
                    :value="Number(value)"
                  />
                </el-select>
              </el-form-item>

              <!-- 优惠券类型：显示优惠券选择 -->
              <el-form-item
                v-if="reward.rewardType === RewardType.Coupon"
                :prop="`rewards.${index}.rewardExtend`"
                :rules="[{ required: true, message: '请选择优惠券', trigger: 'change' }]"
                class="reward-value-item"
              >
                <el-select
                  v-model="reward.rewardExtend"
                  placeholder="请选择优惠券"
                  style="width: 280px"
                  filterable
                  :loading="couponLoading"
                >
                  <el-option
                    v-for="coupon in couponList"
                    :key="coupon.id"
                    :label="`${coupon.title} (满${coupon.minPrice}减${coupon.discountPrice})`"
                    :value="coupon.id"
                  />
                </el-select>
              </el-form-item>

              <!-- 非优惠券类型：显示数值输入 -->
              <el-form-item
                v-else
                :prop="`rewards.${index}.rewardValue`"
                :rules="[
                  { required: true, message: '请输入奖励数值', trigger: 'blur' },
                  { type: 'number', min: 1, message: '奖励数值必须大于0', trigger: 'blur' }
                ]"
                class="reward-value-item"
              >
                <el-input-number
                  v-model="reward.rewardValue"
                  :min="1"
                  :precision="0"
                  placeholder="奖励数值"
                  style="width: 200px"
                />
                <span class="reward-unit">{{ getRewardUnit(reward.rewardType) }}</span>
              </el-form-item>

              <el-button
                type="danger"
                :icon="Delete"
                circle
                size="small"
                @click="removeReward(index)"
                class="delete-btn"
              />
            </div>
          </el-card>
        </div>
      </el-form>
    </div>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import {
  updateSignConfigReward,
  type SignConfigResponse
} from '@/api/business/signconfig'
import {
  RewardType,
  RewardTypeLabels,
  type RewardItem
} from '@/api/business/reward'
import { getCoupons, type CouponResponse } from '@/api/business/coupon'

const props = defineProps<{
  modelValue: boolean
  signConfig: SignConfigResponse | null
}>()

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

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 表单引用
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 优惠券列表
const couponList = ref<CouponResponse[]>([])
const couponLoading = ref(false)

// 表单数据
interface FormDataType {
  rewards: RewardItem[]
}

const formData = reactive<FormDataType>({
  rewards: []
})

// 加载优惠券列表
const loadCoupons = async () => {
  couponLoading.value = true
  try {
    const res = await getCoupons({ page: 1, pageSize: 1000 })
    couponList.value = res.data.list
  } catch {
    couponList.value = []
  } finally {
    couponLoading.value = false
  }
}

// 监听弹窗打开，初始化数据
watch(() => props.modelValue, (visible) => {
  if (visible) {
    // 加载优惠券列表
    loadCoupons()
    
    // 从签到配置中加载现有奖励
    if (props.signConfig?.rewards && props.signConfig.rewards.length > 0) {
      formData.rewards = props.signConfig.rewards.map(r => ({
        rewardType: r.rewardType,
        rewardExtend: r.rewardExtend,
        rewardValue: r.rewardValue
      }))
    } else {
      formData.rewards = []
    }
  }
})

// 获取奖励单位
const getRewardUnit = (type: number): string => {
  switch (type) {
    case RewardType.Diamond:
      return '钻石'
    case RewardType.UUCoin:
      return 'HH币'
    case RewardType.DaDaCoin:
      return '哈尼券'
    default:
      return ''
  }
}

// 奖励类型变化处理
const handleRewardTypeChange = (index: number) => {
  const reward = formData.rewards[index]
  if (reward.rewardType === RewardType.Coupon) {
    reward.rewardValue = 1
    reward.rewardExtend = undefined
  } else {
    reward.rewardExtend = undefined
    reward.rewardValue = 1
  }
}

// 添加奖励
const addReward = () => {
  formData.rewards.push({
    rewardType: RewardType.Diamond,
    rewardValue: 1
  })
}

// 删除奖励
const removeReward = (index: number) => {
  formData.rewards.splice(index, 1)
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  formData.rewards = []
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  if (!props.signConfig) return

  // 验证表单
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  // 验证奖励配置
  for (const reward of formData.rewards) {
    if (reward.rewardType === RewardType.Coupon && !reward.rewardExtend) {
      ElMessage.error('请选择优惠券')
      return
    }
    if (reward.rewardType !== RewardType.Coupon && (!reward.rewardValue || reward.rewardValue <= 0)) {
      ElMessage.error('奖励数值必须大于0')
      return
    }
  }

  submitLoading.value = true
  try {
    const submitData = {
      rewards: formData.rewards.map(r => ({
        rewardType: r.rewardType,
        rewardExtend: r.rewardType === RewardType.Coupon ? r.rewardExtend : undefined,
        rewardValue: r.rewardType === RewardType.Coupon ? 1 : r.rewardValue
      }))
    }
    
    await updateSignConfigReward(props.signConfig.id, submitData)
    ElMessage.success('奖励配置更新成功')
    emit('success')
    handleClose()
  } finally {
    submitLoading.value = false
  }
}
</script>

<style scoped>
.reward-config-container {
  min-height: 200px;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.config-title {
  font-size: 14px;
  color: #606266;
}

.empty-tip {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.reward-item {
  margin-bottom: 12px;
}

.reward-card {
  background: #fafafa;
}

.reward-card :deep(.el-card__body) {
  padding: 12px 16px;
}

.reward-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.reward-type-item {
  margin-bottom: 0;
}

.reward-value-item {
  margin-bottom: 0;
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.reward-unit {
  color: #909399;
  font-size: 12px;
  white-space: nowrap;
}

.delete-btn {
  flex-shrink: 0;
}
</style>
