<template>
  <el-dialog
    :visible.sync="visible"
    title="选择资产分类"
    @before-close="cancel"
    width="80vw"
  >
    <div v-loading="treeLoading" style="height: 60vh; overflow: auto">
      <Content :treeList="treeList" />
    </div>
    <div slot="footer" class="footer">
      <el-button type="text" @click="clear" style="float: left">清除</el-button>
      <el-button type="primary" @click="confirm">确定选中</el-button>
      <el-button @click="cancel">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import Content from './Content.vue';
  // import common from '@/api/common'

  let callback = null;
  export default {
    components: { Content },
    provide() {
      return {
        selected: this.selected,
        handleSelectedChange: this.handleSelectedChange
      };
    },
    data() {
      return {
        visible: false,
        treeLoading: false,
        treeList: [],
        selected: {
          value: ''
        }
      };
    },
    created() {
      this.getTrees();
    },
    methods: {
      open(value) {
        this.visible = true;
        this.selected.value = value;
        return new Promise((res) => {
          callback = res;
        });
      },
      clear() {
        this.selected.value = '';
      },
      handleSelectedChange(value) {
        this.selected.value = value;
      },
      confirm() {
        callback &&
          callback({ code: this.selected.value, name: this.getName() });
        this.$emit('success', this.selected.value);
        this.cancel();
      },

      getName() {
        if (!this.selected.value) return '';
        let res = '';
        const fn = (list, parent = []) => {
          if (res) return;
          for (const p of list) {
            const str = p.name;

            if (res) break;
            if (p.id === this.selected.value) {
              res = [...parent, str].join('/');
              return;
            }

            if (p.children?.length) {
              fn(p.children, [...parent, str]);
            }
          }
        };
        fn(this.treeList);

        return res;
      },
      cancel() {
        this.selected.value = '';
        this.visible = false;
      },
      async getTrees() {
        this.treeLoading = true;
        const res = await common.getClassify({ type: '1,2,5,6,7' });
        this.treeLoading = false;
        if (res.success) {
          this.treeList = res.data;
        }
      }
    }
  };
</script>
<style lang="scss" scoped>
  .footer {
    text-align: right;
  }
</style>
