<template>
  <el-dialog :visible.sync="dialogFormVisible" title="合并部门" width="60%" append-to-body>
    <div>
      <el-row>
        <el-col :span="12">
          <div style="margin-bottom:20px;">
            <div style="margin-bottom:20px; font-size: 16px">请选择要合并的部门:</div>
            <el-input :value="oldDeptNames" size="small" placeholder="至少选择1个,最多5个"/>
          </div>
          <el-scrollbar class="deptScroll">
            <el-tree
              v-loading = "treeLoading"
              ref="tree1"
              :data="deptTree"
              :props="defaultProps"
              :default-expand-all="true"
              :expand-on-click-node="false"
              :check-on-click-node="true"
              :check-strictly="true"
              node-key="id"
              show-checkbox
              class="filter-tree"
              @check-change="oldDeptCheckChange"
            />
          </el-scrollbar>
        </el-col>
        <el-col :span="1">
          <el-divider direction="vertical"/>
        </el-col>
        <el-col :span="11">
          <div style="margin-bottom:20px;">
            <div style="margin-bottom:20px; font-size: 16px">请选择要合并到的部门:</div>
            <el-input :value="newDept?newDept.name:''" size="small" placeholder="只能选择1个"/>
          </div>
          <el-scrollbar class="deptScroll">
            <el-tree
              v-loading = "treeLoading"
              ref="tree2"
              :data="newDeptTree"
              :props="defaultProps"
              :default-expand-all="true"
              :expand-on-click-node="false"
              :check-on-click-node="true"
              :check-strictly="true"
              node-key="id"
              show-checkbox
              class="single-tree"
              @check-change="newDeptCheckChange"
            />
          </el-scrollbar>
        </el-col>
      </el-row>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button :loading="btnLoading" type="primary" @click="saveData">合并部门</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { toTreeList } from '@/utils/structure'
import SelectTree from '@/components/SelectTree/singleSelect'
import { getDeptTreeList, mergeDept } from '@/api/system/dept'
import DeptSelect from '@/components/DeptSelect'

export default {
  name: 'MergeDept',
  components: { DeptSelect, SelectTree },
  data() {
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      deptForm: {
        oldDeptIds: [],
        newDeptId: ''
      }, // 表单
      oldDepts: [],
      newDept: null,
      deptTree: null,
      newDeptTree: null,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      treeLoading: false,
      btnLoading: false // 保存按钮的加载中状态
    }
  },
  computed: {
    oldDeptNames() {
      const list = this.oldDepts.map(item => item.name)
      return list.join(', ')
    }
  },
  methods: {
    // 初始化对话框
    initDialog: function() {
      this.dialogFormVisible = true
      this.fetchDeptTree()
    },
    // 获取组织结构树
    fetchDeptTree() {
      this.treeLoading = true
      getDeptTreeList(this.listQuery).then(response => {
        const deptTree = toTreeList(response.data.list, '0', true)
        this.deptTree = deptTree
        this.newDeptTree = JSON.parse(JSON.stringify(deptTree)) // 复制出一棵树
        this.deptTree[0].disabled = true
        this.treeLoading = false
      })
    },
    oldDeptCheckChange(data, checked) {
      if (checked) {
        this.oldDepts.push(data)
      } else {
        const index = this.oldDepts.findIndex(item => item.id === data.id)
        this.oldDepts.splice(index, 1)
      }
    },
    newDeptCheckChange(data, checked) {
      if (checked) {
        var labvalojb = data // 暂存选中节点
        this.newDept = data
        this.$refs.tree2.setCheckedKeys([]) // 删除所有选中节点
        this.$refs.tree2.setCheckedNodes([labvalojb]) // 选中已选中节点
      }
    },
    // 重置表单
    resetForm() {
      this.deptForm = {
        oldDeptIds: [],
        newDeptId: ''
      }
    },
    // 保存数据
    saveData: function() {
      // 先校验
      if (this.validate()) {
        this.deptForm = {
          oldDeptIds: this.oldDepts.map(item => item.id),
          newDeptId: this.newDept.id
        }
        this.$confirm('合并部门后可能会影响到角色权限，部分需要重新配置，是否确认合并？', '确认信息', {
          distinguishCancelAndClose: true,
          confirmButtonText: '合并',
          cancelButtonText: '放弃'
        })
          .then(() => {
            mergeDept(this.deptForm).then(response => {
              if (response.code === 200) {
                this.$message.success('合并成功')
                this.btnLoading = false
                this.resetForm()
                this.$nextTick(() => {
                  this.$refs['dataForm'].clearValidate()
                })
                this.dialogFormVisible = false
                this.$emit('watchChild')
              }
            }).catch(_ => { // 异常情况，loading置为false
              this.btnLoading = false
            })
          })
          .catch(action => {
          })
      }
    },
    validate() {
      if (this.oldDepts.length === 0) {
        this.$message.warning('请选择待合并部门')
        return false
      }
      if (this.oldDepts.length > 5) {
        this.$message.warning('一次合并部门不能超过5个')
        return false
      }
      if (this.newDept === null) {
        this.$message.warning('请选择要合并到的部门')
        return false
      }
      const index = this.oldDepts.findIndex(item => item.id === this.newDept.id)
      if (index > -1) {
        this.$message.warning('两边部门不能重复')
        return false
      }
      return true
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-scrollbar{
    height: 330px;
  }
  .el-select{
    width: 100%;
  }
  .single-tree{
    el-checkbox__inner{
      border-radius: 10px;
    }
  }
</style>
<style>
  .deptScroll .el-scrollbar__wrap{
    overflow-x: hidden;
    background-color: #fff;
    padding: 0px;
  }
</style>
