<template>
  <div class="new-app-container layout-vertical">
    <el-form :inline="true" :model="queryParams" class="search-form" size="small">
      <el-form-item label="订单号">
        <el-input v-model="queryParams.ordernum" placeholder="请输入订单号" clearable />
      </el-form-item>
      <el-form-item label="会员ID">
        <el-input v-model="queryParams.member_id" placeholder="请输入会员ID" clearable />
      </el-form-item>
      <el-form-item label="会员账号">
        <el-input v-model="queryParams.first_name" placeholder="请输入会员账号" clearable />
      </el-form-item>
      <el-form-item label="游戏名称">
        <el-input v-model="queryParams.game_name" placeholder="请输入父级名称" clearable />
      </el-form-item>
      <el-form-item label="下注项">
        <el-input v-model="queryParams.gameplay_name" placeholder="请输入下注项名称" clearable />
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px;">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          @change="handleDateChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="action-bar">
      <el-button
        type="danger"
        size="small"
        icon="el-icon-money"
        :disabled="batchRefundDisabled"
        @click="openRefundDialog()"
      >
        批量退款
      </el-button>
      <span v-if="batchRefundDisabled && selectionList.length > 0" class="tip-text">
        (仅“待开奖”状态的订单可退款)
      </span>
    </div>

    <div class="table-wrapper">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        height="100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="订单号" min-width="180" align="center">
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" @click="goToDetail(scope.row.id)">{{ scope.row.ordernum }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="member_id" label="会员ID" min-width="100" align="center" />
        <el-table-column prop="first_name" label="会员账号" min-width="120" align="center" />
        <el-table-column prop="game_name" label="游戏名称" min-width="180" align="center" show-overflow-tooltip />
        <el-table-column prop="gameplay_name" label="下注项" min-width="150" align="center" show-overflow-tooltip />
        <el-table-column prop="odds" label="赔率" width="80" align="center">
          <template slot-scope="scope">
            <span style="color: #F56C6C; font-weight: bold;">{{ scope.row.odds }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="下注金额" min-width="100" align="center" />
        <el-table-column prop="win_amount" label="中奖金额" min-width="100" align="center">
          <template slot-scope="scope">{{ scope.row.win_amount || '--' }}</template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status === 0"
              type="danger"
              size="small"
              @click="openRefundDialog(scope.row)"
            >
              退款
            </el-button>
            <el-button
              size="small"
              @click="goToDetail(scope.row.id)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="queryParams.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.size"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog title="订单退款" :visible.sync="refundDialogVisible" width="400px" append-to-body>
      <el-form label-width="80px">
        <el-form-item label="退款原因" required>
          <el-input
            v-model="refundRemark"
            type="textarea"
            rows="3"
            placeholder="请输入退款备注/原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="refundDialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" :loading="submitLoading" @click="confirmRefund">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getSportGameOrderList, refundSportGameOrder } from '@/api/data'

export default {
  name: 'SportGameOrderList',
  data() {
    return {
      loading: false,
      submitLoading: false,
      tableData: [],
      total: 0,
      dateRange: [],
      queryParams: {
        page: 1,
        size: 20,
        ordernum: '',
        member_id: '',
        first_name: '',
        game_name: '',
        gameplay_name: '',
        status: '',
        start_time: '',
        end_time: ''
      },
      statusOptions: [
        { value: 0, label: '待开奖' },
        { value: 1, label: '未中奖' },
        { value: 2, label: '已中奖' },
        { value: 3, label: '已退款' }
      ],
      selectionList: [], // 多选选中的数据

      // 退款相关
      refundDialogVisible: false,
      refundIds: [],
      refundRemark: ''
    }
  },
  computed: {
    // 批量退款按钮是否禁用：未选择数据，或选中的数据中包含非"待开奖(0)"状态的订单
    batchRefundDisabled() {
      if (this.selectionList.length === 0) return true
      return this.selectionList.some(item => item.status !== 0)
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const res = await getSportGameOrderList(this.queryParams)
        if (res && res.data) {
          // 根据提供的返回结构解析数据
          this.tableData = res.data.data || []
          this.total = res.data.total || 0
        }
      } catch (error) {
        console.error('获取订单列表失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 跳转详情页
    goToDetail(id) {
      this.$router.push({ name: 'TotalSoccerAdvanceOrderDetail', query: { id: id } })
    },

    // 搜索
    handleSearch() {
      this.queryParams.page = 1
      this.getList()
    },

    // 重置
    resetQuery() {
      this.dateRange = []
      this.queryParams = {
        page: 1,
        size: this.queryParams.size,
        ordernum: '',
        member_id: '',
        first_name: '',
        game_name: '',
        gameplay_name: '',
        status: '',
        start_time: '',
        end_time: ''
      }
      this.getList()
    },

    // 时间选择器改变
    handleDateChange(val) {
      if (val && val.length === 2) {
        this.queryParams.start_time = val[0]
        this.queryParams.end_time = val[1]
      } else {
        this.queryParams.start_time = ''
        this.queryParams.end_time = ''
      }
    },

    // 列表多选变化
    handleSelectionChange(val) {
      this.selectionList = val
    },

    // 分页：条数改变
    handleSizeChange(val) {
      this.queryParams.size = val
      this.getList()
    },

    // 分页：页码改变
    handleCurrentChange(val) {
      this.queryParams.page = val
      this.getList()
    },

    // 打开退款弹窗 (兼容单个和批量)
    openRefundDialog(row) {
      this.refundRemark = ''
      if (row) {
        // 单个退款
        this.refundIds = [row.id]
      } else {
        // 批量退款
        this.refundIds = this.selectionList.map(item => item.id)
      }
      this.refundDialogVisible = true
    },

    // 确认退款
    async confirmRefund() {
      if (!this.refundRemark.trim()) {
        return this.$message.warning('请输入退款原因')
      }

      this.submitLoading = true
      try {
        const params = {
          id: this.refundIds, // 数组格式
          remark: this.refundRemark
        }
        await refundSportGameOrder(params)
        this.$message.success('退款操作成功')
        this.refundDialogVisible = false
        this.getList() // 刷新列表
      } catch (error) {
        console.error('退款失败:', error)
      } finally {
        this.submitLoading = false
      }
    },

    // 状态文案格式化
    getStatusLabel(status) {
      const target = this.statusOptions.find(item => item.value === status)
      return target ? target.label : '未知'
    },

    // 状态标签颜色格式化
    getStatusTagType(status) {
      const typeMap = {
        0: 'warning', // 待开奖
        1: 'info',    // 未中奖
        2: 'success', // 已中奖
        3: ''         // 已退款
      }
      return typeMap[status] !== undefined ? typeMap[status] : 'info'
    }
  }
}
</script>

<style scoped>
.new-app-container {
  height: calc(100vh - 100px);
  background: #fff;
  padding: 20px;
  margin: 20px;
  box-sizing: border-box;
  width: calc(100% - 40px);
  border-radius: 6px;
  display: flex;
  flex-direction: column;
}
.search-form {
  margin-bottom: 10px;
}
.action-bar {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}
.tip-text {
  font-size: 12px;
  color: #E6A23C;
  margin-left: 10px;
}
.table-wrapper {
  flex: 1;
  overflow: hidden;
}
.pagination-wrapper {
  margin-top: 15px;
  text-align: right;
}
::v-deep .el-table th.el-table__cell {
  background-color: #f5f7fa;
}
</style>
