<script setup>
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';
import api from '@/libs/api';

const search = ref('');
const leagues = ref(null);
const leaguesRelations = ref([]);
const selectedLeagues = reactive({
  polymarket: null,
  pinnacle: null,
});

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

const updateLeagues = () => {
  api.get('/api/games/get_leagues').then(res => {
    if (res.data.statusCode === 200) {
      leagues.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 selectLeague = (type, league) => {
  const { id, name } = league;
  const currentLeagues = { id, name };
  if (type === 'polymarket') {
    if (selectedLeagues.polymarket?.id === id) {
      selectedLeagues.polymarket = null;
    }
    else {
      selectedLeagues.polymarket = currentLeagues;
    }
  }
  else if (type === 'pinnacle') {
    if (selectedLeagues.pinnacle?.id === id) {
      selectedLeagues.pinnacle = null;
    }
    else {
      selectedLeagues.pinnacle = currentLeagues;
    }
  }
  else {
    throw new Error('invalid type');
  }
}

const resetSelectedLeagues = () => {
  selectedLeagues.polymarket = null;
  selectedLeagues.pinnacle = null;
}

const setLeaguesRelation = () => {
  if (!selectedLeagues.polymarket || !selectedLeagues.pinnacle) {
    message.error('请选择要添加的联赛');
    return;
  }
  const leagueRelation = {
    id: selectedLeagues.polymarket.id,
    platforms: selectedLeagues,
  };
  api.post('/api/games/set_leagues_relation', leagueRelation)
  .then(res => {
    if (res.data.statusCode === 200) {
      message.success('添加成功');
    }
    else {
      throw new Error(res.data.message);
    }
    refresh();
    resetSelectedLeagues();
  })
  .catch(err => {
    message.error(err.response?.data?.message ?? err.message);
    console.error(err);
  });
};

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

const getLeaguesRelations = () => {
  api.get('/api/games/get_leagues_relations')
  .then(res => {
    if (res.data.statusCode === 200) {
      leaguesRelations.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 = () => {
  updateLeagues();
  getLeaguesRelations();
}

const getLeagues = (platform) => {
  const searchValue = search.value.trim().toLowerCase();
  return leagues.value?.[platform].map(item => {
    const { id } = item;
    let selected = false;
    let disabeld = false;
    if (selectedLeagues[platform]?.id === id) {
      selected = true;
    }
    if (leaguesRelations.value.some(relation => relation.platforms[platform]?.id === id)) {
      disabeld = true;
    }
    return { ...item, selected, disabeld };
  }).filter(item => {
    const { name, localesName='', sport='' } = item;
    return !searchValue || name.toLowerCase().includes(searchValue) || localesName.toLowerCase().includes(searchValue) || sport.toLowerCase().includes(searchValue);
  }) ?? [];
}

const polymarketLeagues = computed(() => {
  return getLeagues('polymarket');
});

const pinnacleLeagues = computed(() => {
  return getLeagues('pinnacle');
});

const leaguesRelationsFiltered = computed(() => {
  const searchValue = search.value.trim().toLowerCase();
  return leaguesRelations.value.filter(item => {
    const { platforms: { polymarket, pinnacle } } = item;
    return !searchValue
    || polymarket.localesName?.toLowerCase().includes(searchValue)
    || polymarket.name?.toLowerCase().includes(searchValue)
    || pinnacle.name?.toLowerCase().includes(searchValue);
  }) ?? [];
});

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

onUnmounted(() => {
  // console.log('leagues 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="setLeaguesRelation">
        <template #icon>
          <plus-outlined />
        </template>
        添加
      </a-button>
    </template>
  </a-page-header>

  <div class="leagues-container">
    <div class="leagues-column polymarket">
      <h3>Polymarket 联赛 ({{ polymarketLeagues.length }})</h3>
      <a-list item-layout="horizontal" :data-source="polymarketLeagues" size="small">
        <template #renderItem="{ item }">
          <a-list-item :class="{ selected: item.selected, disabled: item.disabeld }" @click="!item.disabeld && selectLeague('polymarket', item)">
            {{ item.localesName }} <em>{{ item.name }} {{ item.sport ? `[${item.sport.toUpperCase()}]` : '' }}</em>
          </a-list-item>
        </template>
      </a-list>
    </div>
    <div class="leagues-column pinnacle">
      <h3>Pinnacle 联赛 ({{ pinnacleLeagues.length }})</h3>
      <a-list item-layout="horizontal" :data-source="pinnacleLeagues" size="small">
        <template #renderItem="{ item }">
          <a-list-item :class="{ selected: item.selected, disabled: item.disabeld }" @click="!item.disabeld && selectLeague('pinnacle', item)">
            {{ item.name }}
          </a-list-item>
        </template>
      </a-list>
    </div>
    <div class="leagues-column relations">
      <h3>已添加的联赛 ({{ leaguesRelationsFiltered.length }})</h3>
      <a-list item-layout="horizontal" :data-source="leaguesRelationsFiltered" size="small">
        <template #renderItem="{ item }">
          <a-list-item>
            <div class="league-name polymarket-name">{{ item.platforms.polymarket.localesName }} <em>{{ item.platforms.polymarket.name }}</em></div>
            <a-button class="remove-button" type="link" @click="removeLeaguesRelation(item)">
              <template #icon>
                <link-outlined />
                <disconnect-outlined />
              </template>
            </a-button>
            <div class="league-name pinnacle-name">{{ item.platforms.pinnacle.name }}</div>
          </a-list-item>
        </template>
      </a-list>
    </div>
  </div>

</template>

<style lang="scss" scoped>
.leagues-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);
}
.leagues-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;
  }
}
.leagues-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;
  }
  .league-name {
    flex: 1;
  }
  .pinnacle-name {
    text-align: right;
  }
  .remove-button {
    visibility: hidden;
    .anticon-disconnect {
      display: none;
    }
    &:hover {
      color: #f5222d;
      .anticon-link {
        display: none;
      }
      .anticon-disconnect {
        margin-inline-start: 0;
        display: inline-block;
      }
    }
  }
  em {
    font-style: normal;
    font-size: 12px;
  }
}
</style>
