<script setup>
import { requestClient } from '#/api/request';
import { Button, message } from 'ant-design-vue';
import { ref, reactive, computed, onMounted } from 'vue';
import dayjs from 'dayjs';
import MatchItem from '../components/match_item.vue';

const gamesList = reactive({});
const gamesRelations = reactive({});
const currentRelation = reactive({});
const selectedInfo = ref(null);

const formatDate = (timestamp) => {
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
}

const formatGameItem = (game, platform) => {
  const selected = currentRelation[platform]?.eventId == game.eventId;
  const { timestamp } = game;
  const dateTime = formatDate(timestamp);
  return { ...game, dateTime, selected };
}

const setGameOrderWeight= (game) => {
  const { t, l, h, a } = selectedInfo.value ?? {};
  game.orderWeight = 0;
  const { leagueName, teamHomeName, teamAwayName, timestamp } = game;
  if (timestamp != t) {
    game.orderWeight = -99;
  }
  else  {
    game.orderWeight += 1;
  }
  if (leagueName.startsWith(l)) {
    game.orderWeight += 1;
  }
  if (teamHomeName.startsWith(h)) {
    game.orderWeight += 1;
  }
  if (teamAwayName.startsWith(a)) {
    game.orderWeight += 1;
  }
  return game;
}

const getGameOrderList = (platform) => {
  let games = gamesList[platform]?.games ?? [];
  const relatedGames = new Set(Object.values(gamesRelations).map(item => item[platform]?.eventId));
  games = games.map(game => formatGameItem(game, platform));
  if (platform == 'jc') {
    return games.filter(game => !relatedGames.has(game.eventId))
    .sort((a, b) => {
      if (a.selected) {
        return -1;
      }
      return 1;
    });
  }
  return games.map(setGameOrderWeight)
  .sort((a, b) => b.orderWeight - a.orderWeight)
  .filter(game => {
    if (game.orderWeight > 0 && !relatedGames.has(game.eventId)) {
      return true;
    }
    return false;
  });
}

const showRelationButton = computed(() => {
  return currentRelation.ps || currentRelation.ob;
});

const relationsList = computed(() => {
  return Object.keys(gamesRelations).map(id => {
    const rel = gamesRelations[id];
    Object.values(rel).forEach(item => {
      item.dateTime = formatDate(item.timestamp);
    });
    return { id, rel };
  });
});

const jcGamesList = computed(() => {
  return getGameOrderList('jc');
});

const psGamesList = computed(() => {
  return getGameOrderList('ps');
});

const obGamesList = computed(() => {
  return getGameOrderList('ob');
});

const getGamesList = async () => {
  try {
    const data = await requestClient.get('/triangle/get_games_list');
    return data;
  }
  catch (error) {
    console.error('Failed to fetch games info:', error);
    message.error('获取比赛信息失败');
    return [];
  }
}

const getGamesRelations = async () => {
  try {
    const data = await requestClient.get('/triangle/get_games_relation');
    return data;
  }
  catch (error) {
    console.error('Failed to fetch game relations:', error);
    message.error('获取比赛关系失败');
    return [];
  }
}

const setGamesRelation = () => {
  const rel = currentRelation;
  Object.keys(rel).forEach(key => {
    if (!rel[key]) {
      delete rel[key];
    }
  });
  Object.values(rel).forEach(item => {
    delete item.orderWeight;
  });
  const id = rel['jc']?.eventId;
  if (!id) {
    console.log('没有选择竞彩的比赛');
    message.warn('设置比赛关系失败');
  }
  requestClient.post('/triangle/update_games_relation', { id, rel })
  .then(res => {
    console.log('设置比赛关系成功', res);
    message.success('设置比赛关系成功');
    selectedInfo.value = null;
    currentRelation.jc = currentRelation.ps = currentRelation.ob = null;
    updateGamesRelations();
  })
  .catch(error => {
    console.error('Failed to set game relation:', error);
    message.error('设置比赛关系失败');
  });
}

const removeGamesRelation = (id) => {
  requestClient.post('/triangle/remove_games_relation', { id })
  .then(res => {
    console.log('删除比赛关系成功', res);
    message.success('删除比赛关系成功');
    updateGamesRelations();
  })
  .catch(error => {
    console.error('Failed to remove game relation:', error);
    message.error('删除比赛关系失败');
  });
}

const openRelationModal = () => {
  relationModalVisible.value = true;
}

const updateGamesList = async () => {
  const data = await getGamesList();
  Object.keys(data).forEach(key => {
    gamesList[key] = data[key];
  });
}

const updateGamesRelations = async () => {
  const data = await getGamesRelations();
  data.forEach(item => {
    const { id, rel } = item;
    gamesRelations[id] = rel;
  });
  const newIds = new Set(data.map(item => item.id));
  Object.keys(gamesRelations).forEach(id => {
    if (!newIds.has(id)) {
      delete gamesRelations[id];
    }
  });
}

const selectGame = (platform, game) => {
  const { leagueId, eventId, timestamp, leagueName, teamHomeName, teamAwayName, selected, matchNumStr } = game;
  if (selected) {
    currentRelation[platform] = null;
  }
  else {
    currentRelation[platform] = { leagueId, eventId, timestamp, leagueName, teamHomeName, teamAwayName, matchNumStr };
  }
  if (platform == 'jc') {
    currentRelation.ps = null;
    currentRelation.ob = null;
    if (selected) {
      selectedInfo.value = null;
    }
    else {
      selectedInfo.value = {
        t: timestamp,
        l: leagueName,
        h: teamHomeName,
        a: teamAwayName,
      }
    }
  }
}

