<template>
  <div class="champion-order-component">

    <div class="filter-body">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item :label="t('注单状态')">
          <el-select v-model="queryParams.status" :placeholder="t('全部')" style="width: 140px;" clearable @change="handleQuery">
            <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="t('日期区间')">
          <el-date-picker
              v-model="dateRange"
              type="daterange"
              :start-placeholder="t('开始日期')"
              :end-placeholder="t('结束日期')"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon class="btn-icon"><Search /></el-icon>{{ t('立即查询') }}
          </el-button>
          <el-button @click="handleReset">
            <el-icon class="btn-icon"><RefreshRight /></el-icon>{{ t('重置') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
        :data="tableData"
        style="width: 100%;"
        height="100%"
        :empty-text="t('暂无投注记录')"
    >
      <el-table-column :label="t('注单号')" min-width="180">
        <template #default="scope">
          <div class="order-no-box">
            <span class="issue-no">{{ scope.row.ordernum }}</span>
            <el-icon class="copy-icon" @click="copyText(scope.row.ordernum)"><DocumentCopy /></el-icon>
          </div>
        </template>
      </el-table-column>

      <el-table-column :label="t('期号')" min-width="120" prop="issue">
      </el-table-column>

      <el-table-column :label="t('投注内容')" min-width="240">
        <template #default="scope">
          <el-tag type="warning" effect="light" class="game-tag" style="margin-right: 8px;" v-if="scope.row.type || scope.row.gameplay?.type">
            {{ getGameType(scope.row.type || scope.row.gameplay?.type) }}
          </el-tag>
          <el-tag type="primary" effect="light" class="game-tag" v-if="scope.row.gameplay?.game">
            {{ locale === 'zh' ? scope.row.gameplay?.game : (scope.row.gameplay?.game_en || scope.row.gameplay?.game) }}
          </el-tag>
          <span class="bet-keywords ml-2">
            {{ locale === 'zh' ? scope.row.gameplay?.gameplay : (scope.row.gameplay?.gameplay_en || scope.row.gameplay?.gameplay) }}
            {{ scope.row.gameplay?.number ? ' - ' + (locale === 'zh' ? scope.row.gameplay?.number : (scope.row.gameplay?.number_en || scope.row.gameplay?.number)) : '' }}
          </span>
        </template>
      </el-table-column>

      <el-table-column :label="t('开奖结果')" min-width="260">
        <template #default="scope">
          <div v-if="scope.row.open_code || scope.row.open_code_other" class="open-result-box">
            <div class="res-balls" v-if="scope.row.open_code">

              <template v-if="isKuai3Dice(scope.row)">
                <span
                    class="dice-item"
                    :class="['dice-' + num, (num == 1 || num == 4) ? 'dice-red' : '']"
                    v-for="(num, index) in scope.row.open_code.split(',')"
                    :key="'dice-'+index"
                >
                  <i class="dot" v-for="i in Number(num)" :key="i"></i>
                </span>
              </template>

              <template v-else>
                <span
                    class="ball-item"
                    :class="getBallColorClass(num, scope.row.type || scope.row.gameplay?.type)"
                    v-for="(num, index) in scope.row.open_code.split(',')"
                    :key="'code-'+index"
                >
                  {{ num }}
                </span>
              </template>

            </div>
            <div class="res-others" v-if="scope.row.open_code_other">
              <el-tag
                  v-for="(tag, idx) in scope.row.open_code_other.split(',')"
                  :key="'other-'+idx"
                  size="small"
                  type="info"
                  effect="plain"
                  class="other-tag"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
          <span v-else>--</span>
        </template>
      </el-table-column>

      <el-table-column :label="t('赔率')" min-width="90" align="center">
        <template #default="scope">
          <span class="odds-val">@{{ scope.row.odds }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="t('投注本金')" min-width="100" align="center">
        <template #default="scope">
          <span class="val-text">{{ parseFloat(scope.row.amount || 0).toFixed(2) }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="t('盈亏')" min-width="110" align="center">
        <template #default="scope">
          <span v-if="scope.row.status === 0" class="val-text">--</span>
          <span v-else class="profit-val" :class="getProfitClass(scope.row)">
            {{ getProfitText(scope.row) }}
          </span>
        </template>
      </el-table-column>

      <el-table-column :label="t('状态')" width="90" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTag(scope.row).type" effect="dark">
            {{ getStatusTag(scope.row).text }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="created_at" :label="t('投注时间')" min-width="170" align="center" />

      <el-table-column :label="t('操作')" width="80" align="center" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="handleGameDetail(scope.row)">{{ t('详情') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

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

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { Search, RefreshRight, DocumentCopy } from '@element-plus/icons-vue';

// 替换为极速游戏投注历史接口
import { getJisuGameOrderList } from '@/request/api';

const { t, locale } = useI18n();
const router = useRouter();

const tableData = ref([]);
const total = ref(0);
const dateRange = ref(null);

const queryParams = reactive({
  page: 1,
  limit: 20,
  status: '',
  start_time: '',
  end_time: ''
});

// 状态枚举：0 未开奖，1未中奖 2已中奖 3 已退款
const statusOptions = computed(() => [
  { label: t('全部'), value: '' },
  { label: t('未开奖'), value: 0 },
  { label: t('未中奖'), value: 1 },
  { label: t('已中奖'), value: 2 },
  { label: t('已退款'), value: 3 }
]);

onMounted(() => {
  fetchData();
});

const fetchData = async () => {
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.start_time = dateRange.value[0];
    queryParams.end_time = dateRange.value[1];
  } else {
    queryParams.start_time = '';
    queryParams.end_time = '';
  }

  try {
    const res = await getJisuGameOrderList(queryParams);
    if (res.code === 1 && res.data) {
      tableData.value = res.data.list || [];
      total.value = res.data.count || res.data.list.length || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (err) {
    tableData.value = [];
    total.value = 0;
  }
};

const handleQuery = () => {
  queryParams.page = 1;
  fetchData();
};

const handleReset = () => {
  queryParams.status = '';
  dateRange.value = null;
  queryParams.start_time = '';
  queryParams.end_time = '';
  handleQuery();
};

const handleSizeChange = (val) => {
  queryParams.limit = val;
  fetchData();
};

const handleCurrentChange = (val) => {
  queryParams.page = val;
  fetchData();
};

// 获取游戏类型
const getGameType = (typeCode) => {
  const tNum = Number(typeCode);
  if (tNum === 1) return t('极速赛车');
  if (tNum === 2) return t('极速时时彩');
  if (tNum === 3) return t('极速飞艇');
  if (tNum === 4) return t('SG时时彩');
  if (tNum === 5) return t('SG飞艇');
  if (tNum === 6) return t('极速快3');
  if (tNum === 7) return t('SG快3');
  return t('未知类型');
};

// 判断是否展示快3骰子
const isKuai3Dice = (row) => {
  const typeCode = row.type || row.gameplay?.type;
  const tNum = Number(typeCode);
  if ([6, 7].includes(tNum) && row.open_code) {
    return row.open_code.split(',').length === 3;
  }
  return false;
};

// 动态获取开奖球颜色 Class
const getBallColorClass = (numStr, typeCode) => {
  if (!numStr) return '';
  const tNum = Number(typeCode);

  if ([1, 3, 5].includes(tNum)) {
    const num = parseInt(numStr, 10);
    return `color-${num}`;
  } else if ([2, 4].includes(tNum)) {
    return 'wave-blue';
  }

  return 'wave-blue';
};

// --- 表格渲染辅助方法 ---
const getStatusTag = (row) => {
  const status = Number(row.status);
  if (status === 0) return { text: t('未开奖'), type: 'warning' };
  if (status === 1) return { text: t('未中奖'), type: 'danger' };
  if (status === 2) return { text: t('已中奖'), type: 'success' };
  if (status === 3) return { text: t('已退款'), type: 'info' };
  return { text: '-', type: 'info' };
};

const getProfitClass = (row) => {
  const status = Number(row.status);
  if (status === 1) return 'text-danger';
  if (status === 2) return 'text-success';
  return 'text-gray';
};

const getProfitText = (row) => {
  const status = Number(row.status);
  if (status === 0) return '--';
  if (status === 1) return `-${parseFloat(row.amount || 0).toFixed(2)}`;
  if (status === 2) return `+${parseFloat(row.profit_and_loss || row.win_amount || 0).toFixed(2)}`;
  if (status === 3) return '0.00';
  return '0.00';
};

const copyText = async (text) => {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success(t('复制成功'));
  } catch (err) {
    const input = document.createElement('input');
    input.value = text;
    document.body.appendChild(input);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);
    ElMessage.success(t('复制成功'));
  }
};

const handleGameDetail = (row) => {
  router.push({ name: 'JisuDetail', query: { id: row.id } });
}
</script>

<style scoped lang="scss">
$main-color: #3c9cff;

.champion-order-component {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: hidden;

  .filter-body {
    margin-bottom: 8px;
    .search-form { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-bottom: 0; }
    :deep(.el-form-item) { margin-right: 6px; margin-bottom: 0; display: flex; align-items: center; }
    .btn-icon { margin-right: 4px; }
  }

  .order-no-box {
    display: flex; align-items: center; gap: 4px;
    .copy-icon { cursor: pointer; color: var(--el-text-color-secondary); font-size: 14px; &:hover { color: $main-color; } }
  }

  .issue-no { font-family: monospace; color: var(--el-text-color-regular); font-size: 13px; }

  .game-tag { border-radius: 4px; }
  .bet-keywords { font-weight: bold; color: var(--el-text-color-primary); font-size: 13px; }

  /* 开奖结果样式 */
  .open-result-box {
    display: flex;
    flex-direction: column;
    gap: 6px;

    .res-balls {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;

      .dice-item {
        width: 25px;
        height: 25px;
        background-color: #ffffff;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        display: grid;
        padding: 3px;
        grid-template-columns: repeat(3, 1fr);
        grid-template-rows: repeat(3, 1fr);
        box-shadow: inset 0 -2px 0 rgba(0,0,0,0.05), 0 1px 3px rgba(0,0,0,0.1);
        box-sizing: border-box;

        .dot {
          width: 5px;
          height: 5px;
          border-radius: 50%;
          background-color: #303133;
          justify-self: center;
          align-self: center;
        }

        &.dice-1 { .dot:nth-child(1) { grid-column: 2; grid-row: 2; width: 6px; height: 6px; } }
        &.dice-2 { .dot:nth-child(1) { grid-column: 1; grid-row: 1; } .dot:nth-child(2) { grid-column: 3; grid-row: 3; } }
        &.dice-3 { .dot:nth-child(1) { grid-column: 1; grid-row: 1; } .dot:nth-child(2) { grid-column: 2; grid-row: 2; } .dot:nth-child(3) { grid-column: 3; grid-row: 3; } }
        &.dice-4 {
          .dot:nth-child(1) { grid-column: 1; grid-row: 1; }
          .dot:nth-child(2) { grid-column: 3; grid-row: 1; }
          .dot:nth-child(3) { grid-column: 1; grid-row: 3; }
          .dot:nth-child(4) { grid-column: 3; grid-row: 3; }
        }
        &.dice-5 {
          .dot:nth-child(1) { grid-column: 1; grid-row: 1; }
          .dot:nth-child(2) { grid-column: 3; grid-row: 1; }
          .dot:nth-child(3) { grid-column: 2; grid-row: 2; }
          .dot:nth-child(4) { grid-column: 1; grid-row: 3; }
          .dot:nth-child(5) { grid-column: 3; grid-row: 3; }
        }
        &.dice-6 {
          .dot:nth-child(1) { grid-column: 1; grid-row: 1; }
          .dot:nth-child(2) { grid-column: 1; grid-row: 2; }
          .dot:nth-child(3) { grid-column: 1; grid-row: 3; }
          .dot:nth-child(4) { grid-column: 3; grid-row: 1; }
          .dot:nth-child(5) { grid-column: 3; grid-row: 2; }
          .dot:nth-child(6) { grid-column: 3; grid-row: 3; }
        }

        &.dice-red .dot {
          background-color: #f56c6c;
        }
      }

      .ball-item {
        width: 22px;
        height: 22px;
        color: #ffffff;
        font-size: 12px;
        font-weight: bold;
        border-radius: 50%;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        background: #ccc;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

        &.wave-blue { background: linear-gradient(135deg, #42a5f5, #1e88e5); box-shadow: 0 1px 3px rgba(66, 165, 245, 0.3); }
        &.color-1 { background: #E6DE00; text-shadow: 0 1px 1px rgba(0,0,0,0.3); box-shadow: 0 1px 3px rgba(230, 222, 0, 0.3); }
        &.color-2 { background: #0092FF; box-shadow: 0 1px 3px rgba(0, 146, 255, 0.3); }
        &.color-3 { background: #4D4D4D; box-shadow: 0 1px 3px rgba(77, 77, 77, 0.3); }
        &.color-4 { background: #FF7600; box-shadow: 0 1px 3px rgba(255, 118, 0, 0.3); }
        &.color-5 { background: #17E2E5; box-shadow: 0 1px 3px rgba(23, 226, 229, 0.3); }
        &.color-6 { background: #5234FF; box-shadow: 0 1px 3px rgba(82, 52, 255, 0.3); }
        &.color-7 { background: #BFBFBF; box-shadow: 0 1px 3px rgba(191, 191, 191, 0.3); }
        &.color-8 { background: #FF2600; box-shadow: 0 1px 3px rgba(255, 38, 0, 0.3); }
        &.color-9 { background: #780B00; box-shadow: 0 1px 3px rgba(120, 11, 0, 0.3); }
        &.color-10 { background: #07BF00; box-shadow: 0 1px 3px rgba(7, 191, 0, 0.3); }
      }
    }

    .res-others {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;
      .other-tag {
        margin-right: 2px;
      }
    }
  }

  .odds-val { font-weight: bold; color: #f8b932; font-size: 14px; }
  .val-text { font-size: 13px; font-weight: bold; color: var(--el-text-color-primary);  }
  .profit-val { font-size: 14px; font-weight: bold; font-family: DIN, monospace; }

  .ml-2 { margin-left: 8px; }

  .text-success { color: var(--el-color-success) !important; }
  .text-danger { color: var(--el-color-danger) !important; }
  .text-gray { color: var(--el-text-color-placeholder) !important; }

  .pagination-wrapper {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
    flex-shrink: 0;
  }
}
</style>