<script setup>
import { ref, watch, onMounted } from 'vue';
import { requestClient } from '#/api/request';
import { Page } from '@vben/common-ui';
import { Form, Input, RadioGroup, Radio, Button, message } 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(-1);
const idsText = ref('');
const idsList = ref([]);
const buttonDisabled = ref(false);

const prettyData = ref(null);
const prettyKey = ref(Date.now());
const dataCount = ref('');

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

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

const idsInput = (value) => {
  idsList.value = idsText.value.split(',').map(item => +item.trim()).filter(item => !!item);
}

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

const showDataPretty = (data, deep) => {
  prettyData.value = data;
  prettyKey.value = Date.now();
}

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 filterLive = () => {
  const solutions = gamesSolution.value.solutions;
  const liveSolutions = solutions.filter((solution) => {
    const { info: { ob, hg, ps } } = solution;
    return ps.stage;
  });
  dataCount.value = `${liveSolutions.length}`;
  showDataPretty(liveSolutions, 2);
  console.log('liveSolutions', liveSolutions);
}

const filterHalf = () => {
  const solutions = gamesSolution.value.solutions;
  const halfSolutions = solutions.filter((solution) => {
    const { info: { ob, hg, ps } } = solution;
    return ps.stage === 'HT';
  });
  dataCount.value = `${halfSolutions.length}`;
  showDataPretty(halfSolutions, 2);
  console.log('halfSolutions', halfSolutions);
}

const filterTarget = () => {
  requestClient.get('/pstery/get_games_relation', { params: { mk: selectedTestMode.value, le: true, id: idsText.value } })
  .then(data => {
    dataCount.value = `${data.length}`;
    showDataPretty(data, 2);
    console.log('data', data);
  })
  .catch(err => {
    message.error('数据获取失败');
    console.error('数据获取失败', err);
  })
}

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

<template>
  <Page title="数据测试" description="用于测试和验证比赛数据的页面">

    <Form :label-col="{ span: 2 }" :wrapper-col="{ span: 14 }">
      <Form.Item label="数据源：">
        <span>比赛管理系统</span>
      </Form.Item>
      <Form.Item label="更新时间：">
        <span>{{ currentTime }}</span>
      </Form.Item>
      <Form.Item label="测试模式：">
        <RadioGroup v-model:value="selectedTestMode">
          <Radio :value="-1">全部</Radio>
          <Radio :value="2">滚球</Radio>
          <Radio :value="1">今日</Radio>
          <Radio :value="0">早盘</Radio>
        </RadioGroup>
      </Form.Item>
      <Form.Item label="目标赛事ID：">
        <Input v-model:value="idsText" placeholder="请输入赛事ID，多个ID用逗号分隔" @input="idsInput" />
      </Form.Item>
      <Form.Item :wrapper-col="{ span: 14, offset: 2 }">
        <Button @click="refreshData" :disabled="buttonDisabled">
          刷新数据
        </Button>
        <Button @click="runTest(true)" :disabled="buttonDisabled">
          有欢乐值
        </Button>
        <Button @click="runTest(false)" :disabled="buttonDisabled">
          无欢乐值
        </Button>
        <Button @click="filterLive" :disabled="buttonDisabled">
          筛选滚球
        </Button>
        <Button @click="filterHalf" :disabled="buttonDisabled">
          筛选中场
        </Button>
        <Button @click="filterTarget" :disabled="!idsList.length">
          目标赛事
        </Button>
      </Form.Item>
    </Form>

    <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="2" :key="prettyKey" :showDoubleQuotes="false"></vue-json-pretty>
    </div>
  </Page>
</template>

<style lang="scss" scoped>
.data-table {
  padding: 20px;
}
</style>