<script setup lang="ts">
import { useRoute, 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 { ElMessage } from "element-plus";
import { formatError } from "@/utils/utils.ts";
import YlActionDiv from "@/components/yl-action-div.vue";

const route = useRoute();
const router = useRouter();
const { data: roomStatus, run } = useRequest(
  () => myRequest(`/api/backgammon/${_.get(route, "params.id", "")}`),
  { pollingInterval: 1000, refreshOnWindowFocus: true },
);

const { runAsync: joinRoom } = useRequest(
  () =>
    myRequest(
      `/api/backgammon/${_.get(route, "params.id", "")}`,
      userinfo.token,
      {},
      "put",
    ),
  { manual: true },
);

const { runAsync: addPawn } = useRequest(
  (p: string) =>
    myRequest(
      `/api/backgammon/${_.get(route, "params.id", "")}?place=${p}`,
      userinfo.token,
      {},
      "post",
    ),
  { manual: true },
);

const { runAsync: leaveRoom } = useRequest(
  () =>
    myRequest(
      `/api/backgammon/${_.get(route, "params.id", "")}`,
      userinfo.token,
      {},
      "delete",
    ),
  { manual: true },
);

const add = (x: number, y: number) => {
  if (_.get(roomStatus, "value.data.winner", "")) {
    ElMessage.error("对局已结束");
    return;
  }
  addPawn(`${x},${y}`)
    .then(() => run())
    .catch((res) => ElMessage.error(formatError(res)));
};

const toJoin = () => {
  joinRoom()
    .then()
    .catch((res) => ElMessage.error(formatError(res)));
};

const toLeave = () => {
  leaveRoom()
    .then(() => {})
    .catch((res) => ElMessage.error(formatError(res)));
  router.back();
};
</script>

<template>
  <yl-action-div>
    <el-button link @click="toLeave">退出</el-button>
    <el-button
      v-if="_.get(roomStatus, 'data.player', '').split(',').length < 2"
      link
      @click="toJoin"
      >加入对战
    </el-button>
    <div v-if="_.get(roomStatus, 'data.winner', '')" class="winner">
      winner:{{ _.get(roomStatus, "data.winner", "") }}
    </div>
  </yl-action-div>
  <div class="gameDiv">
    <div class="player">
      {{ _.get(roomStatus, "data.player", "").split(",")[0] }}
    </div>
    <div class="canvas">
      <div
        v-for="(row, col) in _.get(roomStatus, 'data.pawn_status', '').split(
          ';',
        )"
        class="flex between"
      >
        <div
          v-for="(item, index) in row.split(',')"
          :class="{ black: item === '1', white: item === '-1' }"
          style="width: 50px; height: 50px"
          @click="() => add(col, index)"
        ></div>
      </div>
    </div>
    <div class="player">
      {{ _.get(roomStatus, "data.player", "").split(",")[1] }}
    </div>
  </div>
</template>

<style scoped>
.gameDiv {
  height: 90%;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.black {
  background: url("/src/assets/image/black.png") no-repeat;
  background-size: 100% 100%;
}

.white {
  background: url("/src/assets/image/white.png") no-repeat;
  background-size: 100% 100%;
}

.canvas {
  background: url("/src/assets/image/background.jpg") no-repeat;
  background-size: 100% 100%;
  font-size: 1px;
  width: 750px;
  height: 750px;
  border: 1px solid #eaeaea;
}

.winner {
  text-align: center;
  font-weight: bolder;
  font-size: 20px;
  color: #108ee9;
}

.player {
  font-weight: bolder;
  font-size: 18px;
  color: #ff79ce;
}
</style>
