<template>
  <div>
    <a-radio-group type="button" v-model="selectType">
      <a-radio value="-1" v-if="comType === 'natural'">不看自然量</a-radio>
      <a-radio value="*">全部游戏</a-radio>
      <a-radio value="0">指定游戏</a-radio>
    </a-radio-group>
    <div>
      <a-input-search
        v-if="selectType === '0'"
        style="margin-bottom: 8px; max-width: 240px"
        v-model="searchKey"
        placeholder="搜索游戏"
        class="m-2 ml-0" />
      <a-tree
        v-if="selectType === '0'"
        v-model:checkedKeys="checkedKeys"
        checkable
        checked-strategy="child"
        multiple
        :data="treeData"
        :field-names="{ children: 'children', title: 'title', key: 'key' }"
        @check="handleCheck">
        <template #title="nodeData">
          <template v-if="((index = getMatchIndex(nodeData?.title)), index < 0)">{{ nodeData?.title }}</template>
          <span v-else>
            {{ nodeData?.title?.substr(0, index) }}
            <span style="color: var(--color-primary-light-4)">
              {{ nodeData?.title?.substr(index, searchKey.length) }} </span
            >{{ nodeData?.title?.substr(index + searchKey.length) }}
          </span>
        </template>
      </a-tree>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
const searchKey = ref('')
defineProps({
  comType: {
    type: String,
    default: 'game',
  },
})
const selectType = ref('*')
const checkedKeys = ref([])
const gameList = ref('')
const data = ref([])
const allGameIds = ref([])

// 将原始数据转换为树形数据结构
const treeData = computed(() => {
  const result = data.value.map((item) => ({
    key: item.id || item.name, // Tree组件的唯一标识
    title: item.name, // Tree组件显示的文本
    children: item.children
      ? item.children.map((child) => ({
          key: child.id || `${item.id || item.name}_${child.name}`, // 确保子项有唯一key
          title: child.name, // Tree组件显示的文本
        }))
      : [],
  }))
  if (!searchKey.value) {
    return result
  } else {
    return searchData(result, searchKey.value)
  }
})

// 搜索数据
function searchData(result, keyword) {
  const loop = (data) => {
    const result = []
    data.forEach((item) => {
      if (item.title.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
        result.push({ ...item })
      } else if (item.children) {
        const filterData = loop(item.children)
        if (filterData.length) {
          result.push({
            ...item,
            children: filterData,
          })
        }
      }
    })
    return result
  }

  return loop(result)
}

function getMatchIndex(title) {
  if (!searchKey.value) return -1
  return title.toLowerCase().indexOf(searchKey.value.toLowerCase())
}

const init = (allGameData, checkedGameList) => {
  data.value = []
  gameList.value = checkedGameList
  checkedKeys.value = checkedGameList === '*' ? ['*'] : checkedGameList?.split(',').map(Number) || []
  selectType.value = checkedGameList === '*' ? '*' : checkedGameList === '-1' ? '-1' : '0'

  transformAllGamedata(allGameData)
}

const transformAllGamedata = (allGameData) => {
  let resGameIds = []

  allGameData.forEach((item) => {
    item.checked = checkedKeys.value.includes(item.id) || checkedKeys.value[0] === '*'
    if (item.children && Array.isArray(item.children)) {
      item.children.forEach((child) => {
        if (checkedKeys.value.includes(child.id) || checkedKeys.value[0] === '*') {
          child.checked = true
          resGameIds.push(child.id)
        } else {
          child.checked = false
        }
      })
    }
  })
  data.value = allGameData
  allGameIds.value = resGameIds
  // 初始化选中的keys
  initCheckedKeys()
}

// 初始化选中状态
const initCheckedKeys = () => {
  const keys = []
  data.value.forEach((parent) => {
    // if (parent.checked) {
    //   keys.push(parent.id || parent.name);
    // }
    if (parent.children && Array.isArray(parent.children)) {
      parent.children.forEach((child) => {
        if (child.checked) {
          keys.push(child.id || `${parent.id || parent.name}_${child.name}`)
        }
      })
    }
  })
  checkedKeys.value = keys
}

// 处理树节点选中状态变化
const handleCheck = (checkedKeysValue, e) => {
  console.log('选中状态变化:', checkedKeysValue)
  checkedKeys.value = checkedKeysValue
  // 同步更新原始数据的选中状态
  data.value.forEach((parent) => {
    const parentKey = parent.id || parent.name
    parent.checked = checkedKeys.value.includes(parentKey)

    if (parent.children && Array.isArray(parent.children)) {
      parent.children.forEach((child) => {
        const childKey = child.id || `${parent.id || parent.name}_${child.name}`
        child.checked = checkedKeys.value.includes(childKey)
      })
    }
  })
}

const getGamePermissionData = async () => {
  return {
    selectType: selectType.value,
    checkedKeys: checkedKeys.value,
    gameList: gameList.value,
  }
}

defineExpose({ init, getGamePermissionData })
</script>
