<template>
  <div class="cus-tree" ref="ref_cusTree" v-if="refresh">
    <CusTreeItem
        :data="data"
        :options="{
          label, value, children, left, expendTrueImg, expendFalseImg
        }"
    >
      <template #default="{data}">
        <slot :data="data"/>
      </template>
    </CusTreeItem>
  </div>
</template>

<script lang="ts">
  import {
    defineComponent,
    onMounted,
    ref,
    toRefs,
    reactive,
    watch,
    getCurrentInstance,
    ComponentInternalInstance,
    computed, nextTick
  } from "vue";
  import { useStore } from "vuex";
  import { useRouter } from "vue-router";
  import { ElMessage, ElMessageBox } from "element-plus";
  import CusTreeItem from "./CusTreeItem.vue";
  import expendTrueImg from '@/assets/images/cus/to-bottom.png'
  import expendFalseImg from '@/assets/images/cus/to-right.png'
  export default defineComponent({
    name: "CusTree",
    components: {
      CusTreeItem
    },
    props: {
      data: {required: true},
      label: {default: 'label'},
      value: {default: ''},
      children: {default: 'children'},
      left: {default: 20},
      expend: {default: false},
      expendTrueImg: {default: expendTrueImg},
      expendFalseImg: {default: expendFalseImg},
      filterMethod: {default: () => {}}
    },
    setup(props) {
      const store = useStore();
      const that = (getCurrentInstance() as ComponentInternalInstance).appContext.config.globalProperties;
      const state = reactive({
        _dataBack: props.data,
        _data: props.data,
        refresh: true
      });
      watch(() => props.data, (n) => {
        initData(n)
        filter()
      })

      const initData = (list) => {
        const deep = (arr) => {
          arr.forEach(v => {
            v._expend = props.expend ? true : false
            if (v[props.children]?.length > 0) {
              deep(v[props.children])
            }
          })
        }
        deep(list)
      }
      const filter = (isExpend = null) => {
        const deep = (arr) => {
          arr.forEach(v => {
            v._count = 0
            if (props.filterMethod(v)) {
              if (isExpend !== null) {
                v._expend = isExpend
              }
              v._count++
            }
            if (v[props.children]?.length > 0) {
              deep(v[props.children])
              if (v[props.children].filter(c => c._count > 0).length > 0) {
                if (isExpend !== null) {
                  v._expend = isExpend
                }
                v._count++
              }
            }
          })
        }
        deep(props.data)
        state.refresh = false
        setTimeout(() => {
          state.refresh = true
        }, 100)
      }
      onMounted(() => {
        initData(props.data)
        filter()
      })
      return {
        ...toRefs(state),
        filter,
      }
    },
  });
</script>
<style scoped lang="scss">
.cus-tree {
  width: 100%;
  height: calc(100vh);
}
</style>
