<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">基本信息</el-divider>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="网站名称" prop="title">
              <el-input v-model="formData.title" placeholder="请输入网站名称" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物流Code" prop="logistics_code">
              <el-input v-model="formData.logistics_code" placeholder="请输入物流API密钥" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="分销奖励比例(%)" prop="fx_bili">
              <el-input-number
                v-model.number="formData.fx_bili"
                :min="0"
                :max="100"
                :precision="2"
                placeholder="请输入分销奖励比例"
                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="free_post">
              <el-input-number
                v-model.number="formData.free_post"
                :min="0"
                :max="9999"
                placeholder="背包满多少件包邮"
                style="width: 100%"
              />
              <div class="form-tip">背包满多少件包邮，0表示不包邮</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="背包发货运费" prop="post_money">
              <el-input-number
                v-model.number="formData.post_money"
                :min="0"
                :max="999"
                :precision="2"
                placeholder="请输入运费金额"
                style="width: 100%"
              />
              <div class="form-tip">不满包邮门槛时的运费金额</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="three_time">
              <el-input-number
                v-model.number="formData.three_time"
                :min="0"
                :max="3600"
                placeholder="请输入三发锁箱时间"
                style="width: 100%"
              />
              <div class="form-tip">一番赏三发+锁箱时间（秒）</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="五发锁箱时间(秒)" prop="five_time">
              <el-input-number
                v-model.number="formData.five_time"
                :min="0"
                :max="3600"
                placeholder="请输入五发锁箱时间"
                style="width: 100%"
              />
              <div class="form-tip">一番赏五发+锁箱时间（秒）</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="erweima">
              <ImageUpload
                v-model="formData.erweima"
                placeholder="点击上传二维码"
                :show-url-input="true"
                tip="支持 jpg、png、gif、webp 格式，最大 10MB"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分享图片" prop="share_image">
              <ImageUpload
                v-model="formData.share_image"
                placeholder="点击上传分享图"
                :show-url-input="true"
                tip="支持 jpg、png、gif、webp 格式，最大 10MB"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="分享标题" prop="share_title">
              <el-input 
                v-model="formData.share_title" 
                placeholder="请输入分享标题" 
                maxlength="100"
                show-word-limit
              />
            </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="poster_template">
              <ImageUpload
                v-model="formData.poster_template"
                placeholder="点击上传海报模板"
                :show-url-input="true"
                tip="推荐尺寸 750x1334，二维码将合成到模板上"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站点URL" prop="site_url">
              <el-input 
                v-model="formData.site_url" 
                placeholder="请输入站点URL，如 https://example.com" 
              />
              <div class="form-tip">
                <div>仅用于 H5/APP 端生成海报二维码的推广链接</div>
                <div style="color: #67c23a;">小程序端会自动调用微信API生成小程序码，无需配置此项</div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="二维码X坐标" prop="poster_qr_x">
              <el-input-number
                v-model.number="formData.poster_qr_x"
                :min="0"
                placeholder="二维码左上角X坐标"
                style="width: 100%"
              />
              <div class="form-tip">二维码在海报上的X坐标（像素）</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二维码Y坐标" prop="poster_qr_y">
              <el-input-number
                v-model.number="formData.poster_qr_y"
                :min="0"
                placeholder="二维码左上角Y坐标"
                style="width: 100%"
              />
              <div class="form-tip">二维码在海报上的Y坐标（像素）</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二维码大小" prop="poster_qr_size">
              <el-input-number
                v-model.number="formData.poster_qr_size"
                :min="50"
                placeholder="二维码大小"
                style="width: 100%"
              />
              <div class="form-tip">二维码宽高（像素）</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="清除海报缓存">
              <el-button type="danger" :loading="clearingCache" @click="handleClearPosterCache">
                <el-icon><Delete /></el-icon>清除所有缓存
              </el-button>
              <div class="form-tip">修改海报配置后需清除缓存才能生效</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="is_shou_tan">
              <el-switch
                v-model="formData.is_shou_tan"
                :active-value="1"
                :inactive-value="0"
                active-text="开启"
                inactive-text="关闭"
              />
              <div class="form-tip">是否在首页显示弹窗</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="兑换开关" prop="is_exchange">
              <el-switch
                v-model="formData.is_exchange"
                :active-value="1"
                :inactive-value="0"
                active-text="开启"
                inactive-text="关闭"
              />
              <div class="form-tip">是否开启兑换功能</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Check, Delete } from '@element-plus/icons-vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
import { getBaseSetting, updateBaseSetting, clearPosterCache, type BaseSetting } from '@/api/business/config'

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

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

// 表单数据
interface FormDataType {
  title: string
  logistics_code: string
  lianji_max_num: number
  fx_bili: number
  coupon_ling_max_ci: number
  coupon_a_xz_max: number
  coupon_b_xz_max: number
  coupon_c_xz_max: number
  coupon_d_xz_max: number
  free_post: number
  post_money: number
  three_time: number
  five_time: number
  erweima: string
  share_title: string
  share_image: string
  poster_template: string
  poster_qr_x: number
  poster_qr_y: number
  poster_qr_size: number
  site_url: string
  draw_people_num: number
  is_shou_tan: number
  is_exchange: number
}

