<template>
  <van-popup
    v-model="visible"
    closeable
    position="left"
    :style="{ height: '100%',width:'80%'}"
    @opened="loadTreeData"
    @close="handleClose"
  >
    <van-nav-bar
      :title="title"
      fixed
    />
    <div class="ibps-fixed-navbar ibps-fixed-top">
      <van-loading
        v-if="loading"
        vertical
      >加载中...</van-loading>
      <ibps-tree
        v-else
        :tree-data="treeData"
        :props="props"
        last-class
        @node-click="handleNodeClick"
      />
    </div>
  </van-popup>
</template>

<script>
import { findTreeData } from '@/api/platform/cat/type'
import TreeUtils from '@/utils/tree'
import IbpsTree from '@/components/ibps-tree/index.vue'

export default {
  components: {
    IbpsTree
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '分类'
    },
    categoryKey: {
      type: String
    }

  },
  data() {
    return {
      visible: false,
      loading: false,
      treeData: [],
      props: {
        children: 'children',
        label: 'name'
      }
    }
  },
  watch: {
    value(val, oldVal) {
      if (val !== oldVal) {
        this.visible = val
      }
    }
  },
  created() {
    this.loadTreeData()
  },

  methods: {
    loadTreeData() {
      if (this.$utils.isNotEmpty(this.treeData)) {
        this.loading = false
        return
      }
      this.loading = true
      findTreeData({ 'categoryKey': this.categoryKey }).then(response => {
        const data = response.data || []
        const treeData = TreeUtils.transformToTreeFormat(data, {
          idKey: 'id',
          parentIdKey: 'parentId',
          childrenKey: 'children'
        })
        this.treeData = treeData
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleClose() {
      this.$emit('close', false)
    },
    handleNodeClick(item) {
      this.handleClose()
      const data = item.data
      this.$emit('node-click', data.parentId === '-1' ? {} : data)
    }
  }
}
</script>

