<template>
  <div class="data-test-container">
    <div class="page-header">
      <h1>数据测试</h1>
      <p>用于测试和验证比赛数据的页面</p>
    </div>

    <div class="content-area">
      <div class="test-panel">
        <h2>测试数据展示</h2>
        <div class="data-display">
          <div class="data-item">
            <label>当前时间：</label>
            <span>{{ currentTime }}</span>
          </div>
          <!-- <div class="data-item">
            <label>测试状态：</label>
            <span class="status-success">正常运行</span>
          </div> -->
          <div class="data-item">
            <label>数据源：</label>
            <span>比赛管理系统</span>
          </div>
        </div>

        <div class="radio-options">
          <div class="radio-group">
            <label class="radio-label">
              <input
                type="radio"
                name="testMode"
                value="1"
                v-model="selectedTestMode"
                class="radio-input"
              >
              <span class="radio-text">今日</span>
            </label>
            <label class="radio-label">
              <input
                type="radio"
                name="testMode"
                value="0"
                v-model="selectedTestMode"
                class="radio-input"
              >
              <span class="radio-text">早盘</span>
            </label>
            <label class="radio-label">
              <input
                type="radio"
                name="testMode"
                value=""
                v-model="selectedTestMode"
                class="radio-input"
              >
              <span class="radio-text">全部</span>
            </label>
          </div>
        </div>

        <div class="action-buttons">
          <Button @click="refreshData" :disabled="buttonDisabled">
            刷新数据
          </Button>
          <Button @click="runTest(true)" :disabled="buttonDisabled">
            有欢乐值
          </Button>
          <Button @click="runTest(false)" :disabled="buttonDisabled">
            无欢乐值
          </Button>
          <Button @click="verifyData" :disabled="buttonDisabled">
            验证数据
          </Button>
          <Button @click="filterLive" :disabled="buttonDisabled">
            筛选滚球
          </Button>
        </div>
      </div>
    </div>

    <div class="data-table" v-if="prettyData">
      <div class="data-count" v-if="dataCount">
        <span>数据总数：{{ dataCount }}</span>
      </div>
      <vue-json-pretty :data="prettyData" :indent="2" :deep="prettyDeep" :showDoubleQuotes="false"></vue-json-pretty>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { requestClient } from '#/api/request';
import { Button, message, InputNumber } from 'ant-design-vue';

import dayjs from 'dayjs';
import VueJsonPretty from 'vue-json-pretty';
import 'vue-json-pretty/lib/styles.css';

const currentTime = ref('');
const gamesRelation = ref([]);
const gamesSolution = ref({});
const selectedTestMode = ref('');
const buttonDisabled = ref(false);

const prettyData = ref(null);
const prettyDeep = ref(0);
const dataCount = ref('');

watch(selectedTestMode, () => {
  refreshData();
});

const updateTime = () => {
  currentTime.value = new Date().toLocaleString('zh-CN')
}

const refreshData = () => {
  buttonDisabled.value = true;
  updateTime();
  Promise.all([
    requestClient.get('/pstery/get_games_relation', { params: { mk: selectedTestMode.value } }),
    requestClient.get('/pstery/get_solutions', { params: { win_min: -99999 } })
  ])
  .then(([relations, solutions]) => {
    gamesRelation.value = relations;
    gamesSolution.value = solutions;
    prettyData.value = null;
    prettyDeep.value = 0;
    message.success('数据已刷新');
    console.log('数据已刷新');
  })
  .catch(err => {
    message.error('数据刷新失败');
    console.error('数据刷新失败', err);
  })
  .finally(() => {
    buttonDisabled.value = false;
  });
}

const showDataPretty = (data, deep) => {
  prettyDeep.value = 0;
  prettyData.value = data;
  prettyDeep.value = deep;
}

const runTest = (hasSolutions=true) => {
  const gamesList = gamesRelation.value.map(item => {
    const { mk } = item ?? {};
    const { eventId, leagueName, teamHomeName, teamAwayName, timestamp } = item?.rel?.ps ?? {};
    const datetime = dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
    return { eventId, leagueName, teamHomeName, teamAwayName, datetime, mk };
  });
  gamesSolution.value.solutions.forEach((solution) => {
    const { sid, info: { id }} = solution;
    const currentGame = gamesList.find(game => game.eventId === id);
    if (!currentGame) {
      console.log('game not found', id);
    }
    else {
      if (!currentGame.solutions) {
        currentGame.solutions = [];
      }
      currentGame.solutions.push(sid);
    }
  });
  const dataList = gamesList.filter(item => {
    if (hasSolutions) {
      return !!item.solutions?.length;
    }
    else {
      return !item.solutions?.length;
    }
  }).map((item, index) => {
    const serial = index + 1;
    return { serial, ...item };
  });
  dataCount.value = `${dataList.length} / ${gamesList.length}`;
  showDataPretty(dataList, 2);
  console.log('gamesRelation', dataList);
}

const verifyData = () => {
  const solutions = gamesSolution.value.solutions;
  const invalidSolutions = [];
  solutions.forEach((solution) => {
    const { sol: { win_average, win_profit_rate } } = solution;
    if (win_average * win_profit_rate < 0) {
      invalidSolutions.push(solution)
    }
  });
  showDataPretty(invalidSolutions, 2);
  console.log('invalidSolutions', invalidSolutions);
}

const filterLive = () => {
  const solutions = gamesSolution.value.solutions;
  const liveSolutions = solutions.filter((solution) => {
    const { info: { ob, hg, ps } } = solution;
    return ps.stage;
  });
  showDataPretty(liveSolutions, 2);
  console.log('liveSolutions', liveSolutions);
}

// const currentTime = ref('')

// const updateTime = () => {
//   currentTime.value = new Date().toLocaleString('zh-CN')
// }

// const refreshData = () => {
//   updateTime()
//   console.log('数据已刷新')
// }

// const runTest = () => {
//   console.log('开始运行测试...')
//   // 这里可以添加具体的测试逻辑
// }

onMounted(() => {
  refreshData();
})
</script>

<style lang="scss" scoped>
.data-test-container {
  padding: 20px;

  .page-header {
    margin-bottom: 30px;

    h1 {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 8px;
      color: #333;
    }

    p {
      color: #666;
      font-size: 14px;
    }
  }

  .content-area {
    .test-panel {
      background: #fff;
      border-radius: 8px;
      padding: 24px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      h2 {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 20px;
        color: #333;
      }

      .data-display {
        margin-bottom: 24px;

        .data-item {
          display: flex;
          align-items: center;
          margin-bottom: 12px;

          label {
            font-weight: 500;
            color: #555;
            min-width: 100px;
          }

          span {
            color: #333;

            &.status-success {
              color: #52c41a;
              font-weight: 500;
            }
          }
        }
      }

      .radio-options {
        margin-bottom: 20px;

        .radio-group {
          display: flex;
          gap: 20px;

          .radio-label {
            display: flex;
            align-items: center;
            cursor: pointer;
            user-select: none;

            .radio-input {
              margin-right: 8px;
              cursor: pointer;
            }

            .radio-text {
              font-size: 14px;
              color: #333;
            }
          }
        }
      }
    }
  }
}
.data-table {
  padding: 20px;
}
</style>