<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="4">
        <el-card class="box-card" shadow="always" :body-style="{ height: bodyHeight }" style="overflow-y: auto;">
          <tree
            :nodes="deptNodes"
            :setting="setting"
            @onCheck="onCheck"
            @onCreated="handleCreated"
          />
        </el-card>
      </el-col>
      <el-col :span="20">
        <el-card class="box-card" shadow="always" :body-style="{ height: bodyHeight }" style="overflow-y: auto;">
          <el-form :model="queryParams" ref="queryForm" :inline="true">
            <el-form-item label="用户名称" prop="username">
              <el-input
                v-model="queryParams.username"
                placeholder="请输入用户名称"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <template v-if="advanced">
              <el-form-item label="用户昵称" prop="nickname">
                <el-input
                  v-model="queryParams.nickname"
                  placeholder="请输入用户昵称"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </template>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              <el-button type="text" @click="toggleAdvanced">
                {{ advanced ? '收起' : '展开' }}
                <i
                  :class="{ 'el-icon-arrow-up': advanced, 'el-icon-arrow-down': !advanced }"
                ></i>
              </el-button>
            </el-form-item>
          </el-form>

          <el-row type="flex" justify="space-between">
            <el-col :span="12">
              <el-button-group>
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                  v-hasPerm="['system:user:add']"
                >新增</el-button>
                <el-button
                  type="success"
                  icon="el-icon-edit-outline"
                  size="mini"
                  :disabled="single"
                  @click="handleEdit"
                  v-hasPerm="['system:user:edit']"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleBatchDelete"
                  v-hasPerm="['system:user:remove']"
                >删除</el-button>
              </el-button-group>
            </el-col>
            <el-col :span="12">
              <div class="right-toolbar">
                <el-tooltip content="密度" effect="dark" placement="top">
                  <el-dropdown trigger="click" @command="handleCommand">
                    <el-button circle size="mini">
                      <svg-icon class-name="size-icon" icon-class="colum-height" />
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="medium">正常</el-dropdown-item>
                      <el-dropdown-item command="small">中等</el-dropdown-item>
                      <el-dropdown-item command="mini">紧凑</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-tooltip>
                <el-tooltip content="刷新" effect="dark" placement="top">
                  <el-button circle size="mini" @click="handleRefresh">
                    <svg-icon class-name="size-icon" icon-class="shuaxin" />
                  </el-button>
                </el-tooltip>
                <el-tooltip content="列设置" effect="dark" placement="top">
                  <el-popover placement="bottom" width="100" trigger="click">
                    <el-checkbox-group
                      v-model="checkedTableColumns"
                      @change="handleCheckedColsChange"
                    >
                      <el-checkbox
                        v-for="(item, index) in tableColumns"
                        :key="index"
                        :label="item.prop"
                      >{{ item.label }}</el-checkbox>
                    </el-checkbox-group>
                    <span slot="reference">
                      <el-button circle size="mini">
                        <svg-icon class-name="size-icon" icon-class="shezhi" />
                      </el-button>
                    </span>
                  </el-popover>
                </el-tooltip>
              </div>
            </el-col>
          </el-row>

          <el-table
            v-loading="loading"
            :data="userList"
            @selection-change="handleSelectionChange"
            border
            tooltip-effect="dark"
            :size="tableSize"
            :max-height="tableHeight"
            style="width: 100%;margin: 15px 0;"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" width="55" align="center">
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <template v-for="(item, index) in tableColumns">
              <el-table-column
                v-if="item.show"
                :prop="item.prop"
                :label="item.label"
                :key="index"
                :formatter="item.formatter"
                align="center"
                show-overflow-tooltip
              />
            </template>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit-outline"
                  @click="handleEdit(scope.row)"
                  v-hasPerm="['system:user:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPerm="['system:user:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum"
            :page-size="queryParams.pageSize"
            :total="total"
          ></el-pagination>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listUser } from '@/api/system/user'
import { listDept } from '@/api/system/dept'
import tree from 'vue-giant-tree'

