<template>
  <ui-form class="bi-disk-manage-folder-select" ref="form" :model="formData" :rules="formRules" label-width="100px">
    <ui-form-item prop="targetId" label="目标文件夹">
      <div class="bi-disk-manage-folder-select__control">
        <ui-tree
          :current="formData.targetId"
          label-field="filePath"
          :highlight-current="true"
          :lazy="true"
          :check-leaf-method="handleCheckLeafMethod"
          :query-method="handleQueryFolderData"
          @current-change="handleCurrentChange"
        ></ui-tree>
      </div>
    </ui-form-item>
    <ui-toolbar slot="toolbar" align="right">
      <ui-toolbar-item>
        <ui-button>取消</ui-button>
      </ui-toolbar-item>
      <ui-toolbar-item>
        <ui-button type="primary" :click="handleConfirmClick">确定</ui-button>
      </ui-toolbar-item>
    </ui-toolbar>
  </ui-form>
</template>
<script>
export default {
  name: 'BiDiskManageFolderSelect',
  props: {
    confirmMethod: {
      type: Function
    },
    loadDiskFolderDataMethod: {
      type: Function
    }
  },
  data() {
    return {
      formData: {
        targetId: null
      },
      treeData: []
    }
  },
  computed: {
    formRules() {
      return {
        targetId: [{
          required: true,
          message: '目标文件夹不能为空',
          trigger: 'change'
        }]
      }
    }
  },
  methods: {
    handleQueryFolderData({ parentNode }) {
      if (parentNode.level === 0) {
        return this.loadDiskFolderDataMethod().then((rs) => {
          return [{
            id: 'all',
            filePath: '全部文档',
            children: rs,
            hasChildren: !!rs.length
          }]
        })
      } else if (parentNode.data.id === 'all') {
        return Promise.resolve(parentNode.data.children)
      } else {
        return this.loadDiskFolderDataMethod({
          parentPathId: parentNode.data.id
        })
      }
    },
    handleCheckLeafMethod(node) {
      return node.hasChildren === false
    },
    handleCurrentChange(evt) {
      this.formData.targetId = evt.id
    },
    handleConfirmClick() {
      if (!this.confirmMethod) {
        return
      }
      return this.confirmMethod({
        targetId: this.formData.targetId
      })
    }
  }
}
</script>
<style lang="less">
.bi-disk-manage-folder-select__control{
  padding-top: 6px;
  padding-bottom: 6px;
}
</style>
