<script setup>
import {ref} from 'vue'
import apiReportMaterial from '@/api/reportMaterial'
import { showToast } from 'vant'

const show = defineModel('show', { required: true,type:Boolean,default:false })
const emits=defineEmits(['change'])

const classifyId=ref('')
const classifyOpts=ref([])
function removeEmptyChildrenProperties(nodes) {
    return nodes.map(node => {
        // 深拷贝节点
        const newNode = { ...node };

        // 如果 Children 是空数组，则删除该属性
        if (Array.isArray(newNode.Children) && newNode.Children.length === 0) {
            delete newNode.Children;
        } else if (newNode.Children && newNode.Children.length > 0) {
            // 如果 Children 非空，递归处理子节点
            newNode.Children = removeEmptyChildrenProperties(newNode.Children);
        }

        return newNode;
    });
}
async function getClassifyList(){
  const res=await apiReportMaterial.classify()
  if(res.Ret===200){
    const arr=res.Data.AllNodes||[]
    classifyOpts.value=removeEmptyChildrenProperties(arr)
  }
}
getClassifyList()

let selectedOpt=[]
function handleSelectChange({value,selectedOptions,tabIndex}){
  selectedOpt=selectedOptions
}

function handleConfirm(){
  if(!classifyId.value){
    showToast('请选择分类')
    return
  }
  // console.log(selectedOpt);
  const names=[]
  selectedOpt.forEach(item=>{
    names.push(item.ClassifyName)
  })
  emits('change',{names:names,classifyId:classifyId.value})
  show.value=false
}

</script>

<template>
  <van-popup 
    v-model:show="show" 
    position="bottom" 
    round
    class="classify-wrap"
  > 
    <div class="top-box">
      <span class="cancel-btn" @click="show=false">取消</span>
      <span class="title">选择分类</span>
      <span class="confirm-btn" @click="handleConfirm">确定</span>
    </div>
    <van-cascader
      v-model="classifyId"
      :options="classifyOpts"
      :closeable="false"
      :show-header="false"
      :field-names="{text:'ClassifyName',value:'ClassifyId',children:'Children'}"
      @change="handleSelectChange"
    />
  </van-popup>
</template>

<style lang="scss" scoped>
.classify-wrap{
  height: 70vh;
  display: flex;
  flex-direction: column;
  .top-box{
    display: flex;
    align-items: center;
    padding: 32px 34px;
    border-bottom: 1px solid $border-color;
    .cancel-btn{
      color: $font-grey;
      font-size: 32px;
    }
    .confirm-btn{
      color: $theme-color;
      font-size: 32px;
    }
    .title{
      font-size: 36px;
      flex: 1;
      text-align: center;
    }
  }
}
@media screen and (min-width:$media-width){
  .classify-wrap{
    .top-box{
      padding: 16px 17px;
      .cancel-btn{
        font-size: 16px;
      }
      .confirm-btn{
        font-size: 16px;
      }
      .title{
        font-size: 18px;
      }
    }
  }
}
</style>
