<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="game_id">
        <a-tree-select
          v-model="formData.game_id"
          :data="gameOptions"
          tree-checked-strategy="child"
          :tree-checkable="false"
          :max-tag-count="2"
          :fieldNames="{ title: 'name', key: 'id' }"
          allow-search
          allow-clear
          @change="handleGameChange"
          placeholder="请选择游戏">
        </a-tree-select>
      </a-form-item>
      <a-form-item label="所属媒体" field="media_id">
        <a-select v-model="formData.media_id" placeholder="请选择媒体ID" allow-clear @change="handleMediaChange">
          <a-option v-for="item in mediaOptions" :key="item.id" :value="item.id" :label="`${item.id}:${item.name}`" />
        </a-select>
      </a-form-item>
      <a-form-item label="母包名称" field="name">
        <a-input v-model="formData.name" placeholder="请输入母包名称" />
        <template #extra>
          <div>格式：游戏名(媒体名)</div>
        </template>
      </a-form-item>

      <a-form-item label="打包目录" field="letter">
        <a-input v-model="formData.letter" placeholder="请输入打包目录" />
        <template #extra>
          <div>格式：gamejrtt</div>
        </template>
      </a-form-item>
      <a-form-item label="母包包名" field="package_name">
        <a-input v-model="formData.package_name" placeholder="请输入母包包名com.xxx" />
        <template #extra>
          <div>格式：com.gamegame.game.jrtt</div>
        </template>
      </a-form-item>

      <div v-if="formData.media_id == 1">
        <a-divider orientation="center">头条</a-divider>
        <a-form-item label="媒体APPID" field="tt_appid">
          <a-input v-model="formData.tt_appid" placeholder="请输入媒体APPID" />
        </a-form-item>
        <a-form-item label="母包ID" field="tt_package_id">
          <a-input v-model="formData.tt_package_id" placeholder="请输入母包ID" />
        </a-form-item>
        <a-form-item label="账号ID" field="tt_advertiser_id">
          <a-input v-model="formData.tt_advertiser_id" placeholder="请输入账号ID" />
        </a-form-item>
      </div>
    </a-form>
    <!-- 表单信息 end -->
  </component>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import tool from '@/utils/tool'
import { Message } from '@arco-design/web-vue'
import api from '../../api/advert/gamePackage'
import advertCommonApi from '../../api/advert/common'
import commonApi from '../../api/common'
import v1CommonApi from '@/views/v1/api/common'
import GameSelect from '@/components/game-select/index.vue'

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

let title = computed(() => {
  return '母包管理' + (mode.value == 'add' ? '-新增' : '-编辑')
})

// 表单初始值
const initialFormData = {
  id: null,
  media_id: 1,
  game_id: null,
  name: '',
  package_name: '',
  letter: '',
  tt_appid: '',
  tt_package_id: '',
  tt_advertiser_id: '',
}

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

// 验证规则
const rules = {
  media_id: [{ required: true, message: '媒体ID必需填写' }],
  game_id: [{ required: true, message: '游戏ID必需填写' }],
  name: [{ required: true, message: '母包名称必需填写' }],
  package_name: [{ required: true, message: '母包包名com.xxx必需填写' }],
  tt_appid: [{ required: true, message: '媒体APPID必需填写' }],
}

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

// 根据游戏ID， 获取游戏名和母包名

const findGameById = (options, id) => {
  for (const item of options) {
    if (item.id === id) {
      return item
    }
    if (item.children && item.children.length > 0) {
      const found = findGameById(item.children, id)
      if (found) return found
    }
  }
  return null
}

// 游戏ID改变
const handleGameChange = (value) => {
  console.log(value)

  if (value) {
    const gameItem = findGameById(gameOptions.value, value)
    const media = mediaOptions.value.find((item) => item.id === formData.media_id)

    if (media) {
      gameName.value = gameItem.name.split(':')[1]
      formData.name = `${gameItem.name.split(':')[1]}(${media.name})`
    } else {
      formData.name = gameItem.name.split(':')[1]
    }
    formData.package_name = gameItem.name.split(':')[2]
  }
}

// 媒体ID改变
const handleMediaChange = (value) => {
  if (value) {
    const media = mediaOptions.value.find((item) => item.id === value)
    if (media) {
      formData.name = `${gameName.value}(${media.name})`
    } else {
      formData.name = gameName.value
    }
  }
}

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

// 获取媒体列表Options
const getMediaOptions = async () => {
  const res = await advertCommonApi.getMediaOptionsApi()
  if (res.code == 200) {
    mediaOptions.value = res.data
  }
}

// // 获取游戏列表
const getGameOptions = async () => {
  const res = await v1CommonApi.getGameOptionsApi({ has_package: true })
  if (res.code == 200) {
    gameOptions.value = res.data
  }
}

// 设置数据
const setFormData = async (data) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      formData[key] = data[key]
    }
  }
}

// 数据保存
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
      result = await api.save(data)
    } else {
      // 修改数据
      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>
