<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-divider content-position="left">基本信息</el-divider>
      
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="项目名称" prop="app_name">
            <el-input v-model="formData.app_name" placeholder="请输入项目名称" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="小程序版本号" prop="version">
            <el-input v-model="formData.version" placeholder="请输入版本号，如 1.0.0" maxlength="20" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="购买弹窗设置" prop="purchase_popup">
            <el-radio-group v-model="formData.purchase_popup">
              <el-radio value="1">弹出一次</el-radio>
              <el-radio value="2">每天显示</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商城购买次数" prop="exchange_times">
            <el-input-number
              v-model.number="formData.exchange_times"
              :min="0"
              :max="999"
              placeholder="每日购买限制"
              style="width: 100%"
            />
            <div class="form-tip">每日商城购买次数限制，0表示不限制</div>
          </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="balance_name">
            <el-input v-model="formData.balance_name" placeholder="请输入余额名称" maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="余额图标" prop="balance_icon">
            <ImageUpload
              v-model="formData.balance_icon"
              placeholder="点击上传余额图标"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="货币1名称" prop="currency1_name">
            <el-input v-model="formData.currency1_name" placeholder="请输入货币1名称" maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="货币1图标" prop="currency1_icon">
            <ImageUpload
              v-model="formData.currency1_icon"
              placeholder="点击上传货币1图标"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="货币2名称" prop="currency2_name">
            <el-input v-model="formData.currency2_name" placeholder="请输入货币2名称" maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="货币2图标" prop="currency2_icon">
            <ImageUpload
              v-model="formData.currency2_icon"
              placeholder="点击上传货币2图标"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 音频配置 -->
      <el-divider content-position="left">音频配置</el-divider>
      
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="中奖音频" prop="win_audio">
            <el-input v-model="formData.win_audio" placeholder="请输入中奖音频URL" />
            <div class="form-tip">用户中奖时播放的音频文件URL</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 ImageUpload from '@/components/ImageUpload/index.vue'
import { getAppSetting, updateAppSetting, type AppSetting } from '@/api/business/config'

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

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

// 表单数据
interface FormDataType {
  app_name: string
  purchase_popup: string
  exchange_times: number
  balance_name: string
  balance_icon: string
  currency1_name: string
  currency1_icon: string
  currency2_name: string
  currency2_icon: string
  win_audio: string
  version: string
  sign_threshold: number
  exchange_show_threshold: number
  takeout_box_id: number
  daily_free_draw_id: number
  box_exchange_limit: number
  daily_coupon_limit: number
}

const formData = reactive<FormDataType>({
  app_name: '',
  purchase_popup: '1',
  exchange_times: 0,
  balance_name: '余额',
  balance_icon: '',
  currency1_name: '钻石',
  currency1_icon: '',
  currency2_name: 'HH币',
  currency2_icon: '',
  win_audio: '',
  version: '1.0.0',
  sign_threshold: 0,
  exchange_show_threshold: 0,
  takeout_box_id: 0,
  daily_free_draw_id: 0,
  box_exchange_limit: 0,
  daily_coupon_limit: 0
})

// 表单验证规则
const formRules: FormRules = {
  app_name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { max: 50, message: '项目名称不能超过50个字符', trigger: 'blur' }
  ],
  balance_name: [
    { required: true, message: '请输入余额名称', trigger: 'blur' }
  ],
  currency1_name: [
    { required: true, message: '请输入货币1名称', trigger: 'blur' }
  ],
  currency2_name: [
    { required: true, message: '请输入货币2名称', trigger: 'blur' }
  ]
}

// 加载配置数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await getAppSetting()
    if (res.data?.value) {
      const data = res.data.value
      Object.assign(formData, {
        app_name: data.app_name || '',
        purchase_popup: data.purchase_popup || '1',
        exchange_times: Number(data.exchange_times) || 0,
        balance_name: data.balance_name || '余额',
        balance_icon: data.balance_icon || '',
        currency1_name: data.currency1_name || '钻石',
        currency1_icon: data.currency1_icon || '',
        currency2_name: data.currency2_name || 'HH币',
        currency2_icon: data.currency2_icon || '',
        win_audio: data.win_audio || '',
        version: data.version || '1.0.0',
        sign_threshold: Number(data.sign_threshold) || 0,
        exchange_show_threshold: Number(data.exchange_show_threshold) || 0,
        takeout_box_id: Number(data.takeout_box_id) || 0,
        daily_free_draw_id: Number(data.daily_free_draw_id) || 0,
        box_exchange_limit: Number(data.box_exchange_limit) || 0,
        daily_coupon_limit: Number(data.daily_coupon_limit) || 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: AppSetting = {
      app_name: formData.app_name,
      purchase_popup: formData.purchase_popup,
      exchange_times: String(formData.exchange_times),
      balance_name: formData.balance_name,
      balance_icon: formData.balance_icon,
      currency1_name: formData.currency1_name,
      currency1_icon: formData.currency1_icon,
      currency2_name: formData.currency2_name,
      currency2_icon: formData.currency2_icon,
      win_audio: formData.win_audio,
      version: formData.version,
      sign_threshold: String(formData.sign_threshold),
      exchange_show_threshold: String(formData.exchange_show_threshold),
      takeout_box_id: String(formData.takeout_box_id),
      daily_free_draw_id: String(formData.daily_free_draw_id),
      box_exchange_limit: String(formData.box_exchange_limit),
      daily_coupon_limit: String(formData.daily_coupon_limit)
    }

    await updateAppSetting(submitData)
    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-divider__text) {
  font-weight: 600;
  color: #303133;
}
</style>
