<template>
  <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-alert
        title="排行榜统计说明"
        type="info"
        :closable="false"
        show-icon
        style="margin-bottom: 20px;"
      >
        <template #default>
          <p>配置各排行榜的统计周期。选择"自定义"时需要设置具体的时间范围。</p>
        </template>
      </el-alert>

      <!-- 达达券排行榜 -->
      <el-divider content-position="left">达达券排行榜</el-divider>
      
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="统计方式" prop="dadajuan_stat_type">
            <el-select v-model="formData.dadajuan_stat_type" placeholder="请选择统计方式" style="width: 100%">
              <el-option label="每日" value="daily" />
              <el-option label="每周" value="weekly" />
              <el-option label="每月" value="monthly" />
              <el-option label="每年" value="yearly" />
              <el-option label="自定义" value="custom" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.dadajuan_stat_type === 'custom'">
          <el-form-item label="开始时间" prop="dadajuan_start_time">
            <el-date-picker
              v-model="formData.dadajuan_start_time"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.dadajuan_stat_type === 'custom'">
          <el-form-item label="结束时间" prop="dadajuan_end_time">
            <el-date-picker
              v-model="formData.dadajuan_end_time"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 钻石排行榜 -->
      <el-divider content-position="left">钻石排行榜</el-divider>
      
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="统计方式" prop="diamond_stat_type">
            <el-select v-model="formData.diamond_stat_type" placeholder="请选择统计方式" style="width: 100%">
              <el-option label="每日" value="daily" />
              <el-option label="每周" value="weekly" />
              <el-option label="每月" value="monthly" />
              <el-option label="每年" value="yearly" />
              <el-option label="自定义" value="custom" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.diamond_stat_type === 'custom'">
          <el-form-item label="开始时间" prop="diamond_start_time">
            <el-date-picker
              v-model="formData.diamond_start_time"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.diamond_stat_type === 'custom'">
          <el-form-item label="结束时间" prop="diamond_end_time">
            <el-date-picker
              v-model="formData.diamond_end_time"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- HH币排行榜 -->
      <el-divider content-position="left">HH币排行榜</el-divider>
      
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="统计方式" prop="integral_stat_type">
            <el-select v-model="formData.integral_stat_type" placeholder="请选择统计方式" style="width: 100%">
              <el-option label="每日" value="daily" />
              <el-option label="每周" value="weekly" />
              <el-option label="每月" value="monthly" />
              <el-option label="每年" value="yearly" />
              <el-option label="自定义" value="custom" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.integral_stat_type === 'custom'">
          <el-form-item label="开始时间" prop="integral_start_time">
            <el-date-picker
              v-model="formData.integral_start_time"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.integral_stat_type === 'custom'">
          <el-form-item label="结束时间" prop="integral_end_time">
            <el-date-picker
              v-model="formData.integral_end_time"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 邀请排行榜 -->
      <el-divider content-position="left">邀请排行榜</el-divider>
      
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="统计方式" prop="invite_stat_type">
            <el-select v-model="formData.invite_stat_type" placeholder="请选择统计方式" style="width: 100%">
              <el-option label="每日" value="daily" />
              <el-option label="每周" value="weekly" />
              <el-option label="每月" value="monthly" />
              <el-option label="每年" value="yearly" />
              <el-option label="自定义" value="custom" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.invite_stat_type === 'custom'">
          <el-form-item label="开始时间" prop="invite_start_time">
            <el-date-picker
              v-model="formData.invite_start_time"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.invite_stat_type === 'custom'">
          <el-form-item label="结束时间" prop="invite_end_time">
            <el-date-picker
              v-model="formData.invite_end_time"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 无限赏抽奖倍数 -->
      <el-divider content-position="left">无限赏抽奖倍数</el-divider>
      
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="抽奖倍数" prop="infinite_multiple">
            <el-select v-model="formData.infinite_multiple" placeholder="请选择抽奖倍数" style="width: 100%">
              <el-option label="1000倍" value="1000" />
              <el-option label="10000倍" value="10000" />
              <el-option label="100000倍" value="100000" />
            </el-select>
            <div class="form-tip">无限赏抽奖的倍数设置</div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Check } from '@element-plus/icons-vue'
import { 
  getRankSettingSetting, 
  updateRankSettingSetting, 
  getInfiniteMultipleSetting,
  updateInfiniteMultipleSetting,
  type RankSettingSetting,
  type InfiniteMultipleSetting
} from '@/api/business/config'

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

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

// 表单数据
interface FormDataType {
  dadajuan_stat_type: string
  dadajuan_start_time: string
  dadajuan_end_time: string
  diamond_stat_type: string
  diamond_start_time: string
  diamond_end_time: string
  integral_stat_type: string
  integral_start_time: string
  integral_end_time: string
  invite_stat_type: string
  invite_start_time: string
  invite_end_time: string
  infinite_multiple: string
}

