<template>
  <div class="custom-tree-container">
    <div class="block">
      <el-tree
        :data="datamsg"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
        draggable
        :allow-drop="allowDrop"
        :render-content="renderContent"
        @node-click="nodeClick"
        @node-drop="handleDrop"
      />
    </div>
    <el-dialog title="新建部门" :visible.sync="centerDialogVisible" width="600px" center>
      <span class="addcenterDialogVisible">
        <el-form ref="addSection" :model="addSection" class="demo-ruleForm" :rules="rules">
          <el-form-item label="部门名称：" prop="deptName">
            <el-input v-model="addSection.deptName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="部门英文名称：" prop="deptName_en">
            <el-input v-model="addSection.deptName_en" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDeptName('addSection')">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getTreeList,
  delTreeList,
  moveTreeList
} from '../../api/organization/tree';
import dropdown from '../../views/organization/dropdown';
import {
  addCreate
} from '../../api/organization/organization';

const _ = require('lodash');

export default {
  props: ['show'],
  watch: {
    show() {
      this.centerDialogVisible = true;
    }
  },
  data() {
    return {
      centerDialogVisible: false,
      addSection: {
        compId: '',
        deptName: '',
        deptName_en: '',
        parentDeptId: ''
      },
      ss: '',
      treemsg: '',
      compId: localStorage.getItem('enterprise-front-companyId'),
      msg: '',
      maxexpandId: 6,
      non_maxexpandId: 6,
      children01: [],
      datamsg: [],
      rules: {
        deptName: [{
          required: true,
          message: '',
          trigger: 'blur'
        }]
      }
    };
  },
  created() {
    this.getlist();
  },
  methods: {
    // 获取部门列表
    getlist() {
      getTreeList({
        compId: this.compId
      }).then((response) => {
        function flatTree(tree, childrenName, collector) {
          if (_.isArray(tree)) {
            _.forEach(tree, (child) => {
              collector.push(child);
              flatTree(child[childrenName], childrenName, collector);
            });
          }
        }
        const tree = response;

        const nodes = [];
        flatTree(tree, 'children', nodes);
        for (let i = 0; i < nodes.length; i++) {
          nodes[i].isEdit = false;
        }
        const ss = [];
        ss.push(nodes[0]);
        this.treemsg = response;
        this.datamsg = ss;
        this.$emit('treeMsg', response);
      }).catch(() => {
        this.$emit('treeMsg', false);
      });
    },
    allowDrop(draggingNode, dropNode, type) {
      if (draggingNode.parent.id === dropNode.parent.id) {
        return type !== 'inner';
      }
    },
    handleAdd(s, d, n) {
      this.addSection.parentDeptId = d.id;
      this.centerDialogVisible = true;
      this.$emit('treeAdd', s, d, n);
    },
    handleEdit() { // 编辑节点
    },
    handleDel(s, d, n) { // 删除节点
      const that = this;
      // 有子级不删除
      if (d.children && d.children.length !== 0) {
        this.$message({
          type: 'error',
          message: '此节点有子级，不可删除！',
          showClose: true,
        });

        return false;
      }
      // 新增节点直接删除，否则要询问是否删除
      const delNode = () => {
        delTreeList(d.id).then(() => {
          const list = n.parent.data.children || n.parent.data;
          let _index = 99999; // 要删除的index
          list.forEach((c, i) => {
            if (d.id === c.id) {
              _index = i;
            }
          });
          this.ss = list.splice(_index, 1);
          that.$message({
            message: '删除成功！',
            type: 'success',
            showClose: true,
          });
        }).catch(() => {
          this.$message({
            message: '删除失败！',
            type: 'success',
            showClose: true,
          });
        });
      };
      const isDel = () => {
        that.$confirm('是否删除该部门？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delNode();
        }).catch(() => {
          return false;
        });
      };
      // 判断是否新增
      if (d.id > this.non_maxexpandId) {
        delNode();
      } else {
        isDel();
      }
    },

    renderContent(h, {
      node,
      data,
      store
    }) {
      const that = this;
      return h(dropdown, {
        props: {
          NODE: node,
          DATA: data,
          STORE: store
        },
        on: {
          nodeAdd: (n, d, s) => that.handleAdd(n, d, s),
          nodeEdit: (n, d, s) => that.handleEdit(n, d, s),
          nodeDel: (n, d, s) => that.handleDel(n, d, s)
        }
      });
    },
    nodeClick(data) {
      this.addSection.parentDeptId = data.id;
      this.msg = data;
      const numberval = 0;
      this.$emit('treeClick', data, numberval);
      this.$router.push({
        name: 'organization',
        params: {}
      });
    },
    handleDrop(draggingNode) {
      const ss = [];
      ss.push(draggingNode.store.nodesMap.COMPA1002.data);
      moveTreeList(ss).then(() => {
        this.$message({
          message: '拖拽成功',
          type: 'success',
          showClose: true,
        });
      }).catch(() => {
        this.$message({
          message: '拖拽失败',
          type: 'error',
          showClose: true,
        });
      });
    },
    /* 添加子部门 */
    addDeptName(formName) {
      this.addSection.compId = this.compId;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.addSection.deptName_en === '') {
            this.addSection.deptName_en = this.addSection.deptName;
          }
          if (this.addSection.parentDeptId === '') {
            this.addSection.parentDeptId = this.addSection.compId;
          }
          addCreate(this.addSection)
            .then(() => {
              this.$message({
                message: '保存成功',
                type: 'success',
                showClose: true,
              });
              this.getlist();
              this.centerDialogVisible = false;
            })
            // eslint-disable-next-line handle-callback-err
            .catch(() => {
              this.$message({
                message: '保存失败',
                type: 'reeor',
                showClose: true,
              });
              this.centerDialogVisible = true;
            });
        } else {
          this.$message({
            message: '带星号为必填项！',
            type: 'warning',
            showClose: true,
          });
          this.centerDialogVisible = true;
          return false;
        }
      });
    }
  }
};

</script>
<style lang="scss">
.custom-tree-container {
  height: calc(86vh - 10px);
  overflow-y: auto;
  overflow-x: hidden;
  padding-top: 10px;
  width: 260px;
  // height: auto;
  .el-tree-node__content {
    border-left: 10px solid rgba(0, 0, 0, 0);
  }
  .el-tree-node__content:hover {
    background-color: #dde9fc;
    border-left: 10px solid #1d6ced;
  }
  .el-tree .is-current {
    .el-tree-node__content {
      background-color: #dde9fc;
      border-left: 10px solid #1d6ced;
    }
    .el-tree-node__children .el-tree-node__content {
      background-color: #fff;
      border-left: 10px solid rgba(0, 0, 0, 0);
    }
    .el-tree-node__children .el-tree-node__content:hover {
      background-color: #dde9fc;
      border-left: 10px solid #1d6ced;
    }
  }
}
.el-tree-node__content > .el-tree-node__expand-icon {
  padding: 0;
  width: 18px;
}
</style>
