<template>
  <v-list class="ml-1" color="primary">
    <template v-for="(val, index) in list" :key="val[option.itemValue] ? val[option.itemValue] : 'listGroup'+index">
      <v-list-group color="primary">
        <template v-slot:activator="{ props }">
          <v-list-item
            v-bind="props"
            color="primary"
            active-class="active"
            :active="activeCalc(val)"
            :title="val[option.itemText || 'label']"
            @click="handleClick(val)"
          >
            <!-- 没有children时去掉折叠icon -->
            <template  v-if="!val?.children?.length" v-slot:append="{ appendProps }">
              <template v-bind="appendProps"></template>
            </template>
            <!-- <template v-slot:prepend="{ isActive }">
              <v-list-item-action start>
                <v-checkbox-btn :model-value="isActive"></v-checkbox-btn>
              </v-list-item-action>
            </template> -->
          </v-list-item>
        </template>
        <listGroup
          v-if="val?.children?.length"
          :list="val.children"
          :option="option"
          :selectValue="propsData.selectValue"
          :levelUI="propsData.levelUI + 1"
          @labelUpdate="labelTxt => emit('labelUpdate', labelTxt)"
          @clickUpdate="child => clickUpdate(val, child)"
        ></listGroup>
      </v-list-group>
    </template>
  </v-list>
</template>

<script setup>
// import listGroup from './listGroup'
// import { ref } from 'vue'
defineOptions({ name:'nestedListGroup-listGroup'})
const emit = defineEmits(['clickUpdate', 'parentActUpdate', 'labelUpdate'])
const propsData = defineProps({
  list: Array,
  levelUI: {
    type: Number,
    default: 1
  },
  selectValue: {
    type: [Array, String],
    default: ''
  },
  option: {
    type: Object,
    default: () => {}
  }
})
// const isActive = ref(false)
const list = propsData.list
const option = propsData.option

const handleClick = (val) => {
  val.levelUI = propsData.levelUI
  if (option.selectLevel === -1) {
    // 只能选最后一级
    if (!val.children?.length) emit('clickUpdate', val)
  } else {
    // 自定义可选层级数
    if (val.levelUI >= option.selectLevel) {
      emit('clickUpdate', val)
    }
  }
}

const activeCalc = (val) => {
  if (!propsData.selectValue || !val[option.itemValue]) return false
  else {
    const bool = (val[option.itemValue] - 0) === (propsData.selectValue -0)
    if (bool) {
      emit('labelUpdate', val[option.itemText]) // 回显
    }
    return bool
  }
}

const clickUpdate = (val, child) => {
  emit('clickUpdate', child)
}
</script>
<style lang="scss" scoped>
.active {
  color: var(--v-primary-base) !important;
  background-color: var(--default-bgc) !important;
}
</style>
