<script setup>
import axios from 'axios';
import dayjs from 'dayjs';
import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue';
import { message } from 'ant-design-vue';
import { ReloadOutlined, PlusOutlined, LinkOutlined, DisconnectOutlined } from '@ant-design/icons-vue';

const search = ref('');
const games = ref(null);
const gamesRelations = ref([]);
const selectedGames = reactive({
  polymarket: null,
  pinnacle: null,
});

const onSearch = (value) => {
  search.value = value;
};

const updateGames = async () => {
  return axios.get('/api/games/get_games').then(res => {
    if (res.data.statusCode === 200) {
      games.value = res.data.data;
    }
    else {
      throw new Error(res.data.message);
    }
  })
  .catch(err => {
    message.error(err.response?.data?.message ?? err.message);
    console.error(err);
  });
};

const selectGame = (type, game) => {
  const { id, leagueId, leagueName, teamHomeName, teamAwayName, timestamp } = game;
  const currentGames = { id, leagueId, leagueName, teamHomeName, teamAwayName, timestamp };
  if (type === 'polymarket') {
    if (selectedGames.polymarket?.id === id) {
      selectedGames.polymarket = null;
    }
    else {
      selectedGames.polymarket = currentGames;
    }
  }
  else if (type === 'pinnacle') {
    if (selectedGames.pinnacle?.id === id) {
      selectedGames.pinnacle = null;
    }
    else {
      selectedGames.pinnacle = currentGames;
    }
  }
  else {
    throw new Error('invalid type');
  }
}

const resetSelectedGames = () => {
  selectedGames.polymarket = null;
  selectedGames.pinnacle = null;
}

const setGamesRelation = () => {
  if (!selectedGames.polymarket || !selectedGames.pinnacle) {
    message.error('请选择要添加的比赛');
    return;
  }
  const gameRelation = {
    id: selectedGames.polymarket.id,
    platforms: selectedGames,
    timestamp: selectedGames.polymarket.timestamp,
  };
  axios.post('/api/games/set_relation', gameRelation)
  .then(res => {
    if (res.data.statusCode === 200) {
      message.success('添加成功');
    }
    else {
      throw new Error(res.data.message);
    }
    resetSelectedGames();
    return refresh();
  })
  .then(() => {
    if (search.value.trim() && (!polymarketGames.value.length || !pinnacleGames.value.length)) {
      search.value = '';
    }
  })
  .catch(err => {
    message.error(err.response?.data?.message ?? err.message);
    console.error(err);
  });
};

const removeGamesRelation = (relation) => {
  axios.post('/api/games/remove_relation', { id: relation.id })
  .then(res => {
    if (res.data.statusCode === 200) {
      message.success('删除成功');
    }
    else {
      throw new Error(res.data.message);
    }
    return refresh();
  })
  .catch(err => {
    message.error(err.response?.data?.message ?? err.message);
    console.error(err);
  });
}

const updateGamesRelations = async () => {
  return axios.get('/api/games/get_relations')
  .then(res => {
    if (res.data.statusCode === 200) {
      gamesRelations.value = res.data.data;
    }
    else {
      throw new Error(res.data.message);
    }
  })
  .catch(err => {
    message.error(err.response?.data?.message ?? err.message);
    console.error(err);
  });
};

const refresh = async () => {
  return Promise.all([updateGames(), updateGamesRelations()]);
}

const getGames = (platform) => {
  const searchValue = search.value.trim().toLowerCase();
  return games.value?.[platform].map(item => {
    const { id, timestamp } = item;
    let selected = false;
    let disabeld = false;
    if (selectedGames[platform]?.id === id) {
      selected = true;
    }
    if (gamesRelations.value.some(relation => relation.platforms[platform]?.id === id)) {
      disabeld = true;
    }
    const dateTime = dayjs(timestamp).format('MM-DD HH:mm');
    return { ...item, selected, disabeld, dateTime };
  }).filter(item => {
    const { disabeld, leagueName, teamHomeName, teamAwayName, localesLeagueName, localesTeamHomeName, localesTeamAwayName } = item;
    return !disabeld && (!searchValue
      || leagueName?.toLowerCase().includes(searchValue)
      || localesLeagueName?.toLowerCase().includes(searchValue)
      || teamHomeName?.toLowerCase().includes(searchValue)
      || localesTeamHomeName?.toLowerCase().includes(searchValue)
      || teamAwayName?.toLowerCase().includes(searchValue)
      || localesTeamAwayName?.toLowerCase().includes(searchValue));
  }) ?? [];
}

