<template>
  <a-modal :unmount-on-close="true" v-model:visible="visible" width="600px" @close="handleClose" @ok="handleOk">
    <template #title>数据权限设置</template>
    <a-form :form="formData" auto-label-width>
      <a-form-item label="数据权限">
        <a-radio-group type="button" v-model="formData.data_permission">
          <a-radio :value="0">全部人员及自然量</a-radio>
          <a-radio :value="1">自定义</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="广告数据权限" v-show="formData.data_permission === 1">
        <a-radio-group type="button" v-model="formData.ad_permission">
          <a-radio :value="1">仅本人</a-radio>
          <a-radio :value="2">本人及所属团队成员</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="自然量游戏权限" v-show="formData.data_permission === 1">
        <game-permission ref="gamePermissionRef" :comType="comType" />
      </a-form-item>
    </a-form>
  </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()

  let type = 'normal_game_list'
  let data = {
    [type]: selectType !== '0' ? selectType : checkedKeys.join(','),
  }
  // 更新用户数据
  const result = await userApi.setUserPermission({
    id: formData.value.id,
    data_permission: formData.value.data_permission,
    ad_permission: formData.value.ad_permission,
    ...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 = rowData.normal_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>
