<template>
  <div class="app-container">
    <el-form :model="queryForm" ref="queryForm" :inline="true">
      <el-form-item label="部门名称:">
          <el-input
            v-model="queryForm.deptName"
            placeholder="请输入部门名称"
            style="width: 160px"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item class="right">
          <el-button plain size="mini" @click="resetQuery">重置</el-button>
          <el-button type="primary" size="mini" @click="query()">搜索</el-button>
        </el-form-item>
        <br>
        <el-button
         type="primary"
          size="mini"
          @click="handleAdd()"
          >新增</el-button
        >
      </el-form>
    <el-table
      v-loading="loading"
      :data="tableData"
      row-key="deptId"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @selection-change="handleSelectionChange"
      style="margin-top:20px"
      border
    >
      <!-- <el-table-column  type="selection" width="50" align="center">
          <input type="checkbox">
      </el-table-column> -->
      <el-table-column width="50" ></el-table-column>
      <el-table-column prop="deptName" label="部门名称" align="right"></el-table-column>
      <!-- <el-table-column prop="leader" label="负责人" ></el-table-column>
      <el-table-column prop="phone" label="电话" ></el-table-column>
      <el-table-column prop="email" label="邮箱" ></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column> -->
      <el-table-column label="操作" >
        <template slot-scope="scope">
          <el-button
            icon="el-icon-edit"
            style="color: #406CE5"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            style="color: #406CE5"
          >新增</el-button>
          <el-button
            icon="el-icon-delete"
            style="color: #F27979"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="title" class="roleDialog" :visible.sync="dialogFormVisible"  width="680px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="roleform">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级部门"  />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="dialogFormVisible = false"
          style="background: #f6f6f6"
          >取 消</el-button
        >
        <el-button type="primary" @click="submitForm()"
          >提 交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>


