<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.gameplay" 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-select v-model="queryParams.type" placeholder="请选择类型" clearable style="width: 150px;">
          <el-option v-for="item in typeOptions" :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="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @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="type" label="游戏类型" min-width="120" align="center">
          <template slot-scope="scope">
            {{ getTypeLabel(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="gameplay" label="游戏名称" min-width="180" align="center" show-overflow-tooltip />
        <el-table-column prop="number" 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 label="开奖结果" min-width="220" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.open_code" class="table-balls">
              <template v-if="[6, 7].includes(scope.row.type) && getK3Dice(scope.row.open_code).length === 3">
                <div
                  v-for="(num, idx) in getK3Dice(scope.row.open_code)"
                  :key="idx"
                  :class="['dice-box', 'dice-' + num]"
                >
                  <span v-for="dot in Number(num)" :key="dot" :class="['dice-dot', 'dot-' + dot]"></span>
                </div>
              </template>
              <template v-else>
                <span
                  v-for="(num, idx) in scope.row.open_code.split(',')"
                  :key="idx"
                  :class="getBallColorClass(num, scope.row.type)"
                  class="ball-mini"
                >{{ num }}</span>
              </template>
            </div>
            <span v-else>--</span>
          </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 prop="created_at" label="投注时间" min-width="160" align="center" />
        <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.limit"
        :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 { getjisuGameOrderList, jisuGameOrderRefund } from '@/api/data.js'

export default {
  name: 'JisuGameOrderList',
  data() {
    return {
      loading: false,
      submitLoading: false,
      tableData: [],
      total: 0,
      dateRange: [],
      queryParams: {
        page: 1,
        limit: 20,
        ordernum: '',
        member_id: '',
        first_name: '',
        gameplay: '',
        gameplay_name: '',
        status: '',
        type: '',
        start_time: '',
        end_time: ''
      },
      statusOptions: [
        { value: 0, label: '待开奖' },
        { value: 1, label: '未中奖' },
        { value: 2, label: '已中奖' },
        { value: 3, label: '已退款' }
      ],
      typeOptions: [
        { value: 1, label: '极速赛车' },
        { value: 2, label: '极速时时彩' },
        { value: 3, label: '极速飞艇' },
        { value: 6, label: '极速快3' },
        { value: 4, label: 'SG时时彩' },
        { value: 5, label: 'SG飞艇' },
        { value: 7, label: 'SG快3' }
      ],
      selectionList: [],

      refundDialogVisible: false,
      refundIds: [],
      refundRemark: ''
    }
  },
  computed: {
    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 getjisuGameOrderList(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: 'jisuOrderDetail', query: { id: id } })
    },

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

    resetQuery() {
      this.dateRange = []
      this.queryParams = {
        page: 1,
        size: this.queryParams.limit,
        ordernum: '',
        member_id: '',
        first_name: '',
        gameplay: '',
        gameplay_name: '',
        status: '',
        type: '',
        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.limit = 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 jisuGameOrderRefund(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'
    },

    getTypeLabel(type) {
      const target = this.typeOptions.find(item => item.value === type)
      return target ? target.label : '--'
    },

    // 动态获取开奖号码球样式 Class
    getBallColorClass(numStr, type) {
      if (!numStr) return '';
      if ([1, 3, 5].includes(type)) {
        return `color-${numStr}`;
      } else if ([2, 4].includes(type)) {
        return 'wave-blue';
      }
      return '';
    },

    // 解析快3开奖号码
    getK3Dice(openCode) {
      if (!openCode) return [];
      const str = String(openCode).replace(/,/g, '');
      if (str.length === 3) {
        return str.split('');
      }
      return [];
    }
  }
}
</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;
}

/* ========== 开奖号码球样式 ========== */
.table-balls {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  gap: 6px;
}

.ball-mini {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  font-weight: 600;
  font-size: 13px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.wave-blue.ball-mini {
  background: linear-gradient(135deg, #42a5f5, #1e88e5);
  border-color: #1e88e5;
  color: #fff;
}

.color-1.ball-mini { background: #E6DE00; border-color: #E6DE00; color: #fff; text-shadow: 0 1px 1px rgba(0,0,0,0.3); }
.color-2.ball-mini { background: #0092FF; border-color: #0092FF; color: #fff; }
.color-3.ball-mini { background: #4D4D4D; border-color: #4D4D4D; color: #fff; }
.color-4.ball-mini { background: #FF7600; border-color: #FF7600; color: #fff; }
.color-5.ball-mini { background: #17E2E5; border-color: #17E2E5; color: #fff; }
.color-6.ball-mini { background: #5234FF; border-color: #5234FF; color: #fff; }
.color-7.ball-mini { background: #BFBFBF; border-color: #BFBFBF; color: #fff; }
.color-8.ball-mini { background: #FF2600; border-color: #FF2600; color: #fff; }
.color-9.ball-mini { background: #780B00; border-color: #780B00; color: #fff; }
.color-10.ball-mini { background: #07BF00; border-color: #07BF00; color: #fff; }

/* ========== 快3 骰子样式 ========== */
.dice-box {
  position: relative;
  width: 28px;
  height: 28px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: inset 0 0 2px rgba(0,0,0,0.1);
}
.dice-dot {
  position: absolute;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}
.dice-1 .dice-dot, .dice-4 .dice-dot {
  background-color: #F56C6C;
}
.dice-2 .dice-dot, .dice-3 .dice-dot, .dice-5 .dice-dot, .dice-6 .dice-dot {
  background-color: #303133;
}

.dice-1 .dot-1 { top: 50%; left: 50%; width: 10px; height: 10px; }
.dice-2 .dot-1 { top: 25%; left: 25%; width: 6px; height: 6px; }
.dice-2 .dot-2 { top: 75%; left: 75%; width: 6px; height: 6px; }
.dice-3 .dot-1 { top: 20%; left: 20%; width: 6px; height: 6px; }
.dice-3 .dot-2 { top: 50%; left: 50%; width: 6px; height: 6px; }
.dice-3 .dot-3 { top: 80%; left: 80%; width: 6px; height: 6px; }
.dice-4 .dot-1 { top: 25%; left: 25%; width: 6px; height: 6px; }
.dice-4 .dot-2 { top: 25%; left: 75%; width: 6px; height: 6px; }
.dice-4 .dot-3 { top: 75%; left: 25%; width: 6px; height: 6px; }
.dice-4 .dot-4 { top: 75%; left: 75%; width: 6px; height: 6px; }
.dice-5 .dot-1 { top: 20%; left: 20%; width: 6px; height: 6px; }
.dice-5 .dot-2 { top: 20%; left: 80%; width: 6px; height: 6px; }
.dice-5 .dot-3 { top: 50%; left: 50%; width: 6px; height: 6px; }
.dice-5 .dot-4 { top: 80%; left: 20%; width: 6px; height: 6px; }
.dice-5 .dot-5 { top: 80%; left: 80%; width: 6px; height: 6px; }
.dice-6 .dot-1 { top: 20%; left: 30%; width: 5px; height: 5px; }
.dice-6 .dot-2 { top: 50%; left: 30%; width: 5px; height: 5px; }
.dice-6 .dot-3 { top: 80%; left: 30%; width: 5px; height: 5px; }
.dice-6 .dot-4 { top: 20%; left: 70%; width: 5px; height: 5px; }
.dice-6 .dot-5 { top: 50%; left: 70%; width: 5px; height: 5px; }
.dice-6 .dot-6 { top: 80%; left: 70%; width: 5px; height: 5px; }
</style>
