<script setup lang="ts">
import { useRouter } from "vue-router";
import { useRequest } from "vue-request";
import { myRequest } from "@/requests/request.ts";
import { userinfo } from "@/store/store.ts";
import _ from "lodash";
import YlActionDiv from "@/components/yl-action-div.vue";

const router = useRouter();
const { data: rooms, run: refresh } = useRequest(
  () => myRequest(`/api/chess`),
  { pollingInterval: 1000 },
);
const { runAsync: newRoom } = useRequest(
  () => myRequest(`/api/chess`, userinfo.token, {}, "post"),
  { manual: true },
);

const createRoom = () => {
  newRoom().then((res) => {
    if (_.get(res, "code", 0) === 200) {
      refresh();
      router.push(`/chess/${_.get(res, "data", "")}`);
    }
  });
};
</script>

<template>
  <yl-action-div>
    <el-button link @click="refresh">刷新</el-button>
    <el-button link @click="createRoom">新建房间</el-button>
  </yl-action-div>
  <div class="rooms">
    <div
      v-for="item in _.get(rooms, 'data', []) as chess[]"
      class="room"
      @click="router.push(`/chess/${item.ID}`)"
    >
      <div>no.{{ item.ID }}</div>
      <div class="players flex around">
        <span>{{ item.players?.split(",")[0] || "-" }}</span> vs
        <span>{{ item.players?.split(",")[1] || "-" }}</span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.room {
  width: 20%;
  display: inline-block;
  margin: 1rem;
  border-radius: 1rem;
  background-color: #2dcca729;
  text-align: center;
  height: 5rem;
  padding: 0.5rem;
  cursor: pointer;
}

.players {
  font-size: 1.5rem;

  span:first-child {
    color: #ff0000aa;
  }

  span:last-child {
    color: #000000aa;
  }
}
</style>