<script>
//aa 1：引入api文件
import { listDept, getDept, deptEdit, deptAdd, deptRemove, listDeptExcludeChild } from "@/api/system/orgnization";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import qs from 'qs'
export default {
  data() {
    return {
      loading:true,
      //aa 2：声明变量
      page:{
        current:1,
        size:20,
        total:0

      },
      queryForm:{
        deptName:undefined,
      },
      list: [],

      tableData: [

      ],
      multipleSelection: [],

      options: [

      ],
      value: "",

      options2: [

      ],
      value2: "",

      options3: [

      ],
      value3: "",

      input: "",

      dialogFormVisible: false,
      formLabelWidth: "120px",

       // 部门树选项
      deptOptions: [],
      title:undefined,

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级部门不能为空", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      // 状态数据字典
      statusOptions: [],
      //表格自适应高度
      tableHeight:undefined,
    };
  },
  components: { Treeselect },

  created() {
    //aa 2:钩子里调用查询组件
    // this.fetchData();
    this.getData()
  },
   mounted() {
    // table高度
    if(window.innerWidth <1920){
      this.tableHeight = window.innerHeight - 200
    }else{
      this.tableHeight = window.innerHeight - 205
    }
    // 监听窗口大小变化
    let self = this;
    window.onresize = function() {
      self.tableHeight = window.innerHeight - 200
    }
  },

  methods: {
    //初始化
    getData(){
      listDept(this.queryForm).then(Response =>{
        if(Response.status == "SUCCESS"){
          if(Response.data){
            this.tableData = Response.data
          }
        }
        this.loading = false
      })
      // this.getDicts("sys_normal_disable").then(response => {
      //   this.statusOptions = response.data;
      // });
    },
    query(){
      this.getData()
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: 0,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0"
      };
      this.queryForm ={}
      // this.resetForm("form");
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryForm = {
        deptName:undefined,
      }
      // this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getData();
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // getDept(row.deptId).then(response => {
      //   this.form = response.data.depts[0];
      //   this.dialogFormVisible = true
      //   this.title = "修改部门";
      // });
      this.form = row
      this.dialogFormVisible = true
      this.title = "修改部门";
      this.form.parentId = row.parentId
      listDeptExcludeChild(row.deptId).then(response => {
	        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.dialogFormVisible = true
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.deptId;
      }
      this.title = "添加部门";
      listDept().then(response => {
	      this.deptOptions = response.data;
      });
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deptId != undefined) {
            this.form.children = ''
            if(this.form.parentId){
              let arr = ""
              for(let i=0;i<this.deptOptions.length;i++){
                if(this.deptOptions[i].parentId != this.form.parentId){
                  if(arr.indexOf(this.deptOptions[i].parentId)<0){
                    arr = arr +  this.deptOptions[i].parentId
                  }
                  if(this.deptOptions[i].children){
                    for(let a = 0; a<this.deptOptions[i].children.length;a++){
                      if(this.deptOptions[i].children[a].parentId != this.form.parentId){
                        if(arr.indexOf(this.deptOptions[i].children[a].parentId)<0){
                          arr = arr + "," + this.deptOptions[i].children[a].parentId
                        }
                        if(this.deptOptions[i].children[a].children){
                          for(let b = 0; b<this.deptOptions[i].children[a].children.length;b++){
                            if(this.deptOptions[i].children[a].children[b].parentId != this.form.parentId){
                              if(arr.indexOf(this.deptOptions[i].children[a].children[b].parentId)<0){
                                arr = arr + "," + this.deptOptions[i].children[a].children[b].parentId
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
              this.form.ancestors = arr
            }
            deptEdit(this.form).then(response => {
              if(response.status == "SUCCESS"){
                this.loading = false
                this.$message.success("修改成功")
                this.dialogFormVisible = false
                this.getData();
              }
            });
          } else {
            deptAdd(this.form).then(response => {
              if(response.status == "SUCCESS"){
                this.loading = false
                this.dialogFormVisible = false
                this.$message.success("添加成功")
                this.getData();
              }

            });
          }
        }
      });
    },





    handleEdit(index, row) {
      alert(index, row);
    },
    handleDelete(index, row) {
      this.$confirm("确定删除该部门吗?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
         deptRemove({deptId: row.deptId}).then(response => {
            if(response.status == "SUCCESS"){
              this.loading = false
              this.$message.success("删除成功")
              this.getData();
            }
          })
        }).catch(() => {
          this.$message.info("已取消删除")
        });
    },
    batchDelete() {
      let multData = this.multipleSelection;
      let tableData = this.tableData;
      let multDataLen = multData.length;
      let tableDataLen = tableData.length;
      for (let i = 0; i < multDataLen; i++) {
        for (let y = 0; y < tableDataLen; y++) {
          if (JSON.stringify(tableData[y]) == JSON.stringify(multData[i])) {
            //判断是否相等，相等就删除
            this.tableData.splice(y, 1);
          }
        }
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
  },
};
</script>
<style >
.el-dialog .el-form-item__label{
  line-height: 40px;
  padding-right:10px;
}
.el-input__prefix{
  top:4px;
}
.el-radio{
  margin-top:10px;
}
.el-tabs--border-card {
  background: rgba(0, 0, 0, 0);
  border: 1px solidrgba(0, 0, 0, 0);
  -webkit-box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0), 0 0 6px 0 rgba(0, 0, 0, 0);
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0), 0 0 6px 0 rgba(0, 0, 0, 0);
}
.el-tabs--border-card > .el-tabs__header {
  background-color: rgba(0, 0, 0, 0);
  position: relative;
  top: 12px;
  left: 14px;
  border-bottom: 0;
}
.el-tabs--border-card > .el-tabs__content {
  padding: 0;
}

.el-tabs--border-card > .el-tabs__header .el-tabs__item + .el-tabs__item,
.el-tabs--border-card > .el-tabs__header .el-tabs__item:first-child {
  background: #e4e3e3;

  -webkit-border-top-left-radius: 10px;
  -webkit-border-top-right-radius: 10px;
  color: #444;
}
.el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active {
  color: #fff;
  background-color: #5c88fa;
  border: 1px solid rgba(0, 0, 0, 0);
  border-right-color: rgba(0, 0, 0, 0);

  border-left-color: 0;
}
.el-tabs--border-card
  > .el-tabs__header
  .el-tabs__item:not(.is-disabled):hover {
  color: #fff;
  background-color: #5c88fa;
}
.el-tabs__item {
  height: 35px;
  line-height: 35px;
}


.roleDialog .el-dialog .el-form-item:first-child,
.roleDialog .el-dialog .el-form-item:nth-child(2) {
  display: inline-block;
}
.el-dialog .el-form-item.table-item {
  width: 96%;
}
.el-dialog .el-form-item{
  width:100%;
}



</style>


<style lang="scss" scoped>
//三级组织缩进
::v-deep .el-table__row--level-1 .el-table_1_column_1 .cell  {
  margin-left: 43% !important;
  text-align: left;
}
::v-deep .el-table__row--level-2  .el-table_1_column_1 .cell {
  margin-left: 47.5% !important;
  text-align: left;
}
@media screen and (max-width:1290px){
  ::v-deep .el-table__row--level-1 .el-table_1_column_1 .cell {
    margin-left: 37% !important;
  }
  ::v-deep .el-table__row--level-2 .el-table_1_column_1 .cell  {
    margin-left: 47.5% !important;
  }
}
</style>
