<script setup>
import { onMounted, ref, computed } from "vue"
import { is_empty, checkWin, is_black, is_white, robotPlay } from "./utils"
// import { robotPlay } from './utils/api'
// 配置
const size = ref(20)
const win_size = ref(5)
// 棋盘
const lattices = ref([])
// 下起记录
const records = ref([])
// 5 连珠的下标
let isWin = []
const records_obj = computed(() => {
  return records.value.reduce((r, { location, type }) => {
    const [y, x] = location || []
    const _win = isWin.map(([r, c]) => `${r}_${c}`).includes(`${y}_${x}`)
    return {
      ...r,
      [`${y}_${x}`]: _win ? 'isWin' : type
    }
  }, {})
})

onMounted(confirm)

function confirm() {
  isWin = []
  lattices.value = Array(size.value).fill([]).map(() => Array(size.value).fill(is_empty))
  records.value = []
}
function back() {
  if (records.value.length < 2) return;
  for (let i = 0; i < 2; i++) {
    const { location: [y, x], type } = records.value.pop()
    lattices.value[y][x] = is_empty
    // 如果是玩家赢了，只需要退回一步就行
    if(type === is_black){
      break;
    }
  }
  isWin = []
}

function setPiece([y, x], type) {
  records.value.push({
    location: [y, x],
    type: type
  })
  lattices.value[y][x] = type
}
async function playChess(item, row, col) {
  if (isWin.length || item !== is_empty) return

  // 玩家下棋
  setPiece([row, col], is_black)
  const test = checkWin({ row, col, board: lattices.value, player: is_black, win_size: win_size.value })
  if (test) {
    isWin = test
    return
  }
  // 机器人下棋
  const [y, x] = robotPlay(lattices.value, is_white, win_size.value)

  setPiece([y, x], is_white)
  const testRobo = checkWin({ row: y, col: x, board: lattices.value, player: is_white, win_size: win_size.value })
  if (testRobo) {
    isWin = testRobo
  }
}
</script>

<template>
  <div class="content flex-start">
    <p class="flex-between mr-6px">
      <label for="size" class="space-nowrap">棋盘大小：</label>
      <input v-model="size" id="size" type="number">
    </p>
    <p class="flex-between mr-6px">
      <label for="win_size" class="space-nowrap">胜利棋数：</label>
      <input v-model="win_size" id="win_size" type="number" min="3" max="8">
    </p>
    <button @click="confirm" class="space-nowrap mr-6px">重新开始</button>
    <button @click="back" class="space-nowrap">返回上一步</button>
  </div>
  <div class="content border-top content-lattice">
    <p class="row" v-for="(lattice, r_i) in lattices" :key="r_i">
    <p class="col" :class="records_obj[`${r_i}_${c_i}`]" v-for="(item, c_i) in lattice" :key="`${r_i}-${c_i}`"
      @click="playChess(item, r_i, c_i)">
    </p>
    </p>
  </div>
</template>

