<template>
  <div class="merged-lottery-component">
    <div class="filter-body">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item :label="t('彩种类型')">
          <el-select v-model="queryParams.type" :placeholder="t('全部彩种')" style="width: 140px;" clearable @change="handleQuery">
            <el-option v-for="item in lotteryTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <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="170">
        <template #default="scope">
          <div class="order-no-box">
            <span class="issue-no">{{ scope.row.ordernum || '--' }}</span>
            <el-icon class="copy-icon" v-if="scope.row.ordernum" @click="copyText(scope.row.ordernum)"><DocumentCopy /></el-icon>
          </div>
        </template>
      </el-table-column>

      <el-table-column :label="t('类型')" min-width="120" align="center">
        <template #default="scope">
          <el-tag :type="getLotteryTypeTag(scope.row.type)" effect="plain">
            {{ getLotteryGameName(scope.row.type, t) }}
          </el-tag>
        </template>
      </el-table-column>

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

      <el-table-column :label="t('投注内容')" min-width="180">
        <template #default="scope">
          <span class="type-name" v-if="scope.row.gameplay">[{{ scope.row.gameplay }}] - </span>
          <span class="bet-keywords" v-for="(item, index) in scope.row.items" :key="index">
            <span v-if="index !== 0">,</span>{{ item.number }}
          </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="380" align="center">
        <template #default="scope">
          <LotteryOpenResult :row="scope.row" />
        </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('投注金额')" min-width="100" align="center">
        <template #default="scope">
          <span class="val-text">{{ parseFloat(scope.row.total_amount || 0).toFixed(2) }}</span>
        </template>
      </el-table-column>

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

      <el-table-column :label="t('投注时间')" min-width="170" align="center">
        <template #default="scope">
          {{ formatTime(scope.row.created_at) }}
        </template>
      </el-table-column>

      <el-table-column :label="t('操作')" width="90" align="center" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="handleDetail(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 { getLotteryGameName, getLotteryTypeTag, getLotteryStatusTag } from './game.js';
import LotteryOpenResult from './OpenResult.vue';

import { getDigitalOrderList } from '@/request/api.js';

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

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

const queryParams = reactive({
  page: 1,
  limit: 20,
  type: '',
  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 },
  { label: t('已退款'), value: 4 }
]);

const lotteryTypeOptions = computed(() => [
  { label: t('全部'), value: '' },
  { label: t('新澳门六合彩'), value: 1 },
  { label: t('香港六合彩'), value: 2 },
  { label: t('澳门六合彩'), value: 3 },
  { label: t('极速六合彩'), value: 4 },
  { label: t('加拿大28'), value: 5 },
  { label: t('极速28'), value: 6 },
  { label: t('极速赛车'), value: 7 },
  { label: t('极速时时彩'), value: 8 },
  { label: t('极速飞艇'), value: 9 },
  { label: t('SG时时彩'), value: 10 },
  { label: t('SG飞艇'), value: 11 },
  { label: t('极速快3'), value: 12 },
  { label: t('SG快3'), value: 13 }
]);

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 = '';
  queryParams.type = '';
  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 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 || status === 2) {
    const val = Number(row.win_amount || 0);
    return val > 0 ? `+${val.toFixed(2)}` : val.toFixed(2);
  }
  return '0.00';
};

const formatTime = (time) => {
  return  time
};

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 handleDetail = (row) => {
  router.push({name: 'LotteryOrderDetail', query: { id: row.id }});
}
</script>

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

.merged-lottery-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: 14px; &:hover { color: $main-color; } }
  }

  .issue-no { font-family: monospace; color: var(--el-text-color-regular); font-size: 13px; }
  .type-name { font-weight: bold; color: var(--el-text-color-primary); font-size: 13px; }
  .type-sub { color: var(--el-text-color-regular); font-size: 13px; }

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