onMounted(() => {
  updateGamesList();
  updateGamesRelations();
});
</script>

<template>

  <div class="relation-container">
    <div class="top-panel" ref="topPanel">
      <span>竞彩</span>
      <span>平博</span>
      <span>OB</span>
      <i>{{ relationsList.length }}</i>
    </div>
    <div class="match-list" v-if="relationsList.length">
      <div class="match-row" v-for="({ id, rel }) in relationsList" :key="id">
        <MatchItem
          :eventId="rel.jc.eventId"
          :leagueName="rel.jc.leagueName"
          :teamHomeName="rel.jc.teamHomeName"
          :teamAwayName="rel.jc.teamAwayName"
          :dateTime="rel.jc.dateTime"
          :matchNumStr="rel.jc.matchNumStr" />
        <MatchItem  v-if="rel.ps"
          :eventId="rel.ps.eventId"
          :leagueName="rel.ps.leagueName"
          :teamHomeName="rel.ps.teamHomeName"
          :teamAwayName="rel.ps.teamAwayName"
          :dateTime="rel.ps.dateTime" />
        <div class="match-item match-item-holder" v-else></div>
        <MatchItem v-if="rel.ob"
          :eventId="rel.ob.eventId"
          :leagueName="rel.ob.leagueName"
          :teamHomeName="rel.ob.teamHomeName"
          :teamAwayName="rel.ob.teamAwayName"
          :dateTime="rel.ob.dateTime" />
        <div class="match-item match-item-holder" v-else></div>
        <div class="match-action">
          <Button type="link" class="action-btn" @click="removeGamesRelation(id)">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>
          </Button>
        </div>
      </div>
    </div>
    <div class="match-list col-list" v-if="jcGamesList.length">
      <div class="match-col">
        <MatchItem v-for="game in jcGamesList" :key="game.id"
          :eventId="game.eventId"
          :leagueName="game.leagueName"
          :teamHomeName="game.teamHomeName"
          :teamAwayName="game.teamAwayName"
          :dateTime="game.dateTime"
          :matchNumStr="game.matchNumStr"
          :selected="game.selected"
          @click="selectGame('jc', game)" />
      </div>
      <div class="match-col">
        <MatchItem v-for="game in psGamesList" :key="game.id"
          :eventId="game.eventId"
          :leagueName="game.leagueName"
          :teamHomeName="game.teamHomeName"
          :teamAwayName="game.teamAwayName"
          :dateTime="game.dateTime"
          :selected="game.selected"
          @click="selectGame('ps', game)" />
      </div>
      <div class="match-col">
        <MatchItem v-for="game in obGamesList" :key="game.id"
          :eventId="game.eventId"
          :leagueName="game.leagueName"
          :teamHomeName="game.teamHomeName"
          :teamAwayName="game.teamAwayName"
          :dateTime="game.dateTime"
          :selected="game.selected"
          @click="selectGame('ob', game)" />
      </div>
      <div class="match-action">
        <Button type="link" class="action-btn" v-if="showRelationButton" @click="setGamesRelation">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg>
        </Button>
      </div>
    </div>
    <div class="list-empty" v-if="!relationsList.length && !jcGamesList.length">暂无数据</div>
  </div>

</template>

<style lang="scss" scoped>
.relation-container {
  padding: 10px;
}

.top-panel {
  display: flex;
  margin-bottom: 5px;
  border: 1px solid hsl(var(--border));
  border-radius: 6px;
  background-color: hsl(var(--card));
  span, i {
    display: block;
  }
  span {
    flex: 1;
    text-align: center;
    &:not(:last-child) {
      border-right: 1px solid hsl(var(--border));
    }
  }
  i {
    width: 50px;
    text-align: center;
    font-style: normal;
  }
}

.match-list {
  margin-bottom: 5px;
  border: 1px solid hsl(var(--border));
  border-radius: 6px;
  background-color: hsl(var(--card));
  overflow: hidden;
  &.col-list {
    display: flex;
  }
}

.match-row {
  display: flex;
  flex-wrap: wrap;
  &:not(:last-child) {
    border-bottom: 1px solid hsl(var(--border));
  }
  .match-item {
    &:not(:last-child) {
      border-right: 1px solid hsl(var(--border));
    }
  }
}

.match-col {
  flex: 1;
  &:not(:last-child) {
    border-right: 1px solid hsl(var(--border));
  }
  .match-item {
    border-bottom: 1px solid hsl(var(--border));
    &:last-child {
      margin-bottom: -1px;
    }
  }
}

.match-item-holder {
  flex: 1;
  padding: 10px 15px;
}

.match-action {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
}

.action-btn {
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: hsl(var(--foreground) / 0.7);
  &:hover {
    color: hsl(var(--foreground));
  }
  .col-list & {
    position: relative;
    top: 40px;
    align-self: flex-start;
  }
  svg {
    width: 16px;
    height: 16px;
  }
}

.list-empty {
  text-align: center;
  padding: 10px;
  font-size: 18px;
  color: hsl(var(--foreground) / 0.7);
}

@media (max-width: 768px) {
  .match-item {
    min-width: calc(50% - 16px);
  }
}

@media (max-width: 480px) {
  .match-item {
    min-width: calc(100% - 16px);
  }
}
</style>
