<template>
  <component
    is="a-modal"
    :width="tool.getDevice() === 'mobile' ? '100%' : '600px'"
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :ok-loading="loading"
    @cancel="close"
    @before-ok="submit">
    <!-- 表单信息 start -->
    <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
      <a-form-item label="分组名" field="name">
        <a-input v-model="formData.name" placeholder="请输入分组名" />
      </a-form-item>
      <a-form-item label="游戏列表" field="game_list">
        <a-tree-select
          v-model="formData.game_list"
          :data="gameOptions"
          tree-checked-strategy="child"
          :tree-checkable="true"
          :max-tag-count="2"
          :fieldNames="{ title: 'name', key: 'id' }"
          allow-search
          allow-clear
          placeholder="请选择游戏列表" />
      </a-form-item>
      <a-form-item label="排序" field="sort">
        <a-input v-model="formData.sort" placeholder="请输入排序" />
      </a-form-item>
    </a-form>
    <!-- 表单信息 end -->
  </component>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import tool from '@/utils/tool'
import { Message, Modal } from '@arco-design/web-vue'
import api from '../../api/center/gameGroup'
import commonApi from '../../api/common'

const emit = defineEmits(['success'])
// 引用定义
const visible = ref(false)
const loading = ref(false)
const formRef = ref()
const mode = ref('')
const gameOptions = ref([])

let title = computed(() => {
  return '游戏分组' + (mode.value == 'add' ? '-新增' : '-编辑')
})

// 表单初始值
const initialFormData = {
  id: null,
  name: '',
  game_list: '',
  sort: null,
}

// 表单信息
const formData = reactive({ ...initialFormData })

// 验证规则
const rules = {
  name: [{ required: true, message: '分组名必需填写' }],
}

// 打开弹框
const open = async (type = 'add') => {
  mode.value = type
  // 重置表单数据
  Object.assign(formData, initialFormData)
  formRef.value.clearValidate()
  visible.value = true
  await initPage()
}

// 初始化页面数据
const initPage = async () => {
  if (mode.value == 'add') {
    await getGameListOptionsByGroupApi()
  }
}

// 新增显示的游戏列表
const getGameListOptionsByGroupApi = async (params) => {
  const resp = await commonApi.getGameListOptionsByGroupApi(params)
  if (resp.code === 200) {
    gameOptions.value = resp.data
  }
}

// 设置数据
const setFormData = async (data) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      formData[key] = data[key]
      if (key === 'game_list') {
        formData[key] = data[key].split(',').map(Number)
      }
    }
  }
  await getGameListOptionsByGroupApi({ game_group_id: data.id })
}

// 数据保存
const submit = async (done) => {
  const validate = await formRef.value?.validate()
  if (!validate) {
    loading.value = true
    let data = { ...formData }
    let result = {}
    if (mode.value === 'add') {
      // 添加数据
      data.id = undefined
      data.game_list = data.game_list.join(',')
      result = await api.save(data)
    } else {
      // 修改数据
      data.game_list = data.game_list.join(',')
      result = await api.update(data.id, data)
    }
    if (result.code === 200) {
      Message.success('操作成功')
      emit('success')
      done(true)
    }
    // 防止连续点击提交
    setTimeout(() => {
      loading.value = false
    }, 500)
  }
  done(false)
}

// 关闭弹窗
const close = () => (visible.value = false)

defineExpose({ open, setFormData })
</script>
