<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="220">
        <template #default="scope">
          <el-tag type="primary" effect="light" class="game-tag" v-if="scope.row.game">
            {{ locale === 'zh' ? scope.row.game?.name : scope.row.game?.name_en }}
          </el-tag>
          <span class="bet-keywords ml-2">
            {{ locale === 'zh' ? scope.row.gameplay?.name : scope.row.gameplay?.name_en }}
          </span>
        </template>
      </el-table-column>

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

      <el-table-column :label="t('投注本金')" min-width="120" 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="120" 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="100" 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="90" 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 { sportGameOrderList } from '@/request/api.js';

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 sportGameOrderList(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 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) => {
  // 根据实际路由名称调整，这里假定PC端对应的详情路由为 ChampionOrderDetail
  router.push({ name: 'ChampionOrderDetail', query: { id: row.id } });
}
</script>

<style scoped lang="scss">
$main-color: #3c9cff; // 将色调适配为标准的体育蓝色系，如果您希望保持黄色，可改回 #f8b932

.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; }

  .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>
