<template>
  <div class="new-app-container layout-vertical" style="padding: 20px;">
    <el-form :inline="true" :model="queryParams" size="small" class="search-form">
      <el-form-item label="活动名称">
        <el-input v-model="queryParams.title" placeholder="请输入活动名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增活动</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="tableData" border style="width: 100%; margin-top: 15px;" height="100%">
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="title" label="活动名称" min-width="150" />
      <el-table-column prop="sub_title" label="副标题" min-width="150" />
      <el-table-column prop="start_time" label="开始时间" width="160" />
      <el-table-column prop="end_time" label="结束时间" width="160" />
      <el-table-column label="详情图片" width="100" align="center">
        <template slot-scope="scope">
          <el-image style="width: 50px; height: 50px" :src="scope.row.detail_image" :preview-src-list="[scope.row.detail_image]" />
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 0 ? '下架' : scope.row.status === 1 ? '上架' : '--' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.type ? typeText[scope.row.type] : '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="lang" label="语种" width="100" align="center" />
      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="small" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" icon="el-icon-delete" style="color: #f56c6c" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="queryParams.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="queryParams.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 15px; text-align: right;"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog :title="formTitle" :visible.sync="dialogVisible" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动名称" prop="title">
              <el-input v-model="formData.title" placeholder="请输入活动名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="副标题" prop="sub_title">
              <el-input v-model="formData.sub_title" placeholder="请输入副标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="start_time">
              <el-date-picker v-model="formData.start_time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="end_time">
              <el-date-picker v-model="formData.end_time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" style="width: 100%" :picker-options="pickerOptions" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="App详情图片" prop="detail_image">
              <upload-image v-model="formData.detail_image" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="PC详情图片" prop="pc_image">
              <upload-image v-model="formData.pc_image"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="AppBanner图片" prop="detail_image">
              <upload-image v-model="formData.detail_banner" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="PCBanner图片" prop="pc_image">
              <upload-image v-model="formData.pc_banner"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择" style="width: 100%">
                <el-option label="上架" :value="1" />
                <el-option label="下架" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="语种" prop="lang">
              <el-select v-model="formData.lang" placeholder="请选择" style="width: 100%">
                <el-option label="中文简体" value="zh" />
                <el-option label="Vietnamese" value="vi" />
                <el-option label="English" value="en" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择" style="width: 100%">
                <el-option label="足球首页" :value="2" />
                <el-option label="即充即送" :value="3" />
                <el-option label="老用户召集令" :value="4" />
                <el-option label="USDT使用教学" :value="5" />
                <el-option label="余额宝" :value="6" />
              </el-select>
            </el-form-item>
          </el-col>

          <template v-if="formData.type === 3">
            <el-col :span="12">
              <el-form-item label="单笔充值金额" prop="min_recharge_amount">
                <el-input v-model="formData.min_recharge_amount" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优惠比例" prop="reward_ratio">
                <el-input v-model="formData.reward_ratio" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单笔最高彩金" prop="max_reward_amount">
                <el-input v-model="formData.max_reward_amount" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="彩金流水倍数" prop="reward_turnover_ratio">
                <el-input v-model="formData.reward_turnover_ratio" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="彩金优惠笔数" prop="reward_limit_count">
                <el-input v-model="formData.reward_limit_count" />
              </el-form-item>
            </el-col>
          </template>

          <template  v-if="formData.type === 6">
            <el-col :span="12">
            <el-form-item label="日化率" prop="daily_interest_rate">
              <el-input v-model="formData.daily_interest_rate" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
             <el-form-item label="连续存款天数" prop="number_of_consecutive_days_of_deposit">
              <el-input v-model="formData.number_of_consecutive_days_of_deposit" />
            </el-form-item>
          </el-col>
          </template>



          <template v-if="formData.type === 4">
            <el-col :span="12">
              <el-form-item label="单笔充值金额" prop="min_recharge_amount">
                <el-input v-model="formData.min_recharge_amount" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="未登入天数" prop="no_login_days">
                <el-input v-model="formData.no_login_days" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="回归奖励配置">
                <div style="border: 1px solid #ebeef5; padding: 10px; border-radius: 4px;">
                  <el-table :data="formData.reward_rules || []" size="mini" border style="width: 100%">
                    <el-table-column label="等级范围" min-width="200">
                      <template slot-scope="scope">
                        <div style="display: flex; align-items: center;">
                          <el-select v-model="scope.row.start_level" placeholder="起" size="mini">
                            <el-option v-for="item in levelListData" :key="item.id" :label="item.level_name" :value="item.level" />
                          </el-select>
                          <span style="margin: 0 5px;">至</span>
                          <el-select v-model="scope.row.end_level" placeholder="止" size="mini">
                            <el-option v-for="item in levelListData" :key="item.id" :label="item.level_name" :value="item.level" />
                          </el-select>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column label="彩金" width="120">
                      <template slot-scope="scope">
                        <el-input-number v-model="scope.row.bonus" :controls="false" size="mini" style="width: 100%" placeholder="金额" />
                      </template>
                    </el-table-column>
                    <el-table-column label="流水倍率" width="120">
                      <template slot-scope="scope">
                        <el-input-number v-model="scope.row.turnover_rate" :controls="false" size="mini" style="width: 100%" placeholder="倍数" />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="60" align="center">
                      <template slot-scope="scope">
                        <el-button type="text" style="color: #f56c6c" @click="removeRewardRule(scope.$index)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-button type="primary" size="mini" icon="el-icon-plus" style="margin-top: 10px" @click="addRewardRule">添加等级配置</el-button>
                </div>
              </el-form-item>
            </el-col>
          </template>

          <el-col :span="24">
            <el-form-item label="内容" prop="content">
              <quill-editor v-model="formData.content" style="height: 300px; margin-bottom: 50px;" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { levelList } from '@/api/data'
