<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
import { ref, watch } from "vue";
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 pawns =
  "車馬相仕帥仕相馬車炮炮兵兵兵兵兵車馬象士将士象馬車砲砲卒卒卒卒卒";
const route = useRoute();
const router = useRouter();
const current = ref("");
const { data, run } = useRequest(
  () => myRequest(`/api/chess/${route.params.id}`),
  {
    pollingInterval: 1000,
  },
);
const { runAsync: join } = useRequest(
  () => myRequest(`/api/chess/${route.params.id}`, userinfo.token, {}, "post"),
  { manual: true },
);
const { runAsync: leave } = useRequest(
  () =>
    myRequest(`/api/chess/${route.params.id}`, userinfo.token, {}, "delete"),
  { manual: true },
);
const { runAsync: reset } = useRequest(
  () =>
    myRequest(`/api/chess/${route.params.id}/reset`, userinfo.token, {}, "get"),
  { manual: true },
);
const { runAsync: update } = useRequest(
  (to: string) =>
    myRequest(
      `/api/chess/${route.params.id}?pawn=${current.value}&des=${to}`,
      userinfo.token,
      {},
      "put",
    ),
  { manual: true },
);
const { runAsync: addAi } = useRequest(
  () =>
    myRequest(`/api/chess/${route.params.id}/ai`, userinfo.token, {}, "post"),
  { manual: true },
);
const { runAsync: getAiStep } = useRequest(
  () =>
    myRequest(`/api/chess/${route.params.id}/ai`, userinfo.token, {}, "put"),
  { manual: true },
);
const status = ref<string[]>([]);

const leaveRoom = () => {
  if (
    _.get(data, "value.data.players", "")
      .split(",")
      .indexOf(userinfo.username) !== -1
  ) {
    leave()
      .then((res) => {
        if ((_.get(res, "code", 0) as number) === 200) {
          router.back();
        }
      })
      .catch((res) => ElMessage.error(formatError(res)));
  } else {
    router.back();
  }
};
const joinRoom = () => {
  join()
    .then((res) => {
      if ((_.get(res, "code", 0) as number) === 200) {
        run();
      }
    })
    .catch((res) => ElMessage.error(formatError(res)));
};
const resetRoom = () => {
  reset()
    .then((res) => {
      if ((_.get(res, "code", 0) as number) === 200) {
        run();
      }
    })
    .catch((res) => ElMessage.error(formatError(res)));
};
const updatePawn = (i: number, j: number) => {
  (_.get(data, "value.data.players", "").split(",")[0] === userinfo.username
    ? update(`${9 - i},${j}`)
    : update(`${i},${j}`)
  )
    .then((res) => {
      if ((_.get(res, "code", 0) as number) === 200) {
        current.value = "";
        run();
        if (
          _.get(data, "value.data.players", "").split(",")[1] ===
          "ai--" + route.params.id
        ) {
          getAiStep()
            .then((r) => {
              if ((_.get(r, "code", 0) as number) === 200) {
                run();
              }
            })
            .catch((r) => ElMessage.error(formatError(r)));
        }
      }
    })
    .catch((res) => ElMessage.error(formatError(res)));
};
const addChessAi = () => {
  addAi()
    .then((res) => {
      if ((_.get(res, "code", 0) as number) === 200) {
        run();
      }
    })
    .catch((res) => ElMessage.error(formatError(res)));
};

watch(data, () => {
  status.value =
    _.get(data, "value.data.players", "").split(",")[0] === userinfo.username
      ? _.get(data, "value.data.status", "").split(";").reverse()
      : _.get(data, "value.data.status", "").split(";");
});
watch(
  () => _.get(data, "value.data.current", ""),
  () => (current.value = ""),
);
</script>

<template>
  <yl-action-div>
    <el-button link @click="leaveRoom">退出房间</el-button>
    <el-button
      v-if="
        _.get(data, 'data.players', '')
          .split(',')
          .indexOf(userinfo.username) === -1
      "
      link
      @click="joinRoom"
      >加入房间
    </el-button>
    <el-button
      v-if="_.get(data, 'data.players', '').split(',')[0] === userinfo.username"
      link
      @click="resetRoom"
      >重置房间
    </el-button>
    <el-button
      v-if="_.get(data, 'data.players', '') === userinfo.username"
      link
      @click="addChessAi"
      >添加机器人
    </el-button>
  </yl-action-div>
  <div v-if="_.get(data, 'data.winner', '')" class="winner">
    winner: {{ _.get(data, "data.winner", "") }}
  </div>
  <div class="flex around" style="padding-top: 20px">
    <div
      :class="{
        current:
          _.get(data, 'data.current', '') ===
          _.get(data, 'data.players', '').split(',')[0],
      }"
      class="red player"
    >
      {{ _.get(data, "data.players", "").split(",")[0] || "" }}
    </div>
    <div class="chess-div">
      <div v-for="(row, i) in status" class="flex around">
        <div
          v-for="(col, j) in row.split(',')"
          class="pawn-div"
          @click="
            () =>
              current !== '-1' && current !== '' && current !== col
                ? updatePawn(i, j)
                : current === col ||
                    (Number(col) > 15 &&
                      _.get(data, 'data.players', '').split(',')[0] ===
                        userinfo.username) ||
                    (Number(col) < 16 &&
                      _.get(data, 'data.players', '').split(',')[1] ===
                        userinfo.username)
                  ? (current = '')
                  : (current = col)
          "
        >
          <div
            :class="{
              pawn: col !== '-1',
              red: Number(col) < 16,
              black: Number(col) > 15,
              selected: col === current,
            }"
          >
            {{ col !== "-1" ? pawns[Number(col)] : "" }}
          </div>
        </div>
      </div>
    </div>
    <div
      :class="{
        current:
          _.get(data, 'data.current', '') ===
          _.get(data, 'data.players', '').split(',')[1],
      }"
      class="black player"
    >
      {{ _.get(data, "data.players", "").split(",")[1] || "" }}
    </div>
  </div>
</template>

<style scoped>
.chess-div {
  height: 700px;
  width: 604px;
  border: #2dcca7 1px solid;
  background: #cc6aa510 url("/src/assets/image/chess.webp") no-repeat;
  background-size: 100% 100%;
  padding: 0 0;
}

.pawn-div {
  margin: 10px 9px;
  width: 50px;
  height: 50px;
  box-sizing: border-box;
  line-height: 45px;
  font-family: "楷体", serif;
  font-size: 35px;
  text-align: center;
  z-index: 10;
}

.pawn {
  width: 100%;
  height: 100%;
  border-radius: 60px;
  border: #f0c237 double 1px;
  box-shadow: -5px 5px 5px #f0c237ee;
  background-color: #f6e3a8ee;
  cursor: pointer;
}

.player {
  font-size: 2rem;
}

.red {
  color: #ff0000aa;
}

.black {
  color: #000000aa;
}

.selected {
  background-color: aquamarine;
}

.current {
  border: dotted 1px #b78eff;
}

.winner {
  text-align: center;
  color: #108ee9;
  font-size: 1.5rem;
  font-weight: bolder;
}
</style>
