<template>
  <div class="dep-container">
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="部门列表" name="list">
        <el-table stripe ref="table" :height="tableHeight" v-loading="tableLoading"
                  :data="deptList.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                  border row-key="id">
          <el-table-column show-overflow-tooltip prop="id" label="ID" align="center" width="100"/>
          <el-table-column show-overflow-tooltip prop="sort" label="排序" align="center" width="100"/>
          <el-table-column show-overflow-tooltip prop="name" label="名称" align="center"/>
          <el-table-column show-overflow-tooltip prop="managerName" label="部门主管" align="center"/>
          <el-table-column show-overflow-tooltip prop="createUserName" label="添加人" align="center"/>
          <el-table-column show-overflow-tooltip prop="formatCreateTime" label="添加时间" align="center" width="160"/>
          <el-table-column v-if="isAdmin||(btnRule.filter(value=>value=='edit'||value=='drop'||value=='add').length>0)"
                           label="操作" width="180">
            <template slot-scope="scope">
              <el-tooltip v-if="isAdmin||btnRule.some(btn=>btn=='edit')" class="item" effect="dark" content="编辑"
                          placement="bottom">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleAddRole(scope.row)"/>
              </el-tooltip>
              <el-tooltip v-if="isAdmin||btnRule.some(btn=>btn=='drop')" class="item" effect="dark" content="删除"
                          placement="bottom">
                <el-button :loading="delBtnLoading" type="danger" size="mini" icon="el-icon-delete"
                           @click="handleDelete(scope.row)"/>
              </el-tooltip>
              <el-button v-if="scope.row.hasChild === 1&&(isAdmin||btnRule.some(btn=>btn=='add'))" type="primary"
                         size="mini" icon="el-icon-plus"
                         @click="addMenu(scope.row,1)" class="add">添加子级
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="page-current">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            prev-text="上一页"
            next-text="下一页"
            layout="total, prev, pager, next, jumper"
            style="display: inline-block;"
            background
            @current-change="handleCurrentChange"
            :total="count"/>
        </div>
      </el-tab-pane>
      <el-tab-pane v-if="isAdmin||btnRule.some(btn=>btn=='add')" label="添加部门" name="add">
        <el-form ref="ruleForm" v-loading="loading" :model="ruleForm" size="small" label-width="100px"
                 style="width: 50%">
          <el-form-item label="部门名称" prop="name" :rules="[{
                    required: true, message: '名称不能为空', trigger: 'blur'
                  },
                {min: 2, max: 20, message: '长度在2 到 20 个字符', trigger: 'blur'}]">
            <el-input maxlength="20" clearable v-model="ruleForm.name" size="small" placeholder="请输入部门名称"/>
          </el-form-item>
          <el-form-item label="上级部门">
            <el-cascader
              filterable
              placeholder="无"
              v-model="ruleForm.pid"
              ref="refHandle"
              :options="filterDepList"
              :props="{ checkStrictly: true ,value:'id',label:'name'}"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="部门主管">
            <el-select clearable filterable v-model="ruleForm.manager" size="small">
              <el-option v-for="item in options" :key="item.id" :label="item.username" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="有无子级">
            <el-switch v-model="ruleForm.hasChild" :active-value="1" :inactive-value="2" size="small"/>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number size="small" v-model="ruleForm.sort"></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-document-add" :loading="addBtnLoading" type="primary" size="small" @click="submitForm('ruleForm',1)">立即提交
            </el-button>
            <el-button icon="el-icon-back" size="small" @click="resetForm('ruleForm')">返回</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <!-- 编辑角色 -->
    <el-dialog @close="resetForm('ruleForm') ;addDialogVisible = false  " :close-on-press-escape="false" :close-on-click-modal="false" center :visible.sync="addDialogVisible" :title="dialogType==='edit'? '编辑部门' : '添加子级'">
      <el-form ref="ruleForm" v-loading="loading" :model="ruleForm" size="small" label-width="100px">
        <el-form-item label="部门名称" prop="name" :rules="[{
                    required: true, message: '名称不能为空', trigger: 'blur'
                  },
                {min: 2, max: 20, message: '长度在2 到 20 个字符', trigger: 'blur'}]">
          <el-input maxlength="20" clearable v-model="ruleForm.name" size="small" placeholder="请输入部门名称"/>
        </el-form-item>
        <el-form-item prop="pid" label="上级部门">
          <el-cascader
            :disabled="ruleForm.disable"
            placeholder="无"
            v-model="ruleForm.pid"
            ref="refHandle"
            :options="filterDepList"
            :props="{ checkStrictly: true ,value:'id',label:'name'}"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="部门主管">
          <el-select clearable filterable v-model="ruleForm.manager" size="small">
            <el-option v-for="item in options" :key="item.id" :label="item.username" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="有无子级">
          <el-switch v-model="ruleForm.hasChild" :active-value="1" :inactive-value="2" size="small"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number size="small" v-model="ruleForm.sort"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                      <el-button icon="el-icon-document-add"  :loading="addBtnLoading" type="primary" size="medium"
                                 @click="submitForm('ruleForm',ruleForm.disable?3:2)"
                      >提交
            </el-button>
            <el-button icon="el-icon-back" size="medium" @click="addDialogVisible = false ">取消</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
  import adminApi from '@/api/permission/admin'
  import depApi from '@/api/permission/dep'

  export default {
    name: "dep",
    data() {
      return {
        // 当前页
        currentPage: 1,
        // 总条数
        count: 0,
        // 每页条数
        pageSize: 10,
        tableLoading: true,
        // 显示编辑角色弹框
        addDialogVisible: false,
        dialogType: 'new',
        // 用户按钮权限
        btnRoles: [],
        activeName: 'list',
        deptList: [],
        delBtnLoading: false,
        addBtnLoading: false,
        ruleForm: {
          sort: 1,
          hasChild: 2,
          name: '',
          manager: '',
          pid: ''
        },
        options: [],
        roles: [],
        loading: false,
        tableHeight: document.body.clientHeight - 245,
        btnRule: [],
        isAdmin: false,
        filterDepList: []
      }
    },
    created() {
      this.pageSize = parseInt((document.body.clientHeight - 284) / 50)
      const {btnRule, isAdmin} = this.$store.state.user
      this.btnRule = btnRule
      this.isAdmin = isAdmin
    },
    watch: {
      activeName(val) {
        if (val == 'add') {
          this.initFilterList()
          this.initRuleForm()
        }
      }
    },
    mounted() {
      this.tableLoading = true
      this.getAllList()
      this.getAdminList()
    },
    methods: {
      handleCurrentChange(val) {
        this.currentPage = val
        this.$refs.table.bodyWrapper.scrollTop = 0;
      },
      initRuleForm() {
        this.ruleForm = {
          sort: 1,
          hasChild: 2,
          name: '',
          manager: '',
          pid: ''
        }
      },
      // 分页
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`)
      },
      findFilterList(list, id) {
        for (let i = list.length - 1; i >= 0; i--) {
          if (list[i].hasChild != 1 || list[i].id == id) {
            list.splice(i, 1)
          } else {
            if (list[i].children && list[i].children.length > 0) {
              this.findFilterList(list[i].children)
            }
          }
        }
      },
      initFilterList(id) {
        let filerList = JSON.parse(JSON.stringify(this.deptList))
        this.findFilterList(filerList, id)
        this.filterDepList = filerList
      },
      // 获取列表
      getAllList() {
        // 设置分页
        depApi.departList().then(res => {
          this.deptList = res.data
          this.count = res.data.length
          this.tableLoading = false
        }).catch(e => {
          this.count = 0
          this.deptList = []
          this.tableLoading = false
        })
      },
      getAdminList() {
        adminApi.getAdminList().then(res => {
          let options = res.data ? res.data : []
          this.options = options.filter(item => item.status == 1)
        }).catch(e => {
          this.options = []
        })
      },
      // 新增角色
      handleAddRole(data) {
        this.dialogType = 'edit'
        data.hasChild = data.hasChild
        let ruleForm = JSON.parse(JSON.stringify(data))
        if (ruleForm.pid) {
          ruleForm.pid = ruleForm.pid + ''
        }
        this.ruleForm = Object.assign({}, ruleForm)
        this.initFilterList(data.id)
        this.addDialogVisible = true
      },
      // 删除角色
      handleDelete(data) {
        this.$confirm('您确定要删除该部门吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delBtnLoading = true
          depApi.departDel({id: data.id}).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            this.delBtnLoading = false
            this.tableLoading = true
            this.getAllList()
          }).catch(e => {
            this.delBtnLoading = false
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 重置缓存
      resetCache(res) {
        alert('直接调用接口，给提示')
      },
      // 添加子级
      addMenu(data, type) {
        this.initRuleForm()
        this.initFilterList()
        this.$refs['ruleForm'].resetFields()
        this.addDialogVisible = true
        if (type) {
          this.ruleForm.pid = data.id ? data.id : 0
          this.ruleForm.disable = 1
        }
        this.dialogType = '添加子级'
      },
      submitForm(formName, type) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
            if (ruleForm.pid) {
              if (Array.isArray(ruleForm.pid) && ruleForm.pid.length > 0) {
                ruleForm.pid = ruleForm.pid[ruleForm.pid.length - 1]
              } else if (ruleForm.pid.length == 0) {
                ruleForm.pid = 0
              }
            } else {
              if (!ruleForm.pid) {
                ruleForm.pid = 0
              }
            }
            this.addBtnLoading = true
            if (type == 1 || type == 3) {
              depApi.departAdd(ruleForm).then(res => {
                this.addBtnLoading = false
                this.initRuleForm()
                this.$refs[formName].resetFields()
                if (type == 3) {
                  this.addDialogVisible = false
                }
                this.tableLoading = true
                this.$message({
                  type: 'success',
                  message: '添加成功！'
                })
                this.getAllList()
              }).catch(e => {
                this.addBtnLoading = false
              })
            } else {
              depApi.departEdit(ruleForm).then(res => {
                this.addBtnLoading = false
                this.initRuleForm()
                this.$refs[formName].resetFields()
                this.addDialogVisible = false
                this.tableLoading = true
                this.$message({
                  type: 'success',
                  message: '编辑成功！'
                })
                this.getAllList()
              }).catch(e => {
                this.addBtnLoading = false
              })
            }
          }
        })
      },
      resetForm(formName) {
        this.initRuleForm()
        this.$refs[formName].resetFields()
        this.activeName = 'list'
      }
    }
  }
</script>

<style lang="less">
  .dep-container {
    width: 100%;

    .page-current {
      text-align: center;
      padding: 15px 5px;
      padding-bottom: 0px;

      .sure-page-btn {
        display: inline-block;
        height: 28px;
        line-height: 0;
        width: 46px;
        padding: 0;
        vertical-align: top;
      }
    }
  }

</style>
