<!--
应用功能独有表单
@Author: linqian
@Date: 2021-07-11 15:03
-->
<template>
  <div>
    <transfer-tree
      ref="transferTree"
      filterable
      :titles="['可选资源', '已选资源']"
      v-model="selectedValue"
      :data="data"
      children-name="child"
      pid-name="p"
      :open-all="false"
      :transfer-open-node="true"
      :filter-node-from="handleSearch"
      value-name="id"
    >
    </transfer-tree>
    <div v-footer>
      <dg-button @click="handleCancel">取消</dg-button>
      <dg-button type="primary" @click="handleSubmit">确定</dg-button>
    </div>
  </div>
</template>

<script>
import transferTree from '@/pages/common/transfer-tree';
import { allAppFuncTree, userHasAuthFunIds } from '@/api/permission-selfhelp-manage';

function findIndexArray(data, id, indexArray) {
  let arr = Array.from(indexArray);
  for (let i = 0, len = data.length; i < len; i++) {
    arr.push(data[i].label);
    if (data[i].id === id) {
      return arr;
    }
    let children = data[i].child;
    if (children && children.length) {
      let result = findIndexArray(children, id, arr);
      if (result) return result;
    }
    arr.pop();
  }
  return false;
}

export default {
  props: {
    selectKeys: [Array]
  },
  components: { transferTree },
  data() {
    return {
      approveContent: this.value,
      selectedValue: this.selectKeys,
      data: []
    };
  },
  computed: {},
  methods: {
    nodeTransferLabel() {
      const funcAttr = this.selectedValue.map((item) => {
        return findIndexArray(this.$refs.transferTree.targetData, item, []);
      });
      let attr = [];
      for (let i = 0; i < funcAttr.length; i++) {
        const element = funcAttr[i].join('/');
        attr.push(element);
      }
      return attr.join('，');
    },
    handleCancel() {
      this.$emit('close');
    },
    handleSubmit() {
      if (this.selectedValue.length == 0) {
        this.$message.warning('请至少选择一条功能资源！');
      } else {
       
        const approveContent = this.nodeTransferLabel();
        const resourceInfos = this.selectedValue
          .map((item) => this.$refs.transferTree.$refs['to-tree'].getNode(item).data)
          .map((item) => {
            return {
              appId: item.pid,
              funId: item.id
            };
          });
        this.$emit('success', approveContent, this.selectedValue, resourceInfos);
      }
    },
    handleSearch(value, data) {
      console.log(value, data.label);
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    }
  },
  created() {
    allAppFuncTree().then((res) => {
      this.data = res.data.content;
    });
  },
  mounted() {}
};
</script>

<style lang='scss' scoped>
@import url('../index.scss');
</style>