<template>
  <div class="digital-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.lottery_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="140">
        <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('类型')" align="center" width="130">
        <template #default="scope">
          <el-tag 
            class="odds-val" 
            :type="{ 1: 'primary', 2: 'success', 3: 'warning', 4: 'danger' }[scope.row.type] || 'info'"
          >
            {{ { 1: t('新澳门六合彩'), 2: t('香港六合彩'), 3: t('澳门六合彩'), 4: t('极速六合彩') }[scope.row.type] }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column :label="t('彩种/期号')" min-width="140" align="center">
        <template #default="scope">
          <span class="type-name">{{ scope.row.game }}</span>
          <span class="type-sub"> - 第{{ scope.row.issue }}期</span>
        </template>
      </el-table-column>

      <el-table-column :label="t('投注内容')" min-width="160">
        <template #default="scope">
          <span class="type-name">[{{ scope.row.gameplay }}]</span>
          <span class="bet-keywords ml-2">{{ scope.row.number }}</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="200" align="center">
        <template #default="scope">
          <div v-if="scope.row.lottery && scope.row.lottery.open_code" class="lhc-draw-result">
            <div class="open-time" v-if="scope.row.lottery.open_time">{{ scope.row.lottery.open_time }}</div>
            <div class="lhc-open-code-box">
              <template v-for="(code, index) in scope.row.lottery.open_code.split(',')" :key="index">
                <div v-if="index === scope.row.lottery.open_code.split(',').length - 1" class="plus-sign">+</div>
                <div :class="['lhc-ball', getBallColorClass(code)]">
                  <span class="ball-inner">{{ code }}</span>
                </div>
              </template>
            </div>
          </div>
          <span v-else>--</span>
        </template>
      </el-table-column>

      <el-table-column :label="t('盈亏')" min-width="120" align="center">
        <template #default="scope">
          <span v-if="scope.row.lottery_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="right" />

      <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 { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { Search, RefreshRight, DocumentCopy } from '@element-plus/icons-vue';

// 引入获取购彩记录的真实接口
import { getDigitalOrderList } from '@/request/api.js';
import router from "@/router/index.js";

const { t } = useI18n();

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

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

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 getDigitalOrderList(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.lottery_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 getBallColorClass = (numStr) => {
  const num = parseInt(numStr, 10);
  if (isNaN(num)) return 'bg-gray';
  
  const reds = [1, 2, 7, 8, 12, 13, 18, 19, 23, 24, 29, 30, 34, 35, 40, 45, 46];
  const blues = [3, 4, 9, 10, 14, 15, 20, 25, 26, 31, 36, 37, 41, 42, 47, 48];
  const greens = [5, 6, 11, 16, 17, 21, 22, 27, 28, 32, 33, 38, 39, 43, 44, 49];
  
  if (reds.includes(num)) return 'bg-red';
  if (blues.includes(num)) return 'bg-blue';
  if (greens.includes(num)) return 'bg-green';
  
  return 'bg-gray'; // 异常兜底
};

// --- 表格渲染辅助方法 ---
const getStatusTag = (row) => {
  const status = Number(row.lottery_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' };
  if (status === 3) return { text: t('购物车'), type: 'info' };
  return { text: '-', type: 'info' };
};

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

const getProfitText = (row) => {
  const status = Number(row.lottery_status);

  if(status === 1) {
    return row.profit_and_loss || '--';
  } else if(status === 2) {
    return row.win_amount || '--'
  } else {
    return 0
  }
};

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: 'DigitalOrderDetail',query: { id: row.id }});
}
</script>

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

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

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

  .issue-no {  color: var(--el-text-color-regular); font-size: 12px; }
  .bet-keywords { font-weight: bold; color: $main-color; font-size: 12px; }
  .type-name { font-weight: bold; color: var(--el-text-color-primary); font-size: 12px; }
  .type-sub { color: var(--el-text-color-regular); font-size: 12px; }
  .odds-val { font-weight: bold; color: $main-color; font-size: 13px; }
  .val-text { font-size: 13px; font-weight: bold; color: var(--el-text-color-primary);  }
  .profit-val { font-size: 13px; font-weight: bold;  }

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

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

  .lhc-draw-result {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 6px;
    padding: 4px 0;

    .open-time {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      font-family: DIN, monospace;
    }

    .lhc-open-code-box {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      justify-content: center;
      gap: 6px;

      /* 替换为详情页的高光质感波色样式，适配表格尺寸 */
      .lhc-ball {
        width: 28px;
        height: 28px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2px 5px rgba(0,0,0,0.3), inset 0 -2px 2px rgba(0,0,0,0.2);
        position: relative;
        
        &::after {
          content: '';
          position: absolute;
          top: 3px;
          left: 5px;
          width: 8px;
          height: 5px;
          background: rgba(255,255,255,0.2);
          border-radius: 50%;
        }
        
        .ball-inner {
          font-size: 13px;
          font-weight: 900;
          color: #fff;
          text-shadow: 0 1px 2px rgba(0,0,0,0.3);
        }

        &.bg-red { background: linear-gradient(135deg, #ff6b6b 0%, #dc2626 100%); }
        &.bg-blue { background: linear-gradient(135deg, #60a5fa 0%, #2563eb 100%); }
        &.bg-green { background: linear-gradient(135deg, #34d399 0%, #059669 100%); }
        &.bg-gray { background: linear-gradient(135deg, #9ca3af 0%, #4b5563 100%); }
      }

      .plus-sign {
        font-size: 16px;
        font-weight: bold;
        color: var(--el-text-color-regular);
        margin: 0 2px;
      }
    }
  }

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