<script setup>
import { ref } from 'vue'
import apiReport from '@/api/report'
import _ from 'lodash'

const props = defineProps({
  defaultVal: null
})
const emit = defineEmits(['close',' confirm'])


const activeUser = ref(props.defaultVal?props.defaultVal.map(_ => _.NodeId):[])
const list = ref([])
const userOpts = ref([])
const keyWord = ref([])
async function getUser() {
  const res = await apiReport.getSystemUser({
    KeyWord: ''
  })
  
  if(res.Ret !== 200) return 
//   list.value = res.Data || [];
    
  list.value = filterTreeEmpty({Children:res.Data||[]})
	userOpts.value =  _.cloneDeep(list.value);

}
getUser()

// 递归处理数组
function filterTreeEmpty(arr) {
    let users = []
    function dfs(node) {
        if (Array.isArray(node.Children)) {
            for (let child of node.Children) {
                dfs(child);
            }
            if(node.Children.length===0) delete node.Children
        }
        //若为叶子节点,且不为用户,禁止选中
        if(!node.Children||!Array.isArray(node.Children)){
            if(node.NodeType===3) users.push(node)
        }
    }
    dfs(arr);

    return users
}

function handleSearch() {
	userOpts.value = list.value.filter(_ => _.NodeName.startsWith(keyWord.value))
}

function handleCancle() {
  emit('close')
}
function handleConfirm() {

	let selectUsers = list.value.filter(_ => activeUser.value.includes(_.NodeId));
	emit('confirm',selectUsers)
}
</script>
<template>
  <div class="choose-user-wrap">
		<div class="top-box">
			<van-search 
					shape="round"
					placeholder="请输入用户"
					v-model="keyWord"
					@search="handleSearch"
			/>
		</div>	

		<van-checkbox-group v-model="activeUser">
				<van-checkbox
						v-for="item in userOpts"
						:key="item.NodeId"
						:name="item.NodeId"
				>{{item.NodeName}}</van-checkbox>
		</van-checkbox-group>

    <div class="bot-btns">
        <van-button class="bot-btn" type="default" @click="handleCancle">取消</van-button>
        <van-button class="bot-btn" type="primary" @click="handleConfirm">确定</van-button>
    </div>
      
  </div>
</template>
<style scoped lang="scss">
.choose-user-wrap{
    height: 100%;
    display: flex;
    flex-direction: column;
		.top-box{
				position: sticky;
        top: 0;
        z-index: 99;
        background-color: #fff;
    }
		.van-checkbox-group{
				padding: $page-padding;
				flex: 1;
				overflow-y: auto;
				.van-checkbox{
						:deep(.van-checkbox__label){
								padding: 32px 0;
								flex: 1;
								border-bottom: 1px solid $border-color;
						}
				}
		}
    
    .bot-btns{
			flex-shrink: 0;
			padding: 20px 0;
			text-align: center;
			.bot-btn {
				width: 315px;
    		margin: 0 10px;
			}
    }
}
@media screen and (min-width:$media-width){
    .choose-user-wrap{
    }
}
</style>