import request from '@/utils/request'
// 新增引入：请根据你项目中实际保存的位置修改此处的路径
import UploadImage from '@/components/UploadOneImage/index.vue'

export default {
  components: {
    quillEditor,
    UploadImage // 新增注册组件
  },
  data() {
    return {
      typeText: ['', '', '足球首页', '即充即送', '老用户召集令', 'USDT使用教学', '余额宝'],
      loading: false,
      dialogVisible: false,
      formTitle: '',
      tableData: [],
      total: 0,
      levelListData: [],
      queryParams: {
        page: 1,
        limit: 20,
        title: ''
      },
      formData: {
        id: null,
        title: '',
        sub_title: '',
        start_time: '',
        end_time: '',
        detail_image: '',
        pc_image: '',
        status: 1,
        lang: 'zh',
        type: 2,
        content: '',
        reward_rules: [],
        // 动态字段占位
        min_recharge_amount: '',
        reward_ratio: '',
        max_reward_amount: '',
        reward_turnover_ratio: '',
        reward_limit_count: '',
        daily_interest_rate: '',
        no_login_days: '',
        number_of_consecutive_days_of_deposit: '',
      },
      rules: {
        title: [{ required: true, message: '活动名称不能为空', trigger: 'blur' }],
        sub_title: [{ required: true, message: '副标题不能为空', trigger: 'blur' }],
        start_time: [{ required: true, message: '开始时间不能为空', trigger: 'change' }],
        end_time: [{ required: true, message: '结束时间不能为空', trigger: 'change' }],
        detail_image: [{ required: true, message: 'App详情图片不能为空', trigger: 'change' }],
        pc_image: [{ required: true, message: 'PC详情图片不能为空', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        lang: [{ required: true, message: '请选择语种', trigger: 'change' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }]
      },
      pickerOptions: {
        disabledDate: (time) => {
          if (this.formData.start_time) {
            return time.getTime() < new Date(this.formData.start_time).getTime()
          }
          return false
        }
      }
    }
  },
  created() {
    this.getLevelList()
    this.handleQuery()
  },
  methods: {
    // 获取列表
    getList() {
      this.loading = true
      request({
        url: 'ActivityReward',
        method: 'get',
        params: this.queryParams
      }).then(res => {
        // 遵循原 apis.list.dataParam: 'data.data' 和 resultParam: 'data' 的逻辑
        this.tableData = res.data.data || []
        this.total = res.data.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 获取等级列表
    getLevelList() {
      const params = { page: 1, limit: 9999 }
      levelList(params).then(res => {
        this.levelListData = res.data.data || []
      })
    },
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.title = ''
      this.handleQuery()
    },
    handleSizeChange(val) {
      this.queryParams.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.queryParams.page = val
      this.getList()
    },
    // 新增
    handleAdd() {
      this.formTitle = '新增活动'
      this.formData = {
        id: null,
        title: '',
        sub_title: '',
        start_time: '',
        end_time: '',
        detail_image: '',
        pc_image: '',
        status: 1,
        lang: 'zh',
        type: 2,
        content: '',
        reward_rules: []
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    // 编辑
    handleEdit(row) {
      this.formTitle = '编辑活动'
      // 深度拷贝，并处理 params 展开（如果有）
      const data = JSON.parse(JSON.stringify(row))
      if (data.params) {
        Object.assign(data, data.params)
      }
      this.formData = data
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('是否确认删除该活动?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return request({
          url: 'ActivityReward/delete',
          method: 'post',
          data: { id: row.id }
        })
      }).then(() => {
        this.getList()
        this.$message.success('删除成功')
      })
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 格式化提交数据，遵循原 customHandle.submit 逻辑
          const postData = { ...this.formData }
          const businessParams = {}

          if (postData.type === 3) {
            const keys = ['min_recharge_amount', 'reward_ratio', 'max_reward_amount', 'reward_turnover_ratio', 'reward_limit_count']
            keys.forEach(key => {
              businessParams[key] = postData[key]
              delete postData[key]
            })
          } else if (postData.type === 4) {
            businessParams.no_login_days = postData.no_login_days
            businessParams.min_recharge_amount = postData.min_recharge_amount
            businessParams.reward_rules = postData.reward_rules
            delete postData.no_login_days
            delete postData.min_recharge_amount
            delete postData.reward_rules
          }

          else if (postData.type === 6) {
            businessParams.daily_interest_rate = postData.daily_interest_rate
            businessParams.number_of_consecutive_days_of_deposit = postData.number_of_consecutive_days_of_deposit
            delete postData.daily_interest_rate
            delete postData.number_of_consecutive_days_of_deposit
          }

          postData.params = businessParams

          request({
            url: 'ActivityReward/submit',
            method: 'post',
            data: postData
          }).then(() => {
            this.$message.success('保存成功')
            this.dialogVisible = false
            this.getList()
          })
        }
      })
    },
    // 等级规则操作
    addRewardRule() {
      if (!this.formData.reward_rules) {
        this.$set(this.formData, 'reward_rules', [])
      }
      this.formData.reward_rules.push({
        start_level: null,
        end_level: null,
        bonus: 0,
        turnover_rate: 0
      })
    },
    removeRewardRule(index) {
      this.formData.reward_rules.splice(index, 1)
    }
  }
}
</script>

<style scoped>
.search-form {
  background: #fdfdfd;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}
.layout-vertical {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 50px);
}
</style>
