<template>
  <a-modal :unmount-on-close="true" v-model:visible="visible" width="600px" @close="handleClose" @ok="handleOk">
    <template #title>部门游戏权限设置</template>
    <game-permission ref="gamePermissionRef" :comType="'game'" />
  </a-modal>
</template>

<script setup>
import { ref, computed } from 'vue'
import commonApi from '@/views/v1/api/common'
import api from '@/api/center/game'

import GamePermission from '@/components/game-permission/index.vue'

const emit = defineEmits(['success'])

const visible = ref(false)
const deptId = ref()
const gamePermissionRef = ref()
const checkedGameList = ref('')

// 打开弹框
const open = async (row) => {
  let rowData = JSON.parse(JSON.stringify(row))

  deptId.value = rowData.id
  checkedGameList.value = rowData.game_list

  visible.value = true

  await initPage()
}

// 获取所有的游戏数据
const getAllGameData = async () => {
  const resp = await commonApi.getGameOptionsNoAuthApi()
  let allGameData = JSON.parse(JSON.stringify(resp.data))
  gamePermissionRef.value.init(allGameData, checkedGameList.value)
}

// 初始化页面数据
const initPage = async () => {
  await getAllGameData()
}

// 设置部门游戏权限
const setGameListByDeptId = async () => {
  let { selectType, checkedKeys } = await gamePermissionRef.value.getGamePermissionData()
  try {
    const resp = await api.setGameListByDeptId({
      dept_id: deptId.value,
      game_list: selectType === '*' ? '*' : checkedKeys.join(','),
    })
  } catch (error) {
    Message.error('设置部门游戏权限失败')
    console.error('设置部门游戏权限失败:', error)
  }
}

const handleClose = async () => {
  emit('success', true)
}

const handleOk = async () => {
  setGameListByDeptId()
}

defineExpose({ open })
</script>
