<template>
  <div class="page-container">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>签到配置</span>
          <el-button type="primary" :loading="saving" @click="handleSave">
            <el-icon><Check /></el-icon>保存配置
          </el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="140px"
        class="config-form"
      >
        <!-- 签到奖励配置 -->
        <el-divider content-position="left">7天签到奖励配置</el-divider>
        
        <el-alert
          title="签到奖励说明"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 20px;"
        >
          <template #default>
            <p>配置用户连续签到7天的每日奖励数量，奖励将以积分形式发放给用户。</p>
          </template>
        </el-alert>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="第1天奖励" prop="one_num">
              <el-input-number
                v-model="formData.one_num"
                :min="0"
                :max="99999"
                placeholder="请输入奖励数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="第2天奖励" prop="two_num">
              <el-input-number
                v-model="formData.two_num"
                :min="0"
                :max="99999"
                placeholder="请输入奖励数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="第3天奖励" prop="three_num">
              <el-input-number
                v-model="formData.three_num"
                :min="0"
                :max="99999"
                placeholder="请输入奖励数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="第4天奖励" prop="four_num">
              <el-input-number
                v-model="formData.four_num"
                :min="0"
                :max="99999"
                placeholder="请输入奖励数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="第5天奖励" prop="five_num">
              <el-input-number
                v-model="formData.five_num"
                :min="0"
                :max="99999"
                placeholder="请输入奖励数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="第6天奖励" prop="six_num">
              <el-input-number
                v-model="formData.six_num"
                :min="0"
                :max="99999"
                placeholder="请输入奖励数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="第7天奖励" prop="seven_num">
              <el-input-number
                v-model="formData.seven_num"
                :min="0"
                :max="99999"
                placeholder="请输入奖励数量"
                style="width: 100%"
              />
              <div class="form-tip">第7天为周期最后一天，建议设置较高奖励</div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 奖励预览 -->
        <el-divider content-position="left">奖励预览</el-divider>
        
        <div class="reward-preview">
          <div 
            v-for="(day, index) in rewardDays" 
            :key="index" 
            class="reward-day"
            :class="{ 'highlight': index === 6 }"
          >
            <div class="day-label">第{{ index + 1 }}天</div>
            <div class="day-reward">
              <el-icon><Present /></el-icon>
              <span>{{ day }}</span>
            </div>
          </div>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Check, Present } from '@element-plus/icons-vue'
import { getSignSetting, updateSignSetting, type SignSetting } from '@/api/business/config'

// 加载状态
const loading = ref(false)
const saving = ref(false)

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

// 表单数据
interface FormDataType {
  one_num: number
  two_num: number
  three_num: number
  four_num: number
  five_num: number
  six_num: number
  seven_num: number
}

const formData = reactive<FormDataType>({
  one_num: 0,
  two_num: 0,
  three_num: 0,
  four_num: 0,
  five_num: 0,
  six_num: 0,
  seven_num: 0
})

// 奖励预览数组
const rewardDays = computed(() => [
  formData.one_num,
  formData.two_num,
  formData.three_num,
  formData.four_num,
  formData.five_num,
  formData.six_num,
  formData.seven_num
])

// 数字验证器
const numberValidator = (_rule: any, value: number, callback: any) => {
  if (value === undefined || value === null) {
    callback(new Error('请输入奖励数量'))
  } else if (!Number.isInteger(value)) {
    callback(new Error('奖励数量必须为整数'))
  } else if (value < 0) {
    callback(new Error('奖励数量不能为负数'))
  } else {
    callback()
  }
}

// 表单验证规则
const formRules: FormRules = {
  one_num: [
    { required: true, message: '请输入第1天奖励', trigger: 'blur' },
    { validator: numberValidator, trigger: 'blur' }
  ],
  two_num: [
    { required: true, message: '请输入第2天奖励', trigger: 'blur' },
    { validator: numberValidator, trigger: 'blur' }
  ],
  three_num: [
    { required: true, message: '请输入第3天奖励', trigger: 'blur' },
    { validator: numberValidator, trigger: 'blur' }
  ],
  four_num: [
    { required: true, message: '请输入第4天奖励', trigger: 'blur' },
    { validator: numberValidator, trigger: 'blur' }
  ],
  five_num: [
    { required: true, message: '请输入第5天奖励', trigger: 'blur' },
    { validator: numberValidator, trigger: 'blur' }
  ],
  six_num: [
    { required: true, message: '请输入第6天奖励', trigger: 'blur' },
    { validator: numberValidator, trigger: 'blur' }
  ],
  seven_num: [
    { required: true, message: '请输入第7天奖励', trigger: 'blur' },
    { validator: numberValidator, trigger: 'blur' }
  ]
}

// 加载配置数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await getSignSetting()
    if (res.data?.value) {
      const data = res.data.value
      Object.assign(formData, {
        one_num: Number(data.one_num) || 0,
        two_num: Number(data.two_num) || 0,
        three_num: Number(data.three_num) || 0,
        four_num: Number(data.four_num) || 0,
        five_num: Number(data.five_num) || 0,
        six_num: Number(data.six_num) || 0,
        seven_num: Number(data.seven_num) || 0
      })
    }
  } catch (error) {
    ElMessage.error('加载配置失败')
    console.error('加载配置失败:', error)
  } finally {
    loading.value = false
  }
}

// 保存配置
const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
  } catch {
    ElMessage.warning('请检查表单填写是否正确')
    return
  }

  saving.value = true
  try {
    // 将数字类型转换为字符串类型（后端存储为字符串）
    const submitData: SignSetting = {
      one_num: String(formData.one_num),
      two_num: String(formData.two_num),
      three_num: String(formData.three_num),
      four_num: String(formData.four_num),
      five_num: String(formData.five_num),
      six_num: String(formData.six_num),
      seven_num: String(formData.seven_num)
    }

    await updateSignSetting(submitData)
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
    console.error('保存配置失败:', error)
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

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

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.config-form {
  max-width: 1000px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
}

:deep(.el-divider__text) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-alert p) {
  margin: 4px 0;
  line-height: 1.6;
}

/* 奖励预览样式 */
.reward-preview {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  border-radius: 8px;
}

.reward-day {
  flex: 1;
  min-width: 100px;
  max-width: 140px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.reward-day:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.reward-day.highlight {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  color: #fff;
}

.reward-day.highlight .day-label {
  color: rgba(255, 255, 255, 0.9);
}

.reward-day.highlight .day-reward {
  color: #fff;
}

.day-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.day-reward {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
}

.day-reward .el-icon {
  font-size: 16px;
}
</style>