export default {
  name: 'UserList',
  components: {
    tree
  },
  data () {
    return {
      bodyHeight: document.body.offsetHeight - 130 + 'px',
      tableHeight: document.body.offsetHeight - 230 + 'px',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 表格头
      tableColumns: [
        { prop: 'username', label: '用户名称', show: true },
        { prop: 'nickname', label: '用户昵称', show: true },
        { prop: 'email', label: '电子邮箱', show: true },
        { prop: 'phone', label: '手机号码', show: true },
        {
          prop: 'depts',
          label: '所属部门',
          show: true,
          formatter: this.deptFormatter
        },
        {
          prop: 'posts',
          label: '所属岗位',
          show: true,
          formatter: this.postFormatter
        },
        {
          prop: 'roles',
          label: '所属角色',
          show: true,
          formatter: this.roleFormatter
        },
        {
          prop: 'status',
          label: '状态',
          show: true,
          formatter: this.statusFormatter
        },
        { prop: 'createTime', label: '创建时间', show: true }
      ],
      // 默认选择中表格头
      checkedTableColumns: [],
      tableSize: 'medium',
      // 用户表格数据
      userList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        username: '',
        nickname: '',
        deptId: ''
      },
      // 高级搜索 展开/关闭
      advanced: false,
      // ztree树组件
      ztreeObj: null,
      setting: {
        check: {
          enable: true,
          chkStyle: 'radio',
          radioType: 'all'
        },
        data: {
          key: {
            name: 'deptName'
          },
          simpleData: {
            enable: true,
            idKey: 'id',
            pIdKey: 'parentId',
            rootPId: '0'
          }
        }
      },
      deptNodes: []
    }
  },
  created () {
    this.getList()
    this.getDeptList()
    this.initCols()
  },
  destroyed () {
    this.ztreeObj.destroy()
  },
  methods: {
    /** 查询用户列表 */
    getList () {
      this.loading = true
      listUser(this.queryParams).then(response => {
        const { data } = response
        this.userList = data.data
        this.total = data.totalPage
        this.loading = false
      })
    },
    /** 查询部门列表 */
    getDeptList () {
      listDept().then(response => {
        const { data } = response
        this.deptNodes = data
      })
    },
    initCols () {
      this.checkedTableColumns = this.tableColumns.map(col => col.prop)
    },
    handleCheckedColsChange (val) {
      this.tableColumns.forEach(col => {
        if (!this.checkedTableColumns.includes(col.prop)) {
          col.show = false
        } else {
          col.show = true
        }
      })
    },
    handleCommand (command) {
      this.tableSize = command
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.$refs['queryForm'].resetFields()
      this.ztreeObj.cancelSelectedNode()
      this.ztreeObj
        .getCheckedNodes(true)
        .forEach(node => this.ztreeObj.checkNode(node, false, false, false))
      this.handleQuery()
    },
    /** 刷新列表 */
    handleRefresh () {
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.$emit('showForm', undefined)
    },
    /** 修改按钮操作 */
    handleEdit (row) {
      this.$emit('showForm', row.id)
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      this.$confirm('选中数据将被永久删除, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      }).catch(() => {
      })
    },
    /** 批量删除按钮操作 */
    handleBatchDelete () {
      if (!this.ids.length) {
        this.$message({
          message: '请先选择需要操作的数据',
          type: 'warning'
        })
      }
      this.$confirm('选中数据将被永久删除, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      }).catch(() => {
      })
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.queryParams.pageNum = val
      this.getList()
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    deptFormatter (row, column, cellValue, index) {
      return row.depts.map(item => item.deptName).join(',')
    },
    roleFormatter (row, column, cellValue, index) {
      return row.roles.map(item => item.roleName).join(',')
    },
    postFormatter (row, column, cellValue, index) {
      return row.posts.map(item => item.postName).join(',')
    },
    statusFormatter (row, column, cellValue, index) {
      const status = row.status
      if (status === 0) {
        return <el-tag type="success">禁用</el-tag>
      } else {
        return <el-tag type="success">正常</el-tag>
      }
    },
    handleCreated (ztreeObj) {
      this.ztreeObj = ztreeObj
      this.ztreeObj.expandAll(true)
    },
    onCheck (event, treeId, treeNode) {
      this.queryParams.deptId = treeNode.id
      this.handleQuery()
    }
  }
}
</script>

<style lang="scss" scoped>
.right-toolbar {
  float: right;
}
</style>