const formData = reactive<FormDataType>({
  dadajuan_stat_type: 'daily',
  dadajuan_start_time: '',
  dadajuan_end_time: '',
  diamond_stat_type: 'daily',
  diamond_start_time: '',
  diamond_end_time: '',
  integral_stat_type: 'daily',
  integral_start_time: '',
  integral_end_time: '',
  invite_stat_type: 'daily',
  invite_start_time: '',
  invite_end_time: '',
  infinite_multiple: '1000'
})

// 自定义时间验证器
const customTimeValidator = (field: 'dadajuan' | 'diamond' | 'integral' | 'invite') => {
  return (_rule: any, _value: any, callback: any) => {
    const statType = formData[`${field}_stat_type` as keyof FormDataType]
    if (statType === 'custom') {
      const startTime = formData[`${field}_start_time` as keyof FormDataType]
      const endTime = formData[`${field}_end_time` as keyof FormDataType]
      if (!startTime || !endTime) {
        callback(new Error('自定义模式下必须设置开始和结束时间'))
      } else if (new Date(startTime) >= new Date(endTime)) {
        callback(new Error('结束时间必须大于开始时间'))
      } else {
        callback()
      }
    } else {
      callback()
    }
  }
}

// 表单验证规则
const formRules: FormRules = {
  dadajuan_stat_type: [
    { required: true, message: '请选择统计方式', trigger: 'change' }
  ],
  dadajuan_end_time: [
    { validator: customTimeValidator('dadajuan'), trigger: 'change' }
  ],
  diamond_stat_type: [
    { required: true, message: '请选择统计方式', trigger: 'change' }
  ],
  diamond_end_time: [
    { validator: customTimeValidator('diamond'), trigger: 'change' }
  ],
  integral_stat_type: [
    { required: true, message: '请选择统计方式', trigger: 'change' }
  ],
  integral_end_time: [
    { validator: customTimeValidator('integral'), trigger: 'change' }
  ],
  invite_stat_type: [
    { required: true, message: '请选择统计方式', trigger: 'change' }
  ],
  invite_end_time: [
    { validator: customTimeValidator('invite'), trigger: 'change' }
  ],
  infinite_multiple: [
    { required: true, message: '请选择抽奖倍数', trigger: 'change' }
  ]
}

// 加载配置数据
const loadData = async () => {
  loading.value = true
  try {
    // 并行加载排行榜设置和无限赏倍数设置
    const [rankRes, multipleRes] = await Promise.all([
      getRankSettingSetting(),
      getInfiniteMultipleSetting()
    ])

    if (rankRes.data?.value) {
      const data = rankRes.data.value
      Object.assign(formData, {
        dadajuan_stat_type: data.dadajuan_stat_type || 'daily',
        dadajuan_start_time: data.dadajuan_start_time || '',
        dadajuan_end_time: data.dadajuan_end_time || '',
        diamond_stat_type: data.diamond_stat_type || 'daily',
        diamond_start_time: data.diamond_start_time || '',
        diamond_end_time: data.diamond_end_time || '',
        integral_stat_type: data.integral_stat_type || 'daily',
        integral_start_time: data.integral_start_time || '',
        integral_end_time: data.integral_end_time || '',
        invite_stat_type: data.invite_stat_type || 'daily',
        invite_start_time: data.invite_start_time || '',
        invite_end_time: data.invite_end_time || ''
      })
    }

    if (multipleRes.data?.value) {
      formData.infinite_multiple = multipleRes.data.value.multiple || '1000'
    }
  } 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 rankData: RankSettingSetting = {
      dadajuan_stat_type: formData.dadajuan_stat_type,
      dadajuan_start_time: formData.dadajuan_stat_type === 'custom' ? formData.dadajuan_start_time : '',
      dadajuan_end_time: formData.dadajuan_stat_type === 'custom' ? formData.dadajuan_end_time : '',
      diamond_stat_type: formData.diamond_stat_type,
      diamond_start_time: formData.diamond_stat_type === 'custom' ? formData.diamond_start_time : '',
      diamond_end_time: formData.diamond_stat_type === 'custom' ? formData.diamond_end_time : '',
      integral_stat_type: formData.integral_stat_type,
      integral_start_time: formData.integral_stat_type === 'custom' ? formData.integral_start_time : '',
      integral_end_time: formData.integral_stat_type === 'custom' ? formData.integral_end_time : '',
      invite_stat_type: formData.invite_stat_type,
      invite_start_time: formData.invite_stat_type === 'custom' ? formData.invite_start_time : '',
      invite_end_time: formData.invite_stat_type === 'custom' ? formData.invite_end_time : ''
    }

    // 准备无限赏倍数数据
    const multipleData: InfiniteMultipleSetting = {
      multiple: formData.infinite_multiple
    }

    // 并行保存两个配置
    await Promise.all([
      updateRankSettingSetting(rankData),
      updateInfiniteMultipleSetting(multipleData)
    ])

    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
    console.error('保存排行榜设置失败:', error)
  } finally {
    saving.value = false
  }
}

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

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

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

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

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

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