<template>
  <el-dialog
    title="移动机构"
    :append-to-body="true"
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    :visible.sync="showDialog"
    :modal="false"
    custom-class="dialog-style list-dialog pd_0"
    width="500px"
    height="500px"
    @close="dialogClose"
    v-el-drag-dialog
    v-el-dialog-center
  >
    <div class="cont" style="height: 430px;">
      <el-form ref="editForm" :model="formData" class="tree-box tree-annex">
        <el-tree
          :props="defaultProps"
          :load="loadNode"
          node-key="id"
          ref="tree"
          lazy
          :filter-node-method="filterNode"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
          class="tree-list"
          icon-class="el-icon-arrow-down"
        >
        <span class="el-tree-node__label" slot-scope="{ node, data }" v-if="!node.data.moreBtn">
          <i class="ico-wenjian"></i>
          <span>{{ node.label }}</span>
        </span>
          <span v-else class="el-tree-node__label">
          <el-button type="primary" plain class="button-sty">{{ node.label }}</el-button>
        </span>
        </el-tree>
      </el-form>
    </div>

    <div class="multipleChoice" style="margin-top:8px;">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <i class="position el-icon-map-location"></i>
        <el-breadcrumb-item v-for="(treeNode,index) in treeNodeArr" :key="index" @click.native="doNav(treeNode)">{{
            treeNode.label
          }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <span slot="footer" class="dialog-footer">
		<el-button type="primary" plain class="button-sty" @click="dialogClose">
			<i class="el-icon-close el-icon"></i>
			{{ $t1('取 消') }}
		</el-button>
		<el-button type="primary" class="button-sty" @click="dialogPrimary">
			<i class="el-icon-check el-icon"></i>
			{{ $t1('确 定') }}
		</el-button>
	</span>
  </el-dialog>
</template>

<script>
export default {
  name: 'saleOrgMoveDialog',
  props: {
    _dataId: Number,
    visiable: Boolean,
    checkRows: Array
  },
  components: {},
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {
      showDialog: true,
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'name',
        isLeaf: 'leaf'
      },
      showEditCategoryDialog: false,
      editCategory: {},
      currentRow: null,
      rootCategory: false,
      categoryPageSize: 1000,
      treeNodeArr: [],
      currentNode: null,
      formData: {}
    };
  },
  computed: {},
  created() {

  },
  methods: {
    changeCategory(row, node) {
      this.handleNodeData(node);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.categoryName.indexOf(value) !== -1;
    },
    handleNodeClick(data, node, v) {
      this.changeCategory(data, node);
    },
    // 异步树叶子节点懒加载逻辑
    loadNode(node, resolve) {
      let id = node && node.data && node.data.id ? node.data.id || '' : '';
      let url, param;

      if (!id) {
        url = USER_PREFIX + '/sale_org/getCurrentList';
        param = {};
      } else {
        url = USER_PREFIX + '/sale_org/getChildren';
        param = {
          parent: id
        };
      }
      this.$http({
        url: url,
        method: 'post',
        data: param,
        success: res => {
          let rows = res && res.objx ? res.objx : [];

          if (!id) {
            rows.unshift({
              parent: null,
              name: '全部机构',
              leaf: true,
              allFileBtn: true,
              id: 0
            })
          }

          // moreBtn
          rows.forEach(value => {
            value.leaf = !value.hasChild;
          });
          if (node.level === 0) {
            setTimeout(() => {
              this.$refs.tree.setCurrentKey(node.childNodes[0].data)
              this.handleNodeData(node.childNodes[0]);
            }, 200);
            if (rows.length > 1 && rows[1].hasChild) {
              this.$nextTick(() => {
                if (node.childNodes.length) {
                  let nodedata = node.childNodes[1];
                  nodedata.expanded = true;
                  nodedata.loadData();
                }
              });
            }
          }
          resolve(rows);
        }
      });
    },
    handleNodeData(node) {
      let treeNodeArr = [];
      let tree = this.$refs.tree;
      let firstNode = tree.root.childNodes[0];
      if (node && node.id != firstNode.id) {
        treeNodeArr.push(node);
        let end = false;
        let pNode = node;
        while (!end) {
          pNode = pNode.parent;
          if (pNode && pNode.data) {
            let pData = pNode.data;
            treeNodeArr.push(pNode);
            end = pNode.level <= 1;
          } else {
            end = true;
          }
        }
        treeNodeArr = treeNodeArr.reverse();
      }
      treeNodeArr.unshift(firstNode)
      if (!node) {
        node = firstNode;
      }
      this.currentRow = node && node.data ? node.data : null;
      this.currentNode = node;
      this.$set(this, 'treeNodeArr', treeNodeArr);
    },
    doNav(t) {
      let node = this.$refs.tree.getNode(t.data.id + '');
      this.$refs.tree.setCurrentKey(node.data)
      this.handleNodeClick(node.data, node, this);
    },
    dialogClose() {
      this.$emit('update:visiable', false);
    },
    dialogPrimary() {

      if (!this.currentRow) {
        this.$message({
          message: '请选择需要移动的机构',
          type: 'error',
          duration: 3000,
        });
        return;
      }

      if (this.currentRow.id == this.checkRows[0].parent) {
        this.$message({
          message: '数据已在机构[' + this.currentRow.name + ']中，不需要移动',
          type: 'error',
          duration: 3000,
        });
        return;
      }

      let checkCategorys = this.checkRows.filter(item => item.dirs);
      for (let i = 0; i < checkCategorys.length; i++) {
        let checkCategory = checkCategorys[i];
        if (this.currentRow.id == checkCategory.id) {
          this.$message({
            message: '目标机构与源机构的不允许为同一个机构',
            type: 'error',
            duration: 3000,
          });
          return;
        }
        if (this.currentRow.id && this.currentRow.treePath.indexOf(',' + checkCategory.id + ',') != -1) {
          this.$message({
            message: '目标机构是源机构的子机构',
            type: 'error',
            duration: 3000,
          });
          return;
        }
      }

      if (this.currentRow.id == 0) {
        let fileItem = this.checkRows.find(item => !item.dirs);
        if (fileItem) {
          this.$message({
            message: '数据不允许移动到[全部机构]',
            type: 'error',
            duration: 3000,
          });
          return;
        }
      }

      this.$baseConfirm('您确定要移动机构吗？').then(() => {
        this.$http({
          method: 'post',
          url: USER_PREFIX + '/sale_org/move',
          data: {
            parent: this.currentRow.id,
            fileObjDTOs: this.checkRows
          },
          isLoading: true,
          success: res => {
            this.$message({
              message: res.content,
              type: 'success',
              duration: 500,
            });
            let categoryArr = this.treeNodeArr.reverse().map(item => item.data);
            this.$emit('confirm', this.currentRow, categoryArr);
            this.dialogClose();
          }
        });
      });
    }
  }
};
</script>
<style scoped>
.tree-box {
  width: 100%;
  border-right: none;
}

.tree-box.tree-annex .tree-list {
  height: auto;
  padding-top: 0;
}
</style>
