<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 { ElMessage } from "element-plus";
import { formatError } from "@/utils/utils.ts";
import _ from "lodash";
import YlActionDiv from "@/components/yl-action-div.vue";

const router = useRouter();

const { data: rooms, run } = useRequest(() => myRequest(`/api/backgammon`), {
  pollingInterval: 3000,
});
const { runAsync: addRoom } = useRequest(
  () => myRequest(`/api/backgammon`, userinfo.token, {}, "post"),
  { manual: true },
);

const toRoom = (id: number) => {
  router.push(`/backgammon/${id}`);
};

const onAdd = () => {
  addRoom()
    .then(() => run())
    .catch((res) => ElMessage.error(formatError(res)));
};
</script>

<template>
  <yl-action-div>
    <el-button link @click="onAdd">新建房间</el-button>
  </yl-action-div>
  <div class="rooms">
    <div
      v-for="room in _.get(rooms, 'data', []) as roomStatus[]"
      class="roomDiv"
    >
      <div class="status" @click="() => toRoom(room.room_id as number)">
        {{ room.player.split(",")[0] }}<span> vs </span
        >{{ room.player.split(",")[1] }}
      </div>
    </div>
  </div>
</template>

<style scoped>
.roomDiv {
  display: inline-block;
  width: 30%;
  margin: 2rem;
  height: 8rem;
  background: #eaeaea;
}

.roomDiv:hover {
  cursor: pointer;
}

.status {
  text-align: center;
  font-size: 2rem;
  padding-top: 2rem;
  color: #ff79ce;
}
</style>
