<!-- 组织架构 -->
<template>
  <div class="app-container organizationalStructure">
    <div class="page-container organizationalStructurePage">
      <div class="page-form-title-box">
        <el-form :model="queryParams" class="form-box" ref="queryForm"
                 :inline="true" style="width:100%;">
          <el-form-item label="" prop="deptName">
            <el-input
              maxLength="30"
              v-model="queryParams.deptName"
              placeholder="请输入名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="" prop="state">
            <el-select v-model="queryParams.state" clearable placeholder="请选择状态" style="width: 200px">
              <el-option
                v-for="dict in optionList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <p class="page-inquire-common-style-button" @click="handleQuery">查询</p>
          <p class="page-reset-common-style-button" @click="resetQuery">重置</p>
        </el-form>
      </div>
      <div class="page-content-box">
        <el-table class="table-box" v-loading="loading" border :data="dataList"
                  row-key="deptId"
                  default-expand-all
                  :tree-props="{children: 'child', hasChildren: 'hasChildren'}">>
          <el-table-column label="名称" align="left" prop="deptName"  show-overflow-tooltip/>
          <el-table-column label="简称" align="left" prop="deptShortName" width="200" show-overflow-tooltip/>
          <el-table-column label="编号" align="left" prop="deptNum" width="200" show-overflow-tooltip>
            <template slot-scope="scope" v-if="scope.row.deptId != parentId ">{{scope.row.deptNum}}</template>
          </el-table-column>
          <el-table-column label="是否为学院" align="left" prop="content" width="140" show-overflow-tooltip>
            <template slot-scope="scope" v-if="scope.row.deptId != parentId ">{{scope.row.deptType == 1 ? '学院' : ''}}</template>
          </el-table-column>
          <el-table-column label="状态" align="left" prop="state" width="100" show-overflow-tooltip>
            <template slot-scope="scope">
              <div v-if="scope.row.deptId != parentId"
                   v-hasPermiRouter="['system:dept:edit']">
                <el-switch
                  @click.native="tableButton(4,scope.row)"
                  class="switch captcha-img"
                  :active-value="true"
                  :inactive-value="false"
                  active-color="#0183FA"
                  inactive-color="#999"
                  v-model="scope.row.state"
                  active-text="启用"
                  inactive-text="停用"
                  disabled
                ></el-switch>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="240" show-overflow-tooltip v-if="tableButtonType">
            <template slot-scope="scope">
              <div class="table-button-box">
                <p class="table-button-null"></p>
                <p class="table-button-p"
                   @click="tableButton(1,scope.row)"
                   v-hasPermiRouter="['system:dept:add']"
                >新增</p>
                <p class="table-button-p"
                   @click="tableButton(2,scope.row)"
                   v-hasPermiRouter="['system:dept:edit']"
                >编辑</p>
                <p class="table-button-p"
                   v-if="scope.row.deptId != parentId "
                   @click="tableButton(3,scope.row)"
                   v-hasPermiRouter="['system:dept:del']"
                >删除</p>
                <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
                             v-if="scope.row.deptId != parentId "
                             v-hasPermiRouter="['system:dept:move']">
                  <p class="table-button-p">更多>></p>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="1">上移</el-dropdown-item>
                    <el-dropdown-item command="2">下移</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <p class="table-button-null"></p>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--编辑--组织架构-->
    <el-dialog title="修改部门" v-if="treeOpen" :visible.sync="treeOpen" width="600px" append-to-body class="organizationalStructure-dialog-box">
      <el-form :model="treeForm" class="organizationalStructure-dialog-form-box" ref="treeForm" :rules="rules">
        <el-form-item label="上级部门" prop="parentId" label-width="90px" v-if="treeForm.parentId != 0">
          <treeselect v-model="treeForm.parentId" :options="deptOptionsOne"
                      :normalizer="normalizer" :show-count="true" @select="deptSelect" placeholder="请选择上级部门" />
        </el-form-item>
        <el-form-item label="部门编号" prop="deptNum" label-width="90px" v-if="treeForm.parentId != 0">
          <el-input v-model="treeForm.deptNum" maxlength="15"
                    onkeyup="this.value=this.value.replace(/[^\d.]/g,'')"
                    @blur="treeForm.deptNum = $event.target.value"
                    placeholder="请输入部门编号"/>
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName" label-width="90px">
          <el-input v-model="treeForm.deptName" maxlength="15" @blur="editBlur(treeForm.deptName)" placeholder="请输入部门名称"/>
        </el-form-item>
        <el-form-item label="部门简称" prop="deptShortName" label-width="90px">
          <el-input v-model="treeForm.deptShortName" maxlength="15" placeholder="请输入部门简称"/>
        </el-form-item>
        <el-form-item label="状态" prop="state" label-width="90px" v-if="treeForm.parentId != 0">
          <el-radio-group v-model="treeForm.state" style="margin:4px 0 0 10px;">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="treeForm.parentId == parentId"
                       label="部门类型" prop="deptType" label-width="90px">
          <el-radio-group v-model="treeForm.deptType" style="margin:4px 0 0 10px;">
            <el-radio :label="1">学院</el-radio>
            <el-radio :label="0">非学院</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer dialog-footer-box">
        <p class="dialog-footer-button-null"></p>
        <p class="dialog-footer-button-info" @click="treeOpenOff">取消</p>
        <p class="dialog-footer-button-primary" @click="editDeptButton">提交</p>
        <p class="dialog-footer-button-null"></p>
      </div>
    </el-dialog>
    <!--新增--组织架构-->
    <el-dialog title="新增部门" v-if="treeAddOpen" :visible.sync="treeAddOpen" width="600px" append-to-body class="organizationalStructure-dialog-box">
      <el-form :model="treeAddForm" class="organizationalStructure-dialog-form-box" ref="treeAddForm" :rules="rules">
        <el-form-item label="上级部门" prop="parentId" label-width="110px">
          <treeselect style="width:402px;" v-model="treeAddForm.parentId" :options="deptOptions" :show-count="true"
                      :normalizer="normalizer" @select="deptAddSelect" placeholder="请选择上级部门"/>
        </el-form-item>
        <div class="scrollbar-box" style="max-height:456px">
          <div style="display:flex;border:1px solid #d8d8d8;border-radius:6px;margin:0 20px 20px;padding-top:20px;position: relative"
               v-for="(item,index) in treeAddForm.teaCherDpetList" :key="index">
            <div style="width:490px;">
              <el-form-item label="部门编号" :prop="'teaCherDpetList.' + index + '.deptNum'" :rules="rules.deptNum" label-width="90px">
                <el-input v-model="item.deptNum"
                          onkeyup="value=value.replace(/[^\d]/g,'')"
                          @blur="item.deptNum = $event.target.value"
                          maxlength="15" placeholder="请输入部门编号"/>
              </el-form-item>
              <el-form-item label="部门名称" :prop="'teaCherDpetList.' + index + '.deptName'" :rules="rules.deptName" label-width="90px">
                <el-input v-model="item.deptName" maxlength="15" @blur="addBlur(item.deptName,index)" placeholder="请输入部门名称"/>
              </el-form-item>
              <el-form-item label="部门简称" :prop="'teaCherDpetList.' + index + '.deptShortName'" :rules="rules.deptShortName" label-width="90px">
                <el-input v-model="item.deptShortName" maxlength="15" placeholder="请输入部门简称"/>
              </el-form-item>
              <el-form-item label="状态" :prop="'teaCherDpetList.' + index + '.state'" :rules="rules.state" label-width="90px">
                <el-radio-group v-model="item.state" style="margin:4px 0 0 10px;">
                  <el-radio :label="true">启用</el-radio>
                  <el-radio :label="false">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="treeAddForm.parentId == parentId"
                            label="部门类型" :prop="'teaCherDpetList.' + index + '.deptType'" :rules="rules.deptType" label-width="90px">
                <el-radio-group v-model="item.deptType" style="margin:4px 0 0 10px;">
                  <el-radio :label="1">学院</el-radio>
                  <el-radio :label="0">非学院</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer dialog-footer-box">
        <p class="dialog-footer-button-null"></p>
        <p class="dialog-footer-button-info" @click="treeAddOpenOff">取消</p>
        <p class="dialog-footer-button-primary" @click="addDeptButton">提交</p>
        <p class="dialog-footer-button-null"></p>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { getDeptList,setDeptAdd,setDeptUpdate,setDeptDelete,setDeptSort } from "@/api/commonality/permission";
  export default {
    name: 'index',
    components: {
      Treeselect,
    },
    data () {
      return {
        tableButtonType:this.hasPermiDom(['system:dept:add','system:dept:edit','system:dept:del','system:dept:move',]),
        //页面遮罩
        loading:false,
        // 部门树选项
        deptOptions: null,
        deptOptionsOne:null,
        //下拉列表数据
        optionList:[{value:true,label:'启用'},{value:false,label:'停用'}],
        //查询条件
        queryParams:{
          page:1,
          pageSize:20,
          deptName:"",
          state :null,
        },
        //列表数据
        dataList:[],
        //新增组织架构数据
        treeAddOpen:false,
        treeAddForm:{
          id:null,
          parentId:"",
          teaCherDpetList:[],
        },
        //编辑组织架构数据
        treeOpen:false,
        treeForm:{
          id:"",
          parentId:null,
          deptName:"",
        },
        treeFormOne:{},
        userId:"",
        currentDate:'',
        inputDeptName:"",
        // 表单校验
        rules: {
          parentId: [
            { required: true, message: "请选择上级部门", trigger: "blur" }
          ],
          id: [
            { required: true, message: "请选择上级部门", trigger: "blur" }
          ],
          deptNum: [
            { required: true, message: "请输入部门编号", trigger: "blur" },
            { required: true, message: "请输入部门编号", validator: this.spaceJudgment, trigger: "blur" }
          ],
          deptName: [
            { required: true, message: "请输入部门名称", trigger: "blur" },
            { required: true, message: "请输入部门名称", validator: this.spaceJudgment, trigger: "blur" }
          ],
          deptShortName: [
            { required: true, message: "请输入部门简称", trigger: "change" },
            { required: true, message: "请输入部门简称", validator: this.spaceJudgment, trigger: "change" }
          ],
          state: [
            { required: true, message: "请选择状态", trigger: "blur" },
            { required: true, message: "请选择状态", validator: this.spaceJudgment, trigger: "blur" }
          ],
          deptType: [
            { required: true, message: "请选择部门类型", trigger: "blur" },
            { required: true, message: "请选择部门类型", validator: this.spaceJudgment, trigger: "blur" }
          ],
        },
        normalizer(node){
          //去掉children=[]的children属性
          if(node.child==null||node.child=='null'){
            delete node.child;
          }
          return {
            id: node.deptId,
            parentId:node.parentId,
            label:node.deptName,
            deptNum:node.deptNum,
            deptType:node.deptType,
            children:node.child,
          }
        },
        parentId:null
      }
    },
    created () {

    },
    mounted () {
      this.getList();
    },
    methods: {
      addBlur(name,index){
        if(name != '' && !this.treeAddForm.teaCherDpetList[index].deptShortName){
          this.$set(this.treeAddForm.teaCherDpetList[index],'deptShortName',name);
          // this.$refs['treeAddForm'].clearValidate();
        }
      },
      editBlur(name){
        if(name != '' && !this.treeForm.deptShortName){
          this.$set(this.treeForm,'deptShortName',name);
          // this.$refs['treeForm'].clearValidate();
        }
      },
      //编辑部门关闭
      treeOpenOff(){
        this.treeOpen = false;
      },
      //编辑部门提交
      editDeptButton(){
        let self = this;
        this.$refs["treeForm"].validate(valid => {
          if (valid) {
            let obj = {
              deptId:this.treeForm.deptId,
              parentId:this.treeForm.parentId,
              deptNum:this.treeForm.deptNum,
              deptName:this.treeForm.deptName,
              deptShortName:this.treeForm.deptShortName,
              state:this.treeForm.state,
              deptType:this.treeForm.parentId == this.parentId ? this.treeForm.deptType : 0,
            };
            setDeptUpdate(obj).then(response => {
              this.treeOpen = false;
              this.msgSuccess(response.message)
              this.getList();
            });
          }
        });
      },
      //新增部门提交
      addDeptButton(){
        let self = this;
        this.$refs["treeAddForm"].validate(valid => {
          if (valid) {
            let newObj = {
              teaCherDpetList:[]
            }
            for(let i=0;i<self.treeAddForm.teaCherDpetList.length;i++){
              let obj = {
                parentId:this.treeAddForm.parentId,
                deptNum:this.treeAddForm.teaCherDpetList[i].deptNum,
                deptName:this.treeAddForm.teaCherDpetList[i].deptName,
                deptShortName:this.treeAddForm.teaCherDpetList[i].deptShortName,
                state:this.treeAddForm.teaCherDpetList[i].state,
                deptType:this.treeAddForm.parentId == this.parentId ? this.treeAddForm.teaCherDpetList[i].deptType : 0,
              }
              newObj.teaCherDpetList.push(obj);
            }
            setDeptAdd(newObj.teaCherDpetList[0]).then(response => {
              this.treeAddOpen = false;
              this.msgSuccess(response.message)
              this.getList();
            });
          }
        });
      },
      //关闭新增页面
      treeAddOpenOff(){
        this.treeAddOpen = false;
      },
      //新增节点选择部门
      deptAddSelect(item){
        this.$set(this.treeAddForm,'parentId',item.id);
      },
      //编辑节点选择部门
      deptSelect(item){
        this.$set(this.treeForm,'parentId',item.id);
      },
      //查询按钮
      handleQuery(){
        this.$set(this.queryParams,'page',1);
        this.getList();
      },
      //重置按钮
      resetQuery(){
        this.$set(this,'dateRange',[])
        this.$set(this,'queryParams',{
          page:1,
          pageSize:20,
          deptName:"",
          state :null,
        });
        this.getList();
      },
      //获取数据列表
      getList(){
        this.$set(this,'loading',true);
        let obj = JSON.parse(JSON.stringify(this.queryParams))
        getDeptList(obj).then(response => {
          this.$set(this,'loading',false);
          this.$set(this,'dataList',response.data);
          this.$set(this,'deptOptions',response.data);
          this.$set(this,'parentId',response.data[0].deptId);
        });
      },
      //操作按钮
      tableButton(type,row){
        let self = this;
        if(type == 1){
          //新增
          let obj = {
            parentId:row.deptId,
            teaCherDpetList:[
              {
                deptNum:"",
                deptName:"",
                deptShortName:"",
                state:true,
                deptType:row.deptId == this.parentId ? 1:0
              }
            ]
          }
          this.$set(this,'treeAddForm',obj);
          this.treeAddOpen = true;
        }else if(type == 2){
          //编辑
          let obj = JSON.parse(JSON.stringify(row));
          let newObj = {
            deptId:obj.deptId,
            parentId:obj.parentId,
            deptNum:obj.deptNum,
            deptName:obj.deptName,
            deptShortName:obj.deptShortName,
            state:obj.state,
            deptType:obj.deptType,
          }
          this.$set(this,'treeForm',newObj);
          let list = this.handleTreeList(row.deptId,this.dataList);
          this.$set(this,'deptOptionsOne',list);
          this.treeOpen = true;
        }else if(type == 3){
          //删除
          this.$confirm('是否确认删除?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
          }).then(() => {
            setDeptDelete({deptId:row.deptId}).then(response => {
              self.msgSuccess(response.message)
              self.getList();
            });
          }).catch(() => {});
        }else if(type == 4){
          //启用&停用
          let text = row.state  ? "停用" : "启用";
          this.$confirm('是否确认' + text + '?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
          }).then(() => {
            let newObj = {
              deptId:row.deptId,
              parentId:row.parentId,
              deptNum:row.deptNum,
              deptName:row.deptName,
              deptShortName:row.deptShortName,
              state:!row.state,
              deptType:row.deptType,
            }
            setDeptUpdate(newObj).then(response => {
              self.msgSuccess(response.message)
              self.getList();
            });
          }).catch(() => {});
        }
      },
      //更多按钮
      handleCommand(val,row){
        if(val == 1){
          if(!this.moveDept(row.deptId,this.dataList,'1')){
            this.msgError('当前部门位置,无法继续向上移动')
            return
          }
          let obj = {
            deptId:row.deptId,
            move:'1',
          }
          setDeptSort(obj).then(response => {
            this.msgSuccess(response.message)
            this.getList();
          });
        }else if(val == 2){
          //部门下移动
          if(!this.moveDept(row.deptId,this.dataList,'-1')){
            this.msgError('当前部门位置,无法继续向下移动')
            return
          }
          let obj = {
            deptId:row.deptId,
            move:'-1',
          }
          setDeptSort(obj).then(response => {
            this.msgSuccess(response.message)
            this.getList();
          });
        }
      },
      //移动部门判定
      moveDept(deptId,dataList,status){
        let list = JSON.parse(JSON.stringify(dataList))
        let self = this;
        for(let i=0;i<list.length;i++){
          if(deptId == list[i].deptId){
            if(status == '1'){
              //向上移动
              return i != 0;
            }else if(status == '-1'){
              // 向下移动
              return i != list.length - 1;
            }
          }else if(list[i].child){
            let type = self.moveDept(deptId,list[i].child,status);
            if(type != undefined){
              return type
            }
          }
        }
      },
      // 编辑时上级部门数组处理(剔除自身部门)
      handleTreeList(deptId,dataList){
        let list = JSON.parse(JSON.stringify(dataList))
        let self = this;
        for(let i=0;i<list.length;i++){
          if(deptId == list[i].deptId){
            list.splice(i,1);
          }else if(list[i].child){
            self.handleTreeList(deptId,list[i].child);
          }
        }
        return list
      },
    },
  }
</script>
<style scoped lang="scss">
  .organizationalStructure{
    flex:1;
    display:flex;
    flex-direction: column;
    overflow: hidden;
    .organizationalStructurePage{
      flex:1;
      display:flex;
      flex-direction: column;
      overflow: hidden;
      .title-box{
        padding-top:20px;
        border-bottom:1px solid #dedede;
        display: flex;
      }
      .content-box{
        flex: 1;
        display: flex;
        flex-direction: column;
        padding:20px;
        overflow: hidden;
      }
    }
  }
</style>
<style lang="scss">
  .organizationalStructure {
    .el-input--small{
      width:150px!important;
    }
    .el-select{
      //width:150px!important;
    }
    .table-for-max-box{
      .el-select{
        width:210px!important;
      }
    }
    .pagination-container{
      margin: 0 !important;
      padding: 0!important;
    }
  }
  .organizationalStructure-dialog-box{
    .organizationalStructure-dialog-form-box{

    }
    .organizationalStructure-dialog-button-box{
      display: flex;
      width:190px;
      margin:0 auto;
      p{
        margin:0;
        width:70px;
        height:30px;
        line-height:30px;
        font-size:14px;
      }
      p:nth-child(1){
        margin-right:50px;
      }
    }
  }
</style>
