<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="33%" 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 dropdown from './dropdown';
import {
  getTreeList,
  delTreeList,
  moveTreeList
} from '../../../api/organization/tree';
import { addCreate } from '../../../api/organization/organization';

const _ = require('lodash');

export default {
  data() {
    return {
      compId: localStorage.getItem('enterprise-front-companyId'),
      centerDialogVisible: false,
      addSection: {
        compId: '',
        deptName: '',
        deptName_en: '',
        parentDeptId: ''
      },
      treemsg: '',
      msg: '',
      maxexpandId: 6,
      non_maxexpandId: 6,
      children01: [],
      datamsg: [],
      rules: {
        deptName: [
          {
            required: true,
            message: '',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  watch: {
    show() {
      this.centerDialogVisible = true;
    }
  },
  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) {
      // 删除节点
      const that = this;
      // 有子级不删除
      if (d.children && d.children.length !== 0) {
        that.$message({
          message: '此节点有子级，不可删除！',
          type: 'error',
          showCols: true
        });
        return false;
      }
      // 新增节点直接删除，否则要询问是否删除
      const delNode = () => {
        delTreeList(d.id)
          .then(() => {
            that.$message({
              message: '删除成功！',
              type: 'success',
              showCols: true
            });
          })
          .catch(() => {
            that.$message({
              message: '删除失败！',
              type: 'error',
              showCols: 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.msg = data;
      this.$emit('treeClick', data);
    },
    handleDrop(draggingNode) {
      const ss = [];
      ss.push(draggingNode.store.nodesMap.COMPA1002.data);
      moveTreeList(ss)
        .then(() => {
          this.$message({
            message: '拖拽成功',
            type: 'success'
          });
        })
        .catch(() => {
          this.$message({
            message: '拖拽失败！',
            type: 'error',
            showCols: 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;
          }
          addCreate(this.addSection)
            .then(() => {
              this.$message({
                message: '保存成功',
                type: 'success'
              });
              this.centerDialogVisible = false;
              this.getlist();
            })
            // eslint-disable-next-line handle-callback-err
            .catch(() => {
              this.$message({
                message: '保存失败！',
                type: 'error',
                showCols: true
              });
              this.centerDialogVisible = true;
            });
        } else {
          this.$message({
            message: '带星号为必填项！',
            type: 'warning'
          });
          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;
  .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;
    }
  }
}
</style>