const polymarketGames = computed(() => {
  return getGames('polymarket');
});

const pinnacleGames = computed(() => {
  return getGames('pinnacle');
});

const gamesRelationsFiltered = computed(() => {
  const searchValue = search.value.trim().toLowerCase();
  return gamesRelations.value.filter(item => {
    const { platforms: { polymarket, pinnacle } } = item;
    return !searchValue
    || polymarket.leagueName?.toLowerCase().includes(searchValue)
    || polymarket.localesLeagueName?.toLowerCase().includes(searchValue)
    || polymarket.teamHomeName?.toLowerCase().includes(searchValue)
    || polymarket.localesTeamHomeName?.toLowerCase().includes(searchValue)
    || polymarket.teamAwayName?.toLowerCase().includes(searchValue)
    || polymarket.localesTeamAwayName?.toLowerCase().includes(searchValue)
    || pinnacle.leagueName?.toLowerCase().includes(searchValue)
    || pinnacle.teamHomeName?.toLowerCase().includes(searchValue)
    || pinnacle.teamAwayName?.toLowerCase().includes(searchValue);
  }) ?? [];
});

onMounted(() => {
  // console.log('games mounted');
  refresh();
});

onUnmounted(() => {
  // console.log('games unmounted');
});

</script>

<template>
  <a-page-header title="比赛">
    <template #extra>
      <a-input-search
        v-model:value="search"
        placeholder="搜索"
        :allowClear="true"
        @search="onSearch"
      />
      <a-button @click="refresh">
        <template #icon>
          <reload-outlined />
        </template>
        刷新
      </a-button>
      <a-button type="primary" @click="setGamesRelation">
        <template #icon>
          <plus-outlined />
        </template>
        添加
      </a-button>
    </template>
  </a-page-header>

  <div class="games-container">
    <div class="games-column polymarket">
      <h3>Polymarket 比赛 ({{ polymarketGames.length }})</h3>
      <a-list item-layout="horizontal" :data-source="polymarketGames" size="small">
        <template #renderItem="{ item }">
          <a-list-item :class="{ selected: item.selected, disabled: item.disabeld }" @click="!item.disabeld && selectGame('polymarket', item)">
            <div class="game-info">
              <div class="game-league-name">{{ item.localesLeagueName }} <em>{{ item.leagueName }}</em></div>
              <div class="game-team-name home-team-name">{{ item.localesTeamHomeName }} <em>{{ item.teamHomeName }}</em></div>
              <div class="game-team-name away-team-name">{{ item.localesTeamAwayName }} <em>{{ item.teamAwayName }}</em></div>
            </div>
            <div class="game-date-time">{{ item.dateTime }}</div>
          </a-list-item>
        </template>
      </a-list>
    </div>
    <div class="games-column pinnacle">
      <h3>Pinnacle 比赛 ({{ pinnacleGames.length }})</h3>
      <a-list item-layout="horizontal" :data-source="pinnacleGames" size="small">
        <template #renderItem="{ item }">
          <a-list-item :class="{ selected: item.selected, disabled: item.disabeld }" @click="!item.disabeld && selectGame('pinnacle', item)">
            <div class="game-info">
              <div class="game-league-name">{{ item.leagueName }}</div>
              <div class="game-team-name home-team-name">{{ item.teamHomeName }}</div>
              <div class="game-team-name away-team-name">{{ item.teamAwayName }}</div>
            </div>
            <div class="game-date-time">{{ item.dateTime }}</div>
          </a-list-item>
        </template>
      </a-list>
    </div>
    <div class="games-column relations">
      <h3>已添加的比赛 ({{ gamesRelationsFiltered.length }})</h3>
      <a-list item-layout="horizontal" :data-source="gamesRelationsFiltered" size="small">
        <template #renderItem="{ item }">
          <a-list-item>
            <div class="game-info">
              <div class="game-league-name">{{ item.platforms.polymarket.leagueName }}</div>
              <div class="game-team-name home-team-name">{{ item.platforms.polymarket.teamHomeName }}</div>
              <div class="game-team-name away-team-name">{{ item.platforms.polymarket.teamAwayName }}</div>
            </div>
            <div class="game-info">
              <div class="game-league-name">{{ item.platforms.pinnacle?.leagueName }}</div>
              <div class="game-team-name home-team-name">{{ item.platforms.pinnacle?.teamHomeName }}</div>
              <div class="game-team-name away-team-name">{{ item.platforms.pinnacle?.teamAwayName }}</div>
            </div>
            <div class="game-info">
              <div class="game-league-name">{{ item.platforms.huangguan?.leagueName }}</div>
              <div class="game-team-name home-team-name">{{ item.platforms.huangguan?.teamHomeName }}</div>
              <div class="game-team-name away-team-name">{{ item.platforms.huangguan?.teamAwayName }}</div>
            </div>
            <div class="game-info">
              <div class="game-league-name">{{ item.platforms.obsports?.leagueName }}</div>
              <div class="game-team-name home-team-name">{{ item.platforms.obsports?.teamHomeName }}</div>
              <div class="game-team-name away-team-name">{{ item.platforms.obsports?.teamAwayName }}</div>
            </div>
            <a-button class="remove-button" type="link" @click="removeGamesRelation(item)">
              <template #icon>
                <link-outlined />
                <disconnect-outlined />
              </template>
            </a-button>
            <div class="game-date-time">{{ dayjs(item.timestamp).format('MM-DD HH:mm') }}</div>
          </a-list-item>
        </template>
      </a-list>
    </div>
  </div>

