<template>
  <div style="background-color: #fff;margin: 20px;border-radius: 6px;box-shadow: 0 2px 12px rgba(0,0,0,0.1);padding: 20px;">
    <div class="lottery-container">
    <div class="header-section">
      <el-tabs v-model="activeType" @tab-click="handleTabClick">
        <el-tab-pane label="澳门六合彩" name="3"></el-tab-pane>
        <el-tab-pane label="极速六合彩" name="4"></el-tab-pane>
      </el-tabs>

      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="期号">
          <el-input v-model="queryForm.issue" placeholder="请输入期号" clearable />
        </el-form-item>
        <el-form-item label="开奖号码">
          <el-input v-model="queryForm.open_code" placeholder="如: 24,19" clearable />
        </el-form-item>
        <el-form-item label="开奖时间">
          <el-date-picker
            v-model="queryForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-section">
      <el-table v-loading="loading" :data="tableData" border height="100%" style="width: 100%">
        <el-table-column prop="issue" label="期号" min-width="100" />
        
        <el-table-column label="类型" min-width="110">
          <template slot-scope="scope">
            <span v-if="scope.row.type === 3">澳门六合彩</span>
            <span v-else-if="scope.row.type === 2">香港六合彩</span>
            <span v-else-if="scope.row.type === 4">极速六合彩</span>
            <span v-else>{{ scope.row.type }}</span>
          </template>
        </el-table-column>

        <el-table-column label="状态" min-width="90" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 0" type="info" size="small">待发布</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="primary" size="small">投注中</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="warning" size="small">封盘</el-tag>
            <el-tag v-else-if="scope.row.status === 3" type="success" size="small">开奖</el-tag>
            <span v-else>--</span>
          </template>
        </el-table-column>

        <el-table-column label="开奖号码" min-width="260">
          <template slot-scope="scope">
            <div v-if="scope.row.open_code" class="table-balls">
              <span 
                v-for="(num, idx) in scope.row.open_code.split(',')" 
                :key="idx"
                class="ball-mini"
                :class="getBallColorClass(num)"
              >{{ num }}</span>
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column>

        <el-table-column label="预开奖号码" min-width="260">
          <template slot-scope="scope">
            <div v-if="scope.row.advance_code" class="table-balls">
              <span 
                v-for="(num, idx) in scope.row.advance_code.split(',')" 
                :key="idx"
                class="ball-mini"
                :class="getBallColorClass(num)"
              >{{ num }}</span>
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="open_time" label="开奖时间" min-width="160" />

        <el-table-column label="结算" min-width="80" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.is_settlement === 1 ? 'success' : 'info'" size="small" effect="plain">
              {{ scope.row.is_settlement === 1 ? '已结算' : '未结算' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="next_issue" label="下期期号" min-width="100" />
        <el-table-column prop="next_open_time" label="下期开奖时间" min-width="160" />

        <el-table-column label="操作" width="100" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button 
              v-if="scope.row.status != 3 && (scope.row.type == 3 || scope.row.type == 4) && !scope.row.advance_code" 
              type="text" 
              size="small" 
              @click="handleOpen(scope.row)"
            >预开奖</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

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

    <el-dialog 
      top="5vh"
      title="设置本期开奖号码" 
      :visible.sync="dialogVisible" 
      width="580px" 
      @close="resetDialog"
      custom-class="lottery-dialog"
    >
      <div class="dialog-inner">
        <div class="slots-container">
          <div class="slots-label">
            <span>选号预览</span>
            <el-button type="text" size="mini" class="clear-btn" @click="selectedNumbers = []">清空重选</el-button>
          </div>
          <div class="slots-wrapper">
            <div class="normal-slots">
              <div 
                v-for="i in 6" :key="'normal-'+i" 
                class="slot-item"
                :class="{'is-filled': selectedNumbers[i-1]}"
              >
                <div v-if="selectedNumbers[i-1]" class="ball-display" :class="getBallColorClass(selectedNumbers[i-1])">
                  {{ selectedNumbers[i-1] }}
                </div>
                <div v-else class="ball-placeholder">正码</div>
              </div>
            </div>
            
            <div class="slot-divider"><i class="el-icon-plus"></i></div>
            
            <div class="special-slot">
              <div 
                class="slot-item is-special"
                :class="{'is-filled': selectedNumbers[6]}"
              >
                <div v-if="selectedNumbers[6]" class="ball-display" :class="getBallColorClass(selectedNumbers[6])">
                  {{ selectedNumbers[6] }}
                </div>
                <div v-else class="ball-placeholder special-text">特码</div>
              </div>
            </div>
          </div>
        </div>

        <div class="picker-container">
          <div class="picker-grid">
            <div 
              v-for="n in 49" :key="n" 
              class="picker-item" 
              :class="[
                { 'is-active': selectedNumbers.includes(padZero(n)) },
                getBallColorClass(padZero(n))
              ]"
              @click="toggleNum(padZero(n))"
            >
              <span class="num-text">{{ padZero(n) }}</span>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :disabled="selectedNumbers.length !== 7" @click="submitCode" style="width: 120px;">确认提交</el-button>
      </div>
    </el-dialog>
  </div>
  </div>
</template>

<script>
import { getLotteryList, setOpenCode } from '@/api/data';

export default {
  name: 'LotteryList',
  data() {
    return {
      activeType: '3', 
      loading: false,
      tableData: [],   
      queryForm: {
        issue: '',
        open_code: '',
        timeRange: []
      },
      // 分页参数
      page: 1,
      limit: 10,
      total: 0,
      
      dialogVisible: false,
      selectedNumbers: [],
      currentRow: null,

      // 六合彩波色常量配置
      redWaves: ['1', '2', '7', '8', '12', '13', '18', '19', '23', '24', '29', '30', '34', '35', '40', '45', '46'],
      blueWaves: ['3', '4', '9', '10', '14', '15', '20', '25', '26', '31', '36', '37', '41', '42', '47', '48'],
      greenWaves: ['5', '6', '11', '16', '17', '21', '22', '27', '28', '32', '33', '38', '39', '43', '44', '49']
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 补齐两位数前导零
    padZero(n) {
      return n < 10 ? '0' + n : n.toString();
    },

    // 动态获取波色 Class (已修复带前导零的数据匹配问题)
    getBallColorClass(numStr) {
      if (!numStr) return '';
      
      // 关键修复：用 parseInt 去掉前面的 '0'，比如把 "02" 转成 "2"
      const formatNum = parseInt(numStr, 10).toString();
      
      if (this.redWaves.includes(formatNum)) return 'wave-red';
      if (this.blueWaves.includes(formatNum)) return 'wave-blue';
      if (this.greenWaves.includes(formatNum)) return 'wave-green';
      return '';
    },

    // 点击查询按钮重置页码
    handleSearch() {
      this.page = 1;
      this.fetchData();
    },

    async fetchData() {
      this.loading = true;
      
      const params = {
        type: Number(this.activeType),
        issue: this.queryForm.issue || undefined,
        open_code: this.queryForm.open_code || undefined,
        page: this.page,
        limit: this.limit
      };

      if (this.queryForm.timeRange && this.queryForm.timeRange.length === 2) {
        params.start_time = Math.floor(this.queryForm.timeRange[0] / 1000);
        params.end_time = Math.floor(this.queryForm.timeRange[1] / 1000);
      }

      try {
        const res = await getLotteryList(params);
        
        let list = [];
        if (res.data && Array.isArray(res.data.data)) {
          list = res.data.data;
          this.total = res.data.total || 0; // 适配常规分页结构
        } else if (res.data && Array.isArray(res.data.list)) {
          list = res.data.list;
          this.total = res.data.total || 0;
        } else if (Array.isArray(res.data)) {
          list = res.data;
          this.total = res.total || list.length;
        } else if (Array.isArray(res)) {
          list = res;
          this.total = list.length;
        }
        
        this.tableData = list;
      } catch (e) {
        console.error('获取列表失败:', e);
        this.tableData = []; 
        this.total = 0;
      } finally {
        this.loading = false;
      }
    },
    
    // 分页：修改每页条数
    handleSizeChange(val) {
      this.limit = val;
      this.page = 1;
      this.fetchData();
    },
    
    // 分页：修改当前页码
    handleCurrentChange(val) {
      this.page = val;
      this.fetchData();
    },

    handleTabClick() {
      this.queryForm.issue = '';
      this.queryForm.open_code = '';
      this.queryForm.timeRange = [];
      this.page = 1;
      this.fetchData();
    },
    handleOpen(row) {
      this.currentRow = row;
      this.selectedNumbers = [];
      this.dialogVisible = true;
    },
    toggleNum(numStr) {
      const idx = this.selectedNumbers.indexOf(numStr);
      
      if (idx > -1) {
        this.selectedNumbers.splice(idx, 1);
      } else if (this.selectedNumbers.length < 7) {
        this.selectedNumbers.push(numStr);
      }
    },
    resetDialog() {
      this.selectedNumbers = [];
      this.currentRow = null;
    },
    async submitCode() {
      try {
        await setOpenCode({ 
          id: this.currentRow.id, 
          advance_code: this.selectedNumbers 
        });
        this.$message.success('设置成功');
        this.dialogVisible = false;
        this.fetchData();
      } catch (e) {
        console.error('设置失败:', e);
      }
    }
  }
};
</script>

<style scoped>
/* ========== 页面基础布局 ========== */
.lottery-container {
  height: calc(100vh - 120px); 
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}
.header-section { flex-shrink: 0; }
.table-section {
  flex: 1; 
  height: 0; 
}
.search-form { margin-bottom: 10px; }

/* ========== 分页样式 ========== */
.pagination-container {
  padding-top: 15px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

/* ========== 波色核心样式定义 ========== */
/* 1. 用于实体球：列表小球、弹窗顶部大球、以及底部网格选中时的背景 */
.wave-red.ball-mini, .wave-red.ball-display, .picker-item.is-active.wave-red {
  background: linear-gradient(135deg, #ff5e5e, #e53935);
  border-color: #e53935;
  color: #fff;
}
.wave-blue.ball-mini, .wave-blue.ball-display, .picker-item.is-active.wave-blue {
  background: linear-gradient(135deg, #42a5f5, #1e88e5);
  border-color: #1e88e5;
  color: #fff;
}
.wave-green.ball-mini, .wave-green.ball-display, .picker-item.is-active.wave-green {
  background: linear-gradient(135deg, #66bb6a, #43a047);
  border-color: #43a047;
  color: #fff;
}

/* 2. 用于网格未选中时：白底、波色边框、深色文字 (完美适配白色背景) */
.picker-item.wave-red { border-color: #ffb6b6; color: #303133; }
.picker-item.wave-blue { border-color: #a0cfff; color: #303133; }
.picker-item.wave-green { border-color: #a4da89; color: #303133; }

/* ========== 列表内号码球样式 ========== */
.table-balls {
  display: flex;
  align-items: center;
  gap: 6px;
}
.ball-mini {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 26px;
  height: 26px;
  border-radius: 50%;
  font-weight: 600;
  font-size: 13px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* ========== 弹窗内部样式 ========== */
::v-deep .lottery-dialog .el-dialog__body {
  padding: 20px 30px 30px;
}
.dialog-inner {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

/* 1. 顶部预览槽位 */
.slots-container {
  background: #f8f9fb;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px 20px;
}
.slots-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: bold;
  color: #303133;
}
.clear-btn { padding: 0; color: #909399; }
.clear-btn:hover { color: #f56c6c; }

.slots-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}
.normal-slots {
  display: flex;
  gap: 8px;
}
.slot-divider {
  color: #c0c4cc;
  font-size: 18px;
  font-weight: bold;
  margin: 0 4px;
}

/* 槽位基础样式 */
.slot-item {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  border: 2px dashed #dcdfe6;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}
.slot-item.is-special {
  border-color: #fab6b6;
  background: #fef0f0;
}
.slot-item.is-filled {
  border: none;
  background: transparent;
}
.ball-placeholder {
  font-size: 12px;
  color: #c0c4cc;
}
.ball-placeholder.special-text { color: #f56c6c; }

/* 选中后的球体样式 (3D质感) */
.ball-display {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
  box-shadow: 0 4px 8px rgba(0,0,0,0.15), inset 0 -3px 4px rgba(0,0,0,0.1);
  text-shadow: 0 1px 2px rgba(0,0,0,0.2);
  animation: popIn 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

/* 2. 底部 49宫格选择器 */
.picker-container {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}
.picker-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10px;
}

/* 网格默认未选中基础结构 */
.picker-item {
  aspect-ratio: 1; 
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border: 1px solid; /* 颜色由上方 wave-xx 控制 */
  border-radius: 50%; /* 改为圆形 */
  cursor: pointer;
  transition: all 0.2s;
  font-size: 16px;
  font-weight: 500;
  position: relative;
  overflow: hidden;
}

.picker-item:hover {
  background: #f4f4f5;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
}

/* 激活状态额外增强 */
.picker-item.is-active {
  font-weight: bold;
  box-shadow: 0 4px 10px rgba(0,0,0,0.2);
  transform: scale(1.05);
  z-index: 2;
}

/* 激活状态加点内发光，增强立体感 */
.picker-item.is-active::after {
  content: '';
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  border-radius: 50%; /* 改为圆形 */
  border: 2px solid rgba(255,255,255,0.4); 
}

/* 动画效果 */
@keyframes popIn {
  0% { transform: scale(0.5); opacity: 0; }
  100% { transform: scale(1); opacity: 1; }
}
</style>