<template>
  <div class="pc-history-container">
    <div class="list-wrapper">

      <div class="filter-header">
        <div class="header-left">
          <div class="back-action" @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            <span class="back-text">{{ t('返回') }}</span>
          </div>

          <el-divider direction="vertical" class="header-divider" />

          <div class="title-line">
            <div class="decorate-bar bmc"></div>
            <span class="title-text">{{ t('往期开奖历史') }}</span>
          </div>
        </div>

        <div class="actions-right">
          <span class="date-label">{{ t('开奖日期') }}:</span>
          <el-date-picker
              v-model="dateRange"
              type="daterange"
              :start-placeholder="t('开始日期')"
              :end-placeholder="t('结束日期')"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              class="mr-3"
              @change="handleQuery"
          />
          <el-button type="primary" @click="handleQuery">
            <el-icon class="mr-1"><Search /></el-icon>{{ t('查询') }}
          </el-button>
          <el-button @click="handleReset">
            <el-icon class="mr-1"><RefreshRight /></el-icon>{{ t('重置') }}
          </el-button>
        </div>
      </div>

      <div class="table-card" v-loading="loading">
        <el-table
            :data="validHistoryList"
            style="width: 100%"
            height="100%"
            :empty-text="t('暂无历史记录')"
        >
          <el-table-column :label="t('期号')" width="200">
            <template #default="{ row }">
              <span class="issue-text">{{ row.issue_no || row.section }} {{ t('期') }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="day" :label="t('开奖时间')" width="220" />

          <el-table-column :label="t('开奖结果')" min-width="300">
            <template #default="{ row }">
              <div class="h-equation" v-if="row.winning_array && row.winning_array.length >= 4">
                <div class="circle">{{ row.winning_array[0] }}</div>
                <span class="op">+</span>
                <div class="circle">{{ row.winning_array[1] }}</div>
                <span class="op">+</span>
                <div class="circle">{{ row.winning_array[2] }}</div>
                <span class="op">=</span>
                <div class="circle result">{{ row.winning_array[3] }}</div>
              </div>
              <div class="h-equation" v-else-if="row.openCode1 !== undefined">
                <div class="circle">{{ row.openCode1 }}</div>
                <span class="op">+</span>
                <div class="circle">{{ row.openCode2 }}</div>
                <span class="op">+</span>
                <div class="circle">{{ row.openCode3 }}</div>
                <span class="op">=</span>
                <div class="circle result">{{ Number(row.openCode1) + Number(row.openCode2) + Number(row.openCode3) }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column :label="t('结果属性')" min-width="200">
            <template #default="{ row }">
              <div class="h-tags" v-if="row.combo || row.award">
                <template v-if="row.combo">
                  <el-tag
                      v-for="(tag, i) in row.combo"
                      :key="'c'+i"
                      :type="getTagType(tag)"
                      effect="dark"
                      size="small"
                      class="mr-1"
                  >
                    {{ tag }}
                  </el-tag>
                </template>
                <template v-else-if="row.award">
                  <el-tag
                      v-for="(tag, i) in row.award.slice(0, 3)"
                      :key="'a'+i"
                      :type="getTagType(tag)"
                      effect="dark"
                      size="small"
                      class="mr-1"
                      v-show="tag"
                  >
                    {{ tag }}
                  </el-tag>
                </template>
              </div>
            </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="[20, 50, 100]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { Search, RefreshRight, ArrowLeft } from '@element-plus/icons-vue';
import { apiUrl } from "@/request/index";

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

// 状态变量
const loading = ref(false);
const historyList = ref([]);
const total = ref(0);

// 分页与筛选参数
const queryParams = ref({
  page: 1,
  limit: 20
});
const dateRange = ref(null);

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

const goBack = () => {
  router.back();
};

const getApiBasePath = () => {
  return 'pcissue';
};

// 过滤出真正已经开奖的数据
const validHistoryList = computed(() => {
  return historyList.value.filter(item => {
    return (item.winning_array && item.winning_array.length >= 4) ||
        (item.openCode1 !== undefined && item.openCode1 !== null);
  });
});

const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      page: queryParams.value.page,
      limit: queryParams.value.limit
    };

    if (dateRange.value && dateRange.value.length === 2) {
      params.start_time = dateRange.value[0];
      params.end_time = dateRange.value[1];
    }

    const response = await fetch(`${apiUrl}${getApiBasePath()}?page=${params.page}&limit=${params.limit}${params.start_time ? `&start_time=${params.start_time}&end_time=${params.end_time}` : ''}`, {
      headers: {
        'lang': locale.value
      }
    });
    const res = await response.json();

    if (res && res.code === 0 && res.data && res.data.data) {
      historyList.value = res.data.data;
      total.value = res.data.total || 0;
    } else {
      historyList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取历史记录失败', error);
    historyList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

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

const handleReset = () => {
  dateRange.value = null;
  queryParams.value.page = 1;
  fetchData();
};

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

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

// 映射标签颜色
const getTagType = (text) => {
  if (['大', '双', '极大'].includes(text)) return 'danger';
  if (['小', '单', '极小'].includes(text)) return 'success';
  return 'primary';
};
</script>

<style scoped lang="scss">
$main-color: #f8b932;
$card-bg: var(--el-bg-color-overlay);
$border-color: var(--el-border-color-lighter);

.pc-history-container {
  /* 声明顶级盒子为容器查询基准点 */
  container-type: inline-size;
  container-name: history-container;

  height: 100%;
  padding: 6px 8px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  @container history-container (max-width: 800px) { padding: 4px; }
  @container history-container (max-width: 550px) { padding: 2px; }

  .list-wrapper {
    display: flex; flex-direction: column; width: 100%; flex: 1; overflow: hidden;
  }
}

/* 统一头部容器 (标题 + 筛选) */
.filter-header {
  display: flex;
  justify-content: space-between; /* 左右两端对齐 */
  align-items: center;
  padding: 8px 12px;
  background-color: $card-bg;
  border-bottom: 1px solid $border-color;
  border-radius: 6px 6px 0 0; /* 顶部圆角 */
  flex-shrink: 0;

  /* 容器变窄时自动换行适应 */
  @container history-container (max-width: 800px) { padding: 6px 8px; flex-wrap: wrap; gap: 8px; }
  @container history-container (max-width: 550px) { flex-direction: column; align-items: flex-start; gap: 8px; }

  /* 左侧标题区域样式 */
  .header-left {
    display: flex; align-items: center;
    .back-action { display: flex; align-items: center; cursor: pointer; color: var(--el-text-color-regular); font-size: 13px; transition: color 0.2s; &:hover { color: $main-color; } .el-icon { margin-right: 2px; } }
    .header-divider { margin: 0 10px; height: 14px; }
    .title-line { display: flex; align-items: center; .decorate-bar { width: 3px; height: 12px; background-color: $main-color; margin-right: 6px; border-radius: 2px; } .title-text { font-size: 14px; font-weight: bold; color: var(--el-text-color-primary); } }
  }

  /* 右侧表单区域样式 */
  .actions-right {
    display: flex; align-items: center;

    @container history-container (max-width: 800px) { width: 100%; justify-content: flex-end; }
    @container history-container (max-width: 550px) {
      width: 100%; flex-wrap: wrap; gap: 6px;
      .el-date-editor { width: 100% !important; margin-right: 0 !important; height: 28px; }
      .el-button { flex: 1; margin-left: 0; margin-right: 4px; height: 28px; &:last-child{ margin-right: 0; } }
    }

    .date-label {
      font-size: 13px; color: var(--el-text-color-regular); margin-right: 6px;
      @container history-container (max-width: 550px) { display: none; }
    }

    /* 按钮与日历组件高度压缩 */
    :deep(.el-date-editor) { height: 28px; padding: 0 8px; }
    :deep(.el-range-separator) { line-height: 26px; font-size: 12px; padding: 0 4px; }
    :deep(.el-input__inner) { font-size: 12px; }
    :deep(.el-range-input) { font-size: 12px; }

    .el-button { height: 28px; padding: 4px 10px; font-size: 12px; border-radius: 4px; }
  }
}

/* 历史记录表格卡片 */
.table-card {
  flex: 1; background-color: $card-bg; border-radius: 0 0 6px 6px;
  padding: 6px 8px;
  display: flex; flex-direction: column; overflow: hidden; box-shadow: 0 1px 2px rgba(0,0,0,0.05);

  @container history-container (max-width: 800px) { padding: 4px 6px; }
  @container history-container (max-width: 550px) { padding: 2px 4px; }

  :deep(.el-table) {
    font-size: 12px;
    @container history-container (max-width: 800px) { font-size: 11px; }

    .el-table__header th { padding: 6px 0; font-size: 13px; background-color: var(--el-fill-color-light); }
    .el-table__cell { padding: 6px 0; }
    .cell { padding: 0 8px; line-height: 1.4; }
  }

  .issue-text {
    font-family: monospace; font-weight: bold; color: var(--el-color-danger); font-size: 13px;
    @container history-container (max-width: 800px) { font-size: 12px; }
  }

  .h-equation {
    display: flex; align-items: center; gap: 4px;
    @container history-container (max-width: 550px) { gap: 2px; }

    .circle {
      width: 22px; height: 22px;
      border-radius: 50%; background-color: var(--el-fill-color); border: 1px solid var(--el-border-color); display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: bold; color: var(--el-text-color-primary); box-shadow: inset 0 -1px 0 rgba(0,0,0,0.05);

      @container history-container (max-width: 800px) { width: 20px; height: 20px; font-size: 11px; }
      @container history-container (max-width: 550px) { width: 18px; height: 18px; font-size: 10px; }

      &.result {
        background-color: var(--el-color-danger); border: none; color: #fff; font-size: 13px; box-shadow: 0 1px 2px rgba(245,108,108,0.4);
        @container history-container (max-width: 800px) { font-size: 12px; }
        @container history-container (max-width: 550px) { font-size: 11px; }
      }
    }

    .op {
      color: var(--el-text-color-secondary); font-weight: bold; font-size: 13px;
      @container history-container (max-width: 800px) { font-size: 12px; }
      @container history-container (max-width: 550px) { font-size: 11px; }
    }
  }

  .h-tags {
    display: flex; flex-wrap: wrap; gap: 4px;
    .el-tag {
      height: 20px; padding: 0 6px; line-height: 18px; font-size: 11px; border-radius: 2px;
      @container history-container (max-width: 800px) { height: 18px; padding: 0 4px; line-height: 16px; font-size: 10px; }
    }
  }

  .pagination-wrapper {
    margin-top: 10px; display: flex; justify-content: flex-end; flex-shrink: 0;

    @container history-container (max-width: 550px) { margin-top: 8px; justify-content: center; }

    :deep(.el-pagination) {
      --el-pagination-button-height: 26px;
      --el-pagination-font-size: 12px;
      --el-pagination-button-width: 26px;
      display: flex; align-items: center; flex-wrap: wrap; justify-content: center; gap: 4px;

      .el-pagination__total { margin-right: 4px; font-size: 12px; height: 26px; line-height: 26px; }
      .el-pagination__sizes {
        margin-right: 4px;
        .el-select .el-select__wrapper { min-height: 26px !important; height: 26px !important; padding: 0 6px; font-size: 12px; line-height: 26px; }
      }
      .btn-prev, .btn-next { min-width: 26px; height: 26px; padding: 0 4px; border-radius: 4px; }
      .el-pager li { min-width: 26px; height: 26px; line-height: 26px; font-size: 12px; margin: 0 2px; border-radius: 4px; }

      .el-pagination__jump {
        margin-left: 4px; font-size: 12px; height: 26px; line-height: 26px;
        .el-input { width: 40px; height: 26px; .el-input__wrapper { height: 26px; padding: 0 4px; .el-input__inner { font-size: 12px; text-align: center; } } }
      }
    }
  }
}

.mr-1 { margin-right: 4px; }
.mr-3 { margin-right: 8px; }
</style>