const formData = reactive<FormDataType>({
  title: '',
  logistics_code: '',
  lianji_max_num: 10,
  fx_bili: 0,
  coupon_ling_max_ci: 3,
  coupon_a_xz_max: 100,
  coupon_b_xz_max: 100,
  coupon_c_xz_max: 100,
  coupon_d_xz_max: 100,
  free_post: 0,
  post_money: 0,
  three_time: 60,
  five_time: 120,
  erweima: '',
  share_title: '',
  share_image: '',
  poster_template: '',
  poster_qr_x: 104,
  poster_qr_y: 1180,
  poster_qr_size: 200,
  site_url: '',
  draw_people_num: 10,
  is_shou_tan: 0,
  is_exchange: 1
})

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: '请输入网站名称', trigger: 'blur' },
    { max: 50, message: '网站名称不能超过50个字符', trigger: 'blur' }
  ],
  fx_bili: [
    { type: 'number', min: 0, max: 100, message: '分销比例必须在0-100之间', trigger: 'blur' }
  ],
  free_post: [
    { type: 'number', min: 0, message: '包邮门槛不能为负数', trigger: 'blur' }
  ],
  post_money: [
    { type: 'number', min: 0, message: '运费不能为负数', trigger: 'blur' }
  ]
}

// 加载配置数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await getBaseSetting()
    if (res.data?.value) {
      const data = res.data.value
      // 将字符串类型转换为数字类型
      Object.assign(formData, {
        title: data.title || '',
        logistics_code: data.logistics_code || '',
        lianji_max_num: Number(data.lianji_max_num) || 10,
        fx_bili: Number(data.fx_bili) || 0,
        coupon_ling_max_ci: Number(data.coupon_ling_max_ci) || 3,
        coupon_a_xz_max: Number(data.coupon_a_xz_max) || 100,
        coupon_b_xz_max: Number(data.coupon_b_xz_max) || 100,
        coupon_c_xz_max: Number(data.coupon_c_xz_max) || 100,
        coupon_d_xz_max: Number(data.coupon_d_xz_max) || 100,
        free_post: Number(data.free_post) || 0,
        post_money: Number(data.post_money) || 0,
        three_time: Number(data.three_time) || 60,
        five_time: Number(data.five_time) || 120,
        erweima: data.erweima || '',
        share_title: data.share_title || '',
        share_image: data.share_image || '',
        poster_template: data.poster_template || '',
        poster_qr_x: Number(data.poster_qr_x) || 104,
        poster_qr_y: Number(data.poster_qr_y) || 1180,
        poster_qr_size: Number(data.poster_qr_size) || 200,
        site_url: data.site_url || '',
        draw_people_num: Number(data.draw_people_num) || 10,
        is_shou_tan: Number(data.is_shou_tan) || 0,
        is_exchange: Number(data.is_exchange) || 1
      })
    }
  } 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: BaseSetting = {
      title: formData.title,
      logistics_code: formData.logistics_code,
      lianji_max_num: String(formData.lianji_max_num),
      fx_bili: String(formData.fx_bili),
      coupon_ling_max_ci: String(formData.coupon_ling_max_ci),
      coupon_a_xz_max: String(formData.coupon_a_xz_max),
      coupon_b_xz_max: String(formData.coupon_b_xz_max),
      coupon_c_xz_max: String(formData.coupon_c_xz_max),
      coupon_d_xz_max: String(formData.coupon_d_xz_max),
      free_post: String(formData.free_post),
      post_money: String(formData.post_money),
      three_time: String(formData.three_time),
      five_time: String(formData.five_time),
      erweima: formData.erweima,
      share_title: formData.share_title,
      share_image: formData.share_image,
      poster_template: formData.poster_template,
      poster_qr_x: String(formData.poster_qr_x),
      poster_qr_y: String(formData.poster_qr_y),
      poster_qr_size: String(formData.poster_qr_size),
      site_url: formData.site_url,
      draw_people_num: String(formData.draw_people_num),
      is_shou_tan: String(formData.is_shou_tan),
      is_exchange: String(formData.is_exchange)
    }

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

onMounted(() => {
  loadData()
})

// 清除海报缓存
const handleClearPosterCache = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清除所有用户的海报缓存吗？清除后用户下次访问推广页面时会重新生成海报。',
      '确认清除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    return
  }

  clearingCache.value = true
  try {
    const res = await clearPosterCache()
    ElMessage.success(res.data?.message || '清除成功')
  } catch (error) {
    ElMessage.error('清除失败')
    console.error('清除海报缓存失败:', error)
  } finally {
    clearingCache.value = false
  }
}
</script>

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

.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>
