<template>
  <div class="sy-content">
    <el-row>
      <el-col :span="24">
        <!-- 表单查询 -->
        <el-form ref="queryForm" :model="queryParams" :inline="true" size="small">
          <el-form-item label="部门名称" prop="departmentName">
            <el-input v-model="queryParams.departmentName" placeholder="请输入部门名称" clear />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handelSearch">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="handelReset">重置</el-button>
          </el-form-item>
        </el-form>

        <el-button size="mini" icon="el-icon-plus" type="primary" plain @click="handelAdd">新增</el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-circle-close"
          size="mini"
          :disabled="multiple"
          @click="handelDelAll"
        >批量删除</el-button>

        <!-- 表格数据信息 -->
        <el-table
          ref="deptTable"
          v-loading="loading"
          :data="deptList"
          row-key="id"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            key="departmentName"
            label="部门名称"
            align="center"
            prop="departmentName"
            show-overflow-tooltip
          />
          <el-table-column
            key="departmentDescribe"
            label="部门描述"
            align="center"
            prop="departmentDescribe"
            show-overflow-tooltip
          />
          <el-table-column key="departmentNum" label="排序号" align="center" prop="departmentNum" />
          <el-table-column key="updateTime" label="更新时间" align="center" prop="updateTime" />
          <el-table-column key="createTime" label="创建时间" align="center" prop="createTime" />
          <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handelEdit(scope.row.id)">修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                :disabled="!multiple"
                @click="handelDel(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页信息 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.limit"
          align="right"
          @pagination="getDeptList"
        />
      </el-col>
    </el-row>

    <!-- 弹出框 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="600px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级部门" prop="parentId">
              <selectTree v-model="form.parentId" :options="options" placeholder="请选择上级部门" :key-name="keyName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="部门名称" prop="departmentName">
              <el-input v-model.trim="form.departmentName" clearable placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="部门描述" prop="departmentDescribe">
              <el-input v-model.trim="form.departmentDescribe" clearable placeholder="请输入部门描述" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="排序号" prop="departmentNum">
              <el-input
                v-model.trim="form.departmentNum"
                placeholder="请输入排序号"
                controls-position="right"
                :minlength="1"
                :maxlength="5"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="handelSubmit('form')">确定</el-button>
        <el-button size="mini" @click="handelCancel('form')">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDeptList, addDept, getDeptById, editDept, delDept, getAllSonMenuList } from '@/api/system/dept.js'
import selectTree from '@/components/SelectTree'
export default {
  components: { selectTree },
  data() {
    const departmentNum = (rule, value, callback) => {
      var reg = /^[1-9][0-9]*$/
      if (!value) {
        callback(new Error('排序号不能为空'))
      }
      if (!(reg.test(value))) {
        callback(new Error('只能输入正整数'))
      }
      callback()
    }
    return {
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10
      },
      // 总条数
      total: 0,
      // 表格数据
      deptList: [],
      // 弹出框
      dialogVisible: false,
      // 弹出框标题
      title: '',
      // 弹出框表单
      form: {
        parentId: 0
      },
      // 部门树数据
      options: [],
      // 表单验证
      rules: {
        departmentName: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' }
        ],
        departmentDescribe: [
          { required: true, message: '部门描述不能为空', trigger: 'blur' }
        ],
        departmentNum: [
          { required: true, validator: departmentNum, trigger: 'blur' }
        ]
      },
      // 修改菜单id
      id: null,
      // 控制批量删除按钮
      multiple: true,
      // 删除部门集合
      depts: [],
      // 自定义treeselect键名
      keyName: null
    }
  },
  created() {
    this.getDeptList()
  },
  methods: {
    /** 获取表格数据 */
    getDeptList() {
      getDeptList(this.queryParams).then(res => {
        if (res.code === 200) {
          const data = res.data
          this.deptList = data.departmentList
          this.total = data.count
          this.getOptionsList()
          this.loading = false
        }
      })
    },
    /** 获取上级部门 */
    getOptionsList() {
      getAllSonMenuList().then(res => {
        const data = res.data
        this.options = data
        this.keyName = 'departmentName'
      })
    },
    /** 搜索 */
    handelSearch(event) {
      this.$resetBtn(event)
      this.queryParams.page = 1
      this.getDeptList()
    },
    /** 重置按钮操作 */
    handelReset(event) {
      this.$refs['queryForm'].resetFields()
      this.handelSearch(event)
    },
    /** 新增按钮 */
    handelAdd() {
      this.dialogVisible = true
      this.title = '添加部门'
      this.reset()
    },
    /** 修改按钮 */
    handelEdit(id) {
      this.id = id
      getDeptById({ id }).then(res => {
        this.form = res.data
      })
      this.dialogVisible = true
      this.title = '修改部门'
    },
    /** 表格多选 */
    handleSelectionChange(val) {
      this.depts = val
      this.multiple = !val.length
    },
    /** 删除按钮 */
    handelDel(row) {
      this.$confirm('您确定要删除该部门吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'btn_custom_cancel',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        if (row.children.length) {
          this.$message({
            type: 'warning',
            message: '删除失败,请先删除下级部门'
          })
        } else {
          delDept([row.id]).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.getDeptList()
            }
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /** 批量删除 */
    handelDelAll() {
      this.$confirm('您确定要批量删除选中的部门吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'btn_custom_cancel',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        try {
          this.depts.forEach(o => {
            // 选中父级
            if (o.children.length) {
              this.$message({
                type: 'warning',
                message: '删除失败,请先删除下级部门'
              })
              throw Error()
            } else {
              const ids = this.depts.map(item => item.id)
              delDept(ids).then(res => {
                if (res.code === 200) {
                  this.$message({
                    type: 'success',
                    message: '删除成功'
                  })
                  this.getDeptList()
                }
              })
            }
          })
        } catch (error) {
          console.log(error)
        }
      }).catch(() => {
        this.$refs.deptTable.clearSelection()
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /** 表单提交 */
    handelSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === '添加部门') {
            addDept(this.form).then(res => {
              if (res.code === 200) {
                this.$message({
                  message: res.data,
                  type: 'success'
                })
                this.getDeptList()
                this.dialogVisible = false
              }
            })
          } else {
            this.form.id = this.id
            editDept(this.form).then(res => {
              if (res.code === 200) {
                this.$message({
                  message: res.data,
                  type: 'success'
                })
                this.getDeptList()
                this.dialogVisible = false
              }
            })
          }
        }
      })
    },
    /** 表单取消 */
    handelCancel() {
      this.dialogVisible = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      if (this.$refs['form']) {
        this.$refs['form'].resetFields()
      }
    }
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>

</style>