</template>

<style lang="scss" scoped>
.games-container {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: stretch;
  height: calc(100vh - 126px);
  padding: 15px;
  gap: 15px;
  border-top: 1px solid rgba(5, 5, 5, 0.06);
}
.games-column {
  overflow: auto;
  flex: 1;
  h3 {
    height: 39px;
    margin: 0;
    line-height: 39px;
    text-align: center;
    font-size: 14px;
    font-weight: 600;
    border: 1px solid rgba(5, 5, 5, 0.06);
    border-bottom: none;
    border-radius: 8px 8px 0 0;
    background-color: #fafafa;
  }
}
.games-column.relations {
  flex: 2.5;
  border-right: 0 none;
}
.ant-list {
  max-height: calc(100vh - 196px);
  overflow: auto;
  border: 1px solid rgba(5, 5, 5, 0.06);
  border-radius: 0 0 8px 8px;
}
.ant-list-item {
  &:hover {
    background-color: #fafafa;
    .remove-button {
      visibility: visible;
    }
  }
  &.selected {
    background-color: #e6f7ff;
  }
  &.disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
  .remove-button {
    visibility: hidden;
    .anticon-disconnect {
      display: none;
    }
    &:hover {
      color: #f5222d;
      .anticon-link {
        display: none;
      }
      .anticon-disconnect {
        margin-inline-start: 0;
        display: inline-block;
      }
    }
  }
}
.game-info {
  flex: 1;
  em {
    font-style: normal;
    font-size: 12px;
  }
}
.game-league-name {
  font-size: 16px;
}
.game-team-name {
  color: #666;
  &.home-team-name {
    color: rgb(0, 107, 230);
  }
  &.away-team-name {
    color: rgb(255, 56, 96);
  }
}
.game-date-time {
  color: #666;
}
</style>