<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">
      <!-- 统一的头部 Tab 切换栏 -->
      <div class="header-section">
        <el-tabs v-model="activeType" @tab-click="handleTabClick">
          <el-tab-pane label="极速赛车" name="1"></el-tab-pane>
          <el-tab-pane label="极速时时彩" name="2"></el-tab-pane>
          <el-tab-pane label="极速飞艇" name="3"></el-tab-pane>
          <el-tab-pane label="SG时时彩" name="4"></el-tab-pane>
          <el-tab-pane label="SG飞艇" name="5"></el-tab-pane>
          <el-tab-pane label="极速快3" name="6"></el-tab-pane>
          <el-tab-pane label="SG快3" name="7"></el-tab-pane>
          <el-tab-pane label="澳门六合彩" name="8"></el-tab-pane>
          <el-tab-pane label="极速六合彩" name="9"></el-tab-pane>
          <el-tab-pane label="加拿大28" name="10"></el-tab-pane>
          <el-tab-pane label="极速28" name="11"></el-tab-pane>
        </el-tabs>
      </div>

      <!-- ==================== 区域一：极速系列与SG系列 (Tab 1-7) ==================== -->
      <div v-if="['1','2','3','4','5','6','7'].includes(activeType)" class="layout-vertical" style="height: 100%; display: flex; flex-direction: column;">
        <div class="header-section">
          <el-form :inline="true" :model="queryForm" class="search-form">
            <el-form-item label="期号">
              <el-input v-model="queryForm.issue" clearable placeholder="请输入期号"/>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="queryForm.status" clearable placeholder="请选择状态">
                <el-option :value="0" label="待发布"></el-option>
                <el-option :value="1" label="投注中"></el-option>
                <el-option :value="2" label="封盘"></el-option>
                <el-option :value="3" label="开奖"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="结算状态">
              <el-select v-model="queryForm.is_settlement" clearable placeholder="请选择结算状态">
                <el-option :value="0" label="未结算"></el-option>
                <el-option :value="1" label="已结算"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开奖时间">
              <el-date-picker
                v-model="queryForm.timeRange"
                clearable
                end-placeholder="结束日期"
                range-separator="至"
                start-placeholder="开始日期"
                type="daterange"
                value-format="yyyy-MM-dd"
              />
            </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 label="期号" min-width="120" prop="issue"/>
            <el-table-column label="类型" min-width="110">
              <template slot-scope="scope">
                <span v-if="scope.row.type === 1">极速赛车</span>
                <span v-else-if="scope.row.type === 2">极速时时彩</span>
                <span v-else-if="scope.row.type === 3">极速飞艇</span>
                <span v-else-if="scope.row.type === 4">SG时时彩</span>
                <span v-else-if="scope.row.type === 5">SG飞艇</span>
                <span v-else-if="scope.row.type === 6">极速快3</span>
                <span v-else-if="scope.row.type === 7">SG快3</span>
                <span v-else>{{ scope.row.type }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="状态" min-width="90">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 0" size="small" type="info">待发布</el-tag>
                <el-tag v-else-if="scope.row.status === 1" size="small" type="primary">投注中</el-tag>
                <el-tag v-else-if="scope.row.status === 2" size="small" type="warning">封盘</el-tag>
                <el-tag v-else-if="scope.row.status === 3" size="small" type="success">开奖</el-tag>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column label="开奖号码" min-width="400">
              <template slot-scope="scope">
                <div v-if="scope.row.open_code" class="table-balls">
                  <template v-if="[6, 7].includes(scope.row.type)">
                    <span v-for="(num, idx) in scope.row.open_code.split(',')" :key="idx" :class="['dice-icon', 'dice-' + num]"></span>
                  </template>
                  <template v-else>
                    <span v-for="(num, idx) in scope.row.open_code.split(',')" :key="idx" :class="getJisuColorClass(num, scope.row.type)" class="ball-mini">{{ num }}</span>
                  </template>
                </div>
                <div v-if="scope.row.open_code_other" class="other-code-container">
                  <span v-for="(item, idx) in scope.row.open_code_other.split(',')" :key="'other-' + idx" class="other-tag">{{ item }}</span>
                </div>
                <span v-if="!scope.row.open_code && !scope.row.open_code_other">--</span>
              </template>
            </el-table-column>
            <el-table-column label="预开奖号码" min-width="360">
              <template slot-scope="scope">
                <div v-if="scope.row.advance_code" class="table-balls">
                  <template v-if="[6, 7].includes(scope.row.type)">
                    <span v-for="(num, idx) in scope.row.advance_code.split(',')" :key="idx" :class="['dice-icon', 'dice-' + num]"></span>
                  </template>
                  <template v-else>
                    <span v-for="(num, idx) in scope.row.advance_code.split(',')" :key="idx" :class="getJisuColorClass(num, scope.row.type)" class="ball-mini">{{ num }}</span>
                  </template>
                </div>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column label="开奖时间" min-width="160" prop="open_time"/>
            <el-table-column align="center" label="结算" min-width="80">
              <template slot-scope="scope">
                <el-tag :type="scope.row.is_settlement === 1 ? 'success' : 'info'" effect="plain" size="small">
                  {{ scope.row.is_settlement === 1 ? '已结算' : '未结算' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="下期期号" min-width="100" prop="next_issue"/>
            <el-table-column label="下期开奖时间" min-width="160" prop="next_open_time"/>
            <el-table-column align="center" fixed="right" label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.status != 3 && !scope.row.advance_code && ![4, 5, 7].includes(scope.row.type)"
                  size="small"
                  type="text"
                  @click="handleOpen(scope.row)"
                >预开奖
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

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

      <!-- ==================== 区域二：六合彩系列 (Tab 8-9 原澳门六合彩页面) ==================== -->
      <div v-if="['8','9'].includes(activeType)" class="layout-vertical" style="height: 100%; display: flex; flex-direction: column;">
        <div class="header-section">
          <el-form :inline="true" :model="queryFormMarkSix" class="search-form">
            <el-form-item label="期号">
              <el-input v-model="queryFormMarkSix.issue" placeholder="请输入期号" clearable />
            </el-form-item>
            <el-form-item label="开奖号码">
              <el-input v-model="queryFormMarkSix.open_code" placeholder="如: 24,19" clearable />
            </el-form-item>
            <el-form-item label="开奖时间">
              <el-date-picker
                v-model="queryFormMarkSix.timeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearchMarkSix">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="table-section">
          <el-table v-loading="loadingMarkSix" :data="tableDataMarkSix" 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="getMarkSixColorClass(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="getMarkSixColorClass(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="handleOpenMarkSix(scope.row)"
                >预开奖</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

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

      <!-- ==================== 区域三：加拿大28(10) ==================== -->
      <div v-if="activeType === '10'" key="tab10" class="new-app-container layout-vertical">
        <YMTableSearch :loading="loading" :search-form="searchForm28" @submit="onSubmit28" />
        <YMTable
          ref="table10"
          :table-key="10"
          :index="true"
          :selection="false"
          :table-options="tableOptions10"
          :edit-form="editForm10"
          :edit-config="editConfig28"
          :columns="columns10"
          :rows-actions="rowsActions10"
          :show-summary="false"
          :apis="apis10"
          :loading="loading"
          :custom-style="{ height: 'calc(100vh - 200px)' }"
        />
      </div>

      <!-- ==================== 区域四：极速28(11) ==================== -->
      <div v-if="activeType === '11'" key="tab11" class="new-app-container layout-vertical">
        <YMTableSearch :loading="loading" :search-form="searchFormPc" @submit="onSubmitPc" />
        <YMTable
          ref="table11"
          :table-key="11"
          :index="true"
          :selection="false"
          :table-options="tableOptions11"
          :edit-form="editForm11"
          :edit-config="editConfig28"
          :columns="columns11"
          :rows-actions="rowsActions11"
          :show-summary="false"
          :apis="apis11"
          :loading="loading"
          :custom-style="{ height: 'calc(100vh - 200px)' }"
        />
      </div>

      <!-- ==================== 弹窗区一：常规极速系列预开奖 ==================== -->
      <el-dialog
        :visible.sync="dialogVisible"
        custom-class="lottery-dialog"
        title="设置本期开奖号码"
        top="5vh"
        width="580px"
        @close="resetDialog"
      >
        <div class="dialog-inner">
          <div class="slots-container">
            <div class="slots-label">
              <span>选号预览</span>
              <el-button class="clear-btn" size="mini" type="text" @click="selectedNumbers = []">清空重选</el-button>
            </div>
            <div class="slots-wrapper">
              <div class="normal-slots">
                <template v-if="currentRow && [1, 3, 5].includes(currentRow.type)">
                  <div v-for="i in 10" :key="'normal-'+i" :class="{'is-filled': selectedNumbers[i-1]}" class="slot-item">
                    <div v-if="selectedNumbers[i-1]" :class="getJisuColorClass(selectedNumbers[i-1], currentRow.type)" class="ball-display">
                      {{ selectedNumbers[i - 1] }}
                    </div>
                    <div v-else class="ball-placeholder">号码</div>
                  </div>
                </template>
                <template v-else-if="currentRow && [2, 4].includes(currentRow.type)">
                  <div v-for="i in 5" :key="'normal-'+i" :class="{'is-filled': selectedNumbers[i-1]}" class="slot-item">
                    <div v-if="selectedNumbers[i-1]" :class="getJisuColorClass(selectedNumbers[i-1], currentRow.type)" class="ball-display">
                      {{ selectedNumbers[i - 1] }}
                    </div>
                    <div v-else class="ball-placeholder">号码</div>
                  </div>
                </template>
                <template v-else-if="currentRow && [6, 7].includes(currentRow.type)">
                  <div v-for="i in 3" :key="'normal-'+i" :class="{'is-filled': selectedNumbers[i-1]}" class="slot-item">
                    <div v-if="selectedNumbers[i-1]" :class="['dice-icon', 'dice-display', 'dice-' + selectedNumbers[i-1]]"></div>
                    <div v-else class="ball-placeholder">号码</div>
                  </div>
                </template>
              </div>
            </div>
          </div>

          <div class="picker-container">
            <div class="picker-grid" v-if="currentRow && [1, 3, 5].includes(currentRow.type)">
              <div v-for="n in 10" :key="n" :class="[{ 'is-active': selectedNumbers.includes(n.toString()) }, getJisuColorClass(n.toString(), currentRow.type)]" class="picker-item" @click="toggleNum(n.toString(), currentRow.type)">
                <span class="num-text">{{ n }}</span>
              </div>
            </div>
            <div class="picker-grid" v-else-if="currentRow && [2, 4].includes(currentRow.type)">
              <div v-for="n in 10" :key="n-1" :class="getJisuColorClass((n-1).toString(), currentRow.type)" class="picker-item" @click="toggleNum((n-1).toString(), currentRow.type)">
                <span class="num-text">{{ n - 1 }}</span>
              </div>
            </div>
            <div class="picker-grid" v-else-if="currentRow && [6, 7].includes(currentRow.type)" style="grid-template-columns: repeat(6, 1fr);">
              <div v-for="n in 6" :key="n" class="picker-item" @click="toggleNum(n.toString(), currentRow.type)">
                <span :class="['dice-icon', 'dice-' + n]" style="box-shadow: none;"></span>
              </div>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button :disabled="isSubmitDisabled" style="width: 120px;" type="primary" @click="submitCode">确认提交</el-button>
        </div>
      </el-dialog>

      <!-- ==================== 弹窗区二：六合彩原版预开奖 ==================== -->
      <el-dialog
        top="5vh"
        title="设置本期开奖号码"
        :visible.sync="dialogVisibleMarkSix"
        width="580px"
        @close="resetDialogMarkSix"
        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="selectedNumbersMarkSix = []">清空重选</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': selectedNumbersMarkSix[i-1]}"
                >
                  <div v-if="selectedNumbersMarkSix[i-1]" class="ball-display" :class="getMarkSixColorClass(selectedNumbersMarkSix[i-1])">
                    {{ selectedNumbersMarkSix[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': selectedNumbersMarkSix[6]}"
                >
                  <div v-if="selectedNumbersMarkSix[6]" class="ball-display" :class="getMarkSixColorClass(selectedNumbersMarkSix[6])">
                    {{ selectedNumbersMarkSix[6] }}
                  </div>
                  <div v-else class="ball-placeholder special-text">特码</div>
                </div>
              </div>
            </div>
          </div>

          <div class="picker-container">
            <div class="picker-grid" style="grid-template-columns: repeat(7, 1fr);">
              <div
                v-for="n in 49" :key="n"
                class="picker-item"
                :class="[
                  { 'is-active': selectedNumbersMarkSix.includes(padZero(n)) },
                  getMarkSixColorClass(padZero(n))
                ]"
                @click="toggleNumMarkSix(padZero(n))"
              >
                <span class="num-text">{{ padZero(n) }}</span>
              </div>
            </div>
          </div>
        </div>

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

      <!-- ==================== 弹窗区三：加拿大28 手动开奖 ==================== -->
      <Dialog ref="dialog10" :dialogActions="{width:'560px'}" @confirm="confirm10">
        <template slot="content">
          <el-form label-width="80px">
            <el-form-item label="号码" :rules="[{ required: true, message: '请输入号码' }]">
              <div class="compact-sum">
                <div class="input-group">
                  <el-input v-model.number="value1" type="number" placeholder="数值1" size="small" class="sum-input" />
                  <span class="plus">+</span>
                  <el-input v-model.number="value2" type="number" placeholder="数值2" size="small" class="sum-input" />
                  <span class="plus">+</span>
                  <el-input v-model.number="value3" type="number" placeholder="数值3" size="small" class="sum-input" />
                  <span class="plus">=</span>
                  <el-tag type="success" size="medium" class="sum-tag">{{ sum28 || 0 }}</el-tag>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </template>
      </Dialog>

      <!-- ==================== 弹窗区四：极速28 预开奖 ==================== -->
      <Dialog ref="dialog11" :dialogActions="{width:'480px'}" @confirm="confirm11">
        <template slot="content">
          <el-form label-width="80px">
            <el-form-item label="预开奖" :rules="[{ required: true, message: '请输入预开奖' }]">
              <el-input placeholder='开奖号码取值范围：0-27' v-model="formPc.he" autocomplete="off" style="width: 280px"></el-input>
            </el-form-item>
          </el-form>
        </template>
      </Dialog>
    </div>
  </div>
</template>

<script>
import Dialog from '@/components/Dialog/index.vue'
import {
  getJisuLotteryList,
  setJisuOpenCode,
  getLotteryList,
  setOpenCode,
  issuebetting,
  issueclose,
  issuelotteryDraw,
  pcIssuepreDraw
} from '@/api/data';

const options28 = [
  { value: 0, label: '草稿' },
  { value: 1, label: '投注中' },
  { value: 2, label: '封盘' },
  { value: 3, label: '开奖' },
  { value: '', label: '全部' }
];

const optionsPc = [
  { value: 0, label: '草稿' },
  { value: 1, label: '投注中' },
  { value: 2, label: '封盘' },
  { value: 3, label: '开奖' }
];

export default {
  name: 'MergedLotteryHistory',
  components: { Dialog },
  data() {
    return {
      activeType: '1',
      loading: false,

      // 区域一：极速系列数据
      tableData: [],
      queryForm: { issue: '', status: '', is_settlement: '', timeRange: [] },
      page: 1,
      limit: 10,
      total: 0,
      dialogVisible: false,
      selectedNumbers: [],
      currentRow: null,

      // 区域二：六合彩系列专属隔离数据
      loadingMarkSix: false,
      tableDataMarkSix: [],
      queryFormMarkSix: { issue: '', open_code: '', timeRange: [] },
      pageMarkSix: 1,
      limitMarkSix: 10,
      totalMarkSix: 0,
      dialogVisibleMarkSix: false,
      selectedNumbersMarkSix: [],
      currentRowMarkSix: 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'],

      // 区域三：加拿大28数据
      value1: null,
      value2: null,
      value3: null,
      queryData10: {},
      form10: {},
      searchForm28: [
        { label: '期号', type: 'input', prop: 'issue_no', clearable: false },
        { label: '状态', type: 'select', prop: 'status', clearable: false, options: options28 }
      ],
      columns10: [
        { label: '期号', link: true, prop: 'issue_no', click: (row) => { this.$router.push({ name: 'order', query: { issue_no: row.issue_no } }) } },
        { label: '状态', prop: 'status', method: (row) => options28.find(item => item.value === row.status)?.label },
        { label: '组合', prop: 'combo' },
        { label: '结果', method: (row) => { const arr = row?.winning_numbers?.split(',') ?? []; if (!arr.length) return '--'; const sum = arr.reduce((a, b) => Number(a) + Number(b), 0); return `${arr.join('+')}=${sum}`; } },
        { label: '开奖时间', prop: 'end_time' }
      ],
      rowsActions10: [
        { key: 'bet', label: '下注', vIF: (row) => row.status === 0, method: (row) => { this.loading = true; issuebetting({ id: row.id }).then(() => { this.loading = false; this.$message.success('下注成功'); this.onSubmit28(this.queryData10); }) } },
        { key: 'close', label: '封盘', vIF: (row) => row.status === 1, method: (row) => { this.loading = true; issueclose({ id: row.id }).then(() => { this.loading = false; this.$message.success('封盘成功'); this.onSubmit28(this.queryData10); }) } },
        { key: 'open', label: '手动开奖', vIF: (row) => row.status === 2, method: (row) => { this.form10 = { id: row.id, image: '', winning_numbers: '', combo: '' }; this.value1 = null; this.value2 = null; this.value3 = null; this.$refs.dialog10.open(); } },
        { key: 'autoOpen', label: '开奖', vIF: (row) => row.status === 2, method: (row) => { this.$confirm('此操作将立即开奖, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { issuelotteryDraw({ id: row.id }).then(() => { this.$message.success('开奖成功!'); this.onSubmit28(this.queryData10); }) }) } }
      ],
      apis10: { list: { url: 'issue', dataParam: 'data.data', resultParam: 'data', init: false }, add: { url: 'issue/submit' }, edit: { url: 'issue/submit' }, delete: { url: 'issue/delete', method: 'post' } },
      tableOptions10: { add: { show: true } },
      editForm10: [{ body: [{ label: '期号', type: 'input', prop: 'issue_no', clearable: false, rules: [{ required: true, message: '期号', trigger: 'change' }] }] }],

      // 区域四：极速28数据
      queryDataPc: {},
      formPc: {},
      searchFormPc: [ { label: '期号', type: 'input', prop: 'issue_no', clearable: false } ],
      columns11: [
        { label: '期号', prop: 'issue_no', link: true, click: (row) => { this.$router.push({ name: 'order', query: { issue_no: row.issue_no } }) } },
        { label: '状态', prop: 'status', method: (row) => optionsPc.find(item => item.value === row.status)?.label },
        { label: '组合', prop: 'combo' },
        { label: '结果', method: (row) => { const arr = row?.winning_numbers?.split(',') ?? []; if (!arr.length) return '--'; const sum = arr.reduce((a, b) => Number(a) + Number(b), 0); return `${arr.join('+')}=${sum}`; } },
        { label: '预开奖号码', prop: 'advance_code', method: (row) => row.advance_code === 0 ? '0' : row.advance_code || '--' },
        { label: '开奖时间', prop: 'end_time' }
      ],
      rowsActions11: [
        { key: 'open', label: '预开奖', vIF: (row) => row.status === 1, method: (row) => { this.formPc = { issue_no: row.issue_no, he: '' }; this.$refs.dialog11.open(); } }
      ],
      apis11: { list: { url: 'pcIssue', dataParam: 'data.data', resultParam: 'data', init: false } },
      tableOptions11: { add: { show: false } },
      editForm11: [{ body: [] }],
      editConfig28: { size: 'small' }
    };
  },
  computed: {
    sum28() { return (parseFloat(this.value1) || 0) + (parseFloat(this.value2) || 0) + (parseFloat(this.value3) || 0); },
    isSubmitDisabled() {
      if (!this.currentRow) return true;
      const type = this.currentRow.type;
      if ([1, 3, 5].includes(type)) return this.selectedNumbers.length !== 10;
      if ([2, 4].includes(type)) return this.selectedNumbers.length !== 5;
      if ([6, 7].includes(type)) return this.selectedNumbers.length !== 3;
      return true;
    }
  },
  mounted() {
    this.handleSearch();
  },
  methods: {
    padZero(n) { return n < 10 ? '0' + n : n.toString(); },

    // 极速系列样式取色
    getJisuColorClass(numStr, type) {
      if (!numStr) return '';
      if ([1, 3, 5].includes(type)) return `color-${numStr}`;
      if ([2, 4].includes(type)) return 'wave-blue';
      return '';
    },

    // 六合彩原版样式取色
    getMarkSixColorClass(numStr) {
      if (!numStr) return '';
      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 '';
    },

    // ==================== 全局 Tab 路由拦截 ====================
    handleTabClick() {
      if (['1', '2', '3', '4', '5', '6', '7'].includes(this.activeType)) {
        this.page = 1;
        this.queryForm = { issue: '', status: '', is_settlement: '', timeRange: [] };
        this.fetchData();
      } else if (['8', '9'].includes(this.activeType)) {
        this.pageMarkSix = 1;
        this.queryFormMarkSix = { issue: '', open_code: '', timeRange: [] };
        this.fetchDataMarkSix();
      } else if (this.activeType === '10') {
        this.$nextTick(() => { this.onSubmit28({}); });
      } else if (this.activeType === '11') {
        this.$nextTick(() => { this.onSubmitPc({}); });
      }
    },

    // ==================== 区域一：极速系列核心逻辑 ====================
    handleSearch() { this.page = 1; this.fetchData(); },
    async fetchData() {
      this.loading = true;
      const params = {
        type: Number(this.activeType),
        issue: this.queryForm.issue || undefined,
        status: this.queryForm.status !== '' ? this.queryForm.status : undefined,
        is_settlement: this.queryForm.is_settlement !== '' ? this.queryForm.is_settlement : undefined,
        page: this.page,
        limit: this.limit
      };
      if (this.queryForm.timeRange && this.queryForm.timeRange.length === 2) {
        params.start_time = this.queryForm.timeRange[0];
        params.end_time = this.queryForm.timeRange[1];
      }
      try {
        const res = await getJisuLotteryList(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) { 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(); },
    handleOpen(row) { this.currentRow = row; this.selectedNumbers = []; this.dialogVisible = true; },
    toggleNum(numStr, type) {
      if ([1, 3, 5].includes(type)) {
        const idx = this.selectedNumbers.indexOf(numStr);
        if (idx > -1) this.selectedNumbers.splice(idx, 1);
        else if (this.selectedNumbers.length < 10) this.selectedNumbers.push(numStr);
      } else if ([2, 4].includes(type)) {
        if (this.selectedNumbers.length < 5) this.selectedNumbers.push(numStr);
      } else if ([6, 7].includes(type)) {
        if (this.selectedNumbers.length < 3) { this.selectedNumbers.push(numStr); this.selectedNumbers.sort((a, b) => Number(a) - Number(b)); }
      }
    },
    resetDialog() { this.selectedNumbers = []; this.currentRow = null; },
    async submitCode() {
      try {
        await setJisuOpenCode({ id: this.currentRow.id, type: this.currentRow.type, advance_code: this.selectedNumbers });
        this.$message.success('设置成功');
        this.dialogVisible = false;
        this.fetchData();
      } catch (e) { console.error(e); }
    },

    // ==================== 区域二：六合彩原版核心逻辑 ====================
    handleSearchMarkSix() { this.pageMarkSix = 1; this.fetchDataMarkSix(); },
    async fetchDataMarkSix() {
      this.loadingMarkSix = true;
      const actualType = this.activeType === '8' ? 3 : 4;
      const params = {
        type: actualType,
        issue: this.queryFormMarkSix.issue || undefined,
        open_code: this.queryFormMarkSix.open_code || undefined,
        page: this.pageMarkSix,
        limit: this.limitMarkSix
      };
      if (this.queryFormMarkSix.timeRange && this.queryFormMarkSix.timeRange.length === 2) {
        params.start_time = Math.floor(this.queryFormMarkSix.timeRange[0] / 1000);
        params.end_time = Math.floor(this.queryFormMarkSix.timeRange[1] / 1000);
      }
      try {
        const res = await getLotteryList(params);
        let list = [];
        if (res.data && Array.isArray(res.data.data)) { list = res.data.data; this.totalMarkSix = res.data.total || 0; }
        else if (res.data && Array.isArray(res.data.list)) { list = res.data.list; this.totalMarkSix = res.data.total || 0; }
        else if (Array.isArray(res.data)) { list = res.data; this.totalMarkSix = res.total || list.length; }
        else if (Array.isArray(res)) { list = res; this.totalMarkSix = list.length; }
        this.tableDataMarkSix = list;
      } catch (e) { this.tableDataMarkSix = []; this.totalMarkSix = 0; } finally { this.loadingMarkSix = false; }
    },
    handleSizeChangeMarkSix(val) { this.limitMarkSix = val; this.pageMarkSix = 1; this.fetchDataMarkSix(); },
    handleCurrentChangeMarkSix(val) { this.pageMarkSix = val; this.fetchDataMarkSix(); },
    handleOpenMarkSix(row) { this.currentRowMarkSix = row; this.selectedNumbersMarkSix = []; this.dialogVisibleMarkSix = true; },
    toggleNumMarkSix(numStr) {
      const idx = this.selectedNumbersMarkSix.indexOf(numStr);
      if (idx > -1) { this.selectedNumbersMarkSix.splice(idx, 1); }
      else if (this.selectedNumbersMarkSix.length < 7) { this.selectedNumbersMarkSix.push(numStr); }
    },
    resetDialogMarkSix() { this.selectedNumbersMarkSix = []; this.currentRowMarkSix = null; },
    async submitCodeMarkSix() {
      try {
        await setOpenCode({ id: this.currentRowMarkSix.id, advance_code: this.selectedNumbersMarkSix });
        this.$message.success('设置成功');
        this.dialogVisibleMarkSix = false;
        this.fetchDataMarkSix();
      } catch (e) { console.error(e); }
    },

    // ==================== 区域三：加拿大28 逻辑 ====================
    onSubmit28(params) { this.queryData10 = params; this.$refs.table10.getList(params); },
    confirm10() {
      issuelotteryDraw({ id: this.form10.id, winning_numbers: `${this.value1},${this.value2},${this.value3}` })
        .then((res) => { if (res.code === 0) { this.$message.success('开奖成功'); this.onSubmit28(this.queryData10); this.$refs.dialog10.close(); } })
        .catch(() => { this.$message.error('开奖失败'); });
    },

    // ==================== 区域四：极速28 逻辑 ====================
    onSubmitPc(params) { this.queryDataPc = params; this.$refs.table11.getList(params); },
    confirm11() {
      pcIssuepreDraw(this.formPc)
        .then((res) => { if (res.code === 0) { this.$message.success('设置成功'); this.onSubmitPc(this.queryDataPc); this.$refs.dialog11.close(); } })
        .catch(() => { this.$message.error('设置失败'); });
    }
  }
};
</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; }

/* ========== 波色核心样式 ========== */
.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; }
.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; }

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

/* ========== 列表号码样式 ========== */
.table-balls { display: flex; align-items: center; flex-wrap: wrap; 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); }
.other-code-container { margin-top: 8px; display: flex; align-items: center; flex-wrap: wrap; gap: 6px; }
.other-tag { display: inline-block; padding: 2px 6px; background-color: #f4f4f5; border: 1px solid #e9e9eb; border-radius: 4px; font-size: 12px; color: #909399; }

/* ========== 弹窗内部样式 ========== */
::v-deep .lottery-dialog .el-dialog__body { padding: 20px 30px 30px; }
.dialog-inner { display: flex; flex-direction: column; gap: 25px; }
.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; flex-wrap: wrap; justify-content: center; }
.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; }
.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); }
.picker-container { border-top: 1px solid #ebeef5; padding-top: 20px; }
.picker-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 10px; }
.picker-item { aspect-ratio: 1; display: flex; align-items: center; justify-content: center; background: #fff; border: 1px solid; 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; } }

/* ========== 骰子、28专属样式 ========== */
.dice-icon { display: inline-block; width: 26px; height: 26px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); border-radius: 4px; }
.dice-display { width: 100%; height: 100%; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15); border-radius: 6px; animation: popIn 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
.dice-1 { background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="white" stroke="%23dcdfe6" stroke-width="1"/><circle cx="12" cy="12" r="4" fill="%23F56C6C"/></svg>') no-repeat center/contain; }
.dice-2 { background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="white" stroke="%23dcdfe6" stroke-width="1"/><circle cx="7" cy="7" r="2.5" fill="%23303133"/><circle cx="17" cy="17" r="2.5" fill="%23303133"/></svg>') no-repeat center/contain; }
.dice-3 { background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="white" stroke="%23dcdfe6" stroke-width="1"/><circle cx="6" cy="6" r="2.5" fill="%23303133"/><circle cx="12" cy="12" r="2.5" fill="%23303133"/><circle cx="18" cy="18" r="2.5" fill="%23303133"/></svg>') no-repeat center/contain; }
.dice-4 { background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="white" stroke="%23dcdfe6" stroke-width="1"/><circle cx="7" cy="7" r="2.5" fill="%23F56C6C"/><circle cx="17" cy="7" r="2.5" fill="%23F56C6C"/><circle cx="7" cy="17" r="2.5" fill="%23F56C6C"/><circle cx="17" cy="17" r="2.5" fill="%23F56C6C"/></svg>') no-repeat center/contain; }
.dice-5 { background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="white" stroke="%23dcdfe6" stroke-width="1"/><circle cx="6" cy="6" r="2.5" fill="%23303133"/><circle cx="18" cy="6" r="2.5" fill="%23303133"/><circle cx="12" cy="12" r="2.5" fill="%23303133"/><circle cx="6" cy="18" r="2.5" fill="%23303133"/><circle cx="18" cy="18" r="2.5" fill="%23303133"/></svg>') no-repeat center/contain; }
.dice-6 { background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="white" stroke="%23dcdfe6" stroke-width="1"/><circle cx="7" cy="5" r="2.5" fill="%23303133"/><circle cx="17" cy="5" r="2.5" fill="%23303133"/><circle cx="7" cy="12" r="2.5" fill="%23303133"/><circle cx="17" cy="12" r="2.5" fill="%23303133"/><circle cx="7" cy="19" r="2.5" fill="%23303133"/><circle cx="17" cy="19" r="2.5" fill="%23303133"/></svg>') no-repeat center/contain; }

.compact-sum { display: inline-flex; align-items: center; }
.input-group { display: flex; align-items: center; gap: 4px; background: #f8f9fa; padding: 8px 12px; border-radius: 6px; border: 1px solid #ebeef5; }
.sum-input { width: 60px; }
.plus { color: #909399; font-weight: 500; padding: 0 4px; }
.sum-tag { font-size: 14px; min-width: 80px; justify-content: center; }
</style>
