<template>
  <a-modal :unmount-on-close="true" v-model:visible="visible" width="600px" @close="handleClose" @ok="handleOk">
    <template #title>{{ comType === 'natural' ? '自然量' : '游戏' }}数据权限设置</template>
    <div>
      <game-permission ref="gamePermissionRef" :comType="comType" />
    </div>
  </a-modal>
</template>
<script setup>
import { ref, computed } from 'vue'
import api from '@/api/center/game'
import userApi from '@/api/system/user'
import commonApi from '@/views/v1/api/common'
import GamePermission from '@/components/game-permission/index.vue'
import { Message } from '@arco-design/web-vue'
const emit = defineEmits(['success'])

const visible = ref(false)
const adPermission = ref(0)
const gamePermissionRef = ref()
const deptId = ref(0)
const id = ref(0)
const comType = ref('natural')
const checkedGameList = ref('')
const formData = ref({})

const handleClose = () => {
  visible.value = false
}

const handleOk = async () => {
  let { selectType, checkedKeys } = await gamePermissionRef.value.getGamePermissionData()
  console.log(selectType, checkedKeys)
  let type = comType.value === 'natural' ? 'normal_game_list' : 'game_list'
  let data = {
    [type]: selectType !== '0' ? selectType : checkedKeys.join(','),
  }
  // 更新用户数据
  const result = await userApi.setUserPermission({
    id: formData.value.id,
    ...data,
  })

  if (result.code === 200) {
    Message.success('操作成功')
    emit('success')
  }
}

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

  formData.value = rowData
  deptId.value = rowData.dept_id
  checkedGameList.value = type === 'natural' ? rowData.normal_game_list : rowData.game_list
  comType.value = type

  visible.value = true

  await initPage()
}

// 根据部门ID获取游戏列表数据
const getGameListByDeptId = async () => {
  const resp = await commonApi.getGameListByDeptIdApi({
    dept_id: deptId.value,
  })
  let gameList = JSON.parse(JSON.stringify(resp.data))
  gamePermissionRef.value.init(gameList, checkedGameList.value)
}

const initPage = async () => {
  await getGameListByDeptId()
}

defineExpose({ open })
</script>
