<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="650px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入标题"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item :label="dayLabel" prop="day">
        <el-input-number
          v-model="formData.day"
          :min="1"
          :max="365"
          :precision="0"
          placeholder="请输入天数"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="图标" prop="icon">
        <ImageUpload
          v-model="formData.icon"
          placeholder="点击上传图标"
          :show-url-input="true"
          tip="支持 jpg、png、gif、webp 格式，最大 10MB"
        />
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="formData.sort"
          :min="0"
          :max="9999"
          :precision="0"
          placeholder="请输入排序值"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入描述（可选）"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <!-- 新增时显示奖励配置 -->
      <template v-if="!isEdit">
        <el-divider content-position="left">奖励配置</el-divider>
        
        <div class="reward-config-section">
          <div v-for="(reward, index) in formData.rewards" :key="index" class="reward-item">
            <el-row :gutter="12" align="middle">
              <el-col :span="7">
                <el-form-item
                  :prop="`rewards.${index}.rewardType`"
                  :rules="[{ required: true, message: '请选择奖励类型', trigger: 'change' }]"
                  label-width="0"
                >
                  <el-select
                    v-model="reward.rewardType"
                    placeholder="奖励类型"
                    style="width: 100%"
                    @change="handleRewardTypeChange(index)"
                  >
                    <el-option
                      v-for="(label, value) in RewardTypeLabels"
                      :key="value"
                      :label="label"
                      :value="Number(value)"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <!-- 优惠券类型：显示优惠券选择 -->
                <el-form-item
                  v-if="reward.rewardType === RewardType.Coupon"
                  :prop="`rewards.${index}.rewardExtend`"
                  :rules="[{ required: true, message: '请选择优惠券', trigger: 'change' }]"
                  label-width="0"
                >
                  <el-select
                    v-model="reward.rewardExtend"
                    placeholder="请选择优惠券"
                    style="width: 100%"
                    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' }
                  ]"
                  label-width="0"
                >
                  <el-input-number
                    v-model="reward.rewardValue"
                    :min="1"
                    :precision="0"
                    placeholder="奖励数值"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              
              <el-col :span="5">
                <el-button
                  type="danger"
                  :icon="Delete"
                  circle
                  size="small"
                  @click="removeReward(index)"
                  :disabled="formData.rewards.length <= 1"
                />
              </el-col>
            </el-row>
          </div>
          
          <el-button type="primary" link @click="addReward">
            <el-icon><Plus /></el-icon>添加奖励
          </el-button>
        </div>
      </template>
    </el-form>

    <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, type FormRules } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
import {
  createSignConfig,
  updateSignConfig,
  SignType,
  SignTypeLabels,
  type SignConfigResponse,
  type SignConfigCreateRequest,
  type SignConfigUpdateRequest
} 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
  isEdit: boolean
  signType: number
}>()

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 dialogTitle = computed(() => {
  const typeName = SignTypeLabels[props.signType] || '签到'
  return props.isEdit ? `编辑${typeName}配置` : `新增${typeName}配置`
})

// 天数标签
const dayLabel = computed(() => {
  return props.signType === SignType.Daily ? '签到天数' : '累计天数'
})

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

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

// 表单数据
interface FormDataType {
  title: string
  day: number
  icon: string
  sort: number
  description: string
  rewards: RewardItem[]
}

const formData = reactive<FormDataType>({
  title: '',
  day: 1,
  icon: '',
  sort: 0,
  description: '',
  rewards: [{ rewardType: RewardType.Diamond, rewardValue: 1 }]
})

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  day: [
    { required: true, message: '请输入天数', trigger: 'blur' },
    { type: 'number', min: 1, message: '天数必须大于0', trigger: 'blur' }
  ]
}

// 加载优惠券列表
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.isEdit && props.signConfig) {
      // 编辑模式：回显数据
      Object.assign(formData, {
        title: props.signConfig.title || '',
        day: props.signConfig.day || 1,
        icon: props.signConfig.icon || '',
        sort: props.signConfig.sort || 0,
        description: props.signConfig.description || '',
        rewards: [{ rewardType: RewardType.Diamond, rewardValue: 1 }]
      })
    } else {
      // 新增模式：重置数据
      resetForm()
    }
  }
})

// 奖励类型变化处理
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) => {
  if (formData.rewards.length > 1) {
    formData.rewards.splice(index, 1)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    title: '',
    day: 1,
    icon: '',
    sort: 0,
    description: '',
    rewards: [{ rewardType: RewardType.Diamond, rewardValue: 1 }]
  })
  formRef.value?.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

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

  try {
    await formRef.value.validate()
  } catch {
    return
  }

  // 新增时验证奖励配置
  if (!props.isEdit) {
    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 {
    if (props.isEdit && props.signConfig) {
      // 编辑模式
      const submitData: SignConfigUpdateRequest = {
        type: props.signType,
        day: formData.day,
        title: formData.title,
        icon: formData.icon || undefined,
        sort: formData.sort,
        description: formData.description || undefined
      }
      await updateSignConfig(props.signConfig.id, submitData)
      ElMessage.success('更新成功')
    } else {
      // 新增模式
      const submitData: SignConfigCreateRequest = {
        type: props.signType,
        day: formData.day,
        title: formData.title,
        icon: formData.icon || undefined,
        sort: formData.sort,
        description: formData.description || undefined,
        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 createSignConfig(submitData)
      ElMessage.success('创建成功')
    }

    emit('success')
    handleClose()
  } finally {
    submitLoading.value = false
  }
}
</script>

<style scoped>
.reward-config-section {
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
}

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

.reward-item:last-child {
  margin-bottom: 8px;
}
</style>
