<template>
  <div>
    <el-row :gutter="20">
      <el-col :xs="24" :sm="7" :md="6" :lg="5" :xl="4">
        <el-card class="custom-menu box-card">
          <div slot="header">
            <span>组织分类</span>
          </div>
          <el-input
            v-model="filterText"
            placeholder="输入关键字进行过滤"
            style="margin-bottom: 20px"
          />
          <el-tree
            ref="tree"
            :data="organizationList"
            :props="defaultProps"
            node-key="id"
            default-expand-all
            :filter-node-method="filterNode"
            highlight-current
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node }">
              <span> {{ node.label }}</span>
            </span>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="17" :md="18" :lg="19" :xl="20">
        <el-card class="no-bottom">
          <el-form
            ref="searchForm"
            :model="searchForm"
            label-width="80px"
            inline
          >
            <el-form-item
              label="真实姓名:"
              prop="realName"
            >
              <el-input v-model="searchForm.realName" />
            </el-form-item>
            <el-form-item
              label="角色:"
              prop="roleId"
            >
              <el-select v-model="searchForm.roleId" placeholder="请选择">
                <el-option label="全部" :value="null" />
                <el-option-group
                  v-for="group in roleList"
                  :key="group.label"
                  :label="group.tenantName"
                >
                  <el-option
                    v-for="item in group.roles"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id"
                  />
                </el-option-group>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="getUserList(1)">查询</el-button>
              <el-button icon="el-icon-refresh" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="margin-top-20">
          <div class="buttons-group" style="margin-bottom: 20px">
            <el-button v-permission="'UserMgr_add'" type="primary" icon="el-icon-plus" @click="addUser">增加用户</el-button>
          </div>

          <el-table :data="tableData" border>
            <el-table-column
              type="index"
              label="序号"
              width="50px"
              align="center"
            />
            <el-table-column
              prop="account"
              label="账号"
            />
            <el-table-column
              prop="realName"
              label="真实姓名"
            />
            <el-table-column
              prop="mobile"
              label="手机号"
            />
            <el-table-column
              prop="departmentName"
              label="所属部门"
            />
            <el-table-column
              prop="roleName"
              label="角色"
            />
            <el-table-column
              prop="status"
              label="状态"
              :formatter="formatterStatus"
            />
            <el-table-column
              label="操作"
              width="140px"
              align="center"
            >
              <template slot-scope="props">
                <el-button
                  v-permission="'UserMgr_update'"
                  type="text"
                  @click="editUser(props.row)"
                >编辑</el-button>
                <el-popconfirm
                  v-permission="'UserMgr_delete'"
                  title="确定要删除此条记录吗？"
                  @onConfirm="deleteUser(props.row.id)"
                >
                  <el-button
                    slot="reference"
                    v-permission="'UserMgr_delete'"
                    type="text"
                    :disabled="!props.row.canEdited"
                  >删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            style="margin-top: 20px;text-align: right"
            :current-page="pageForm.pageNum"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageForm.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageForm.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-col>
    </el-row>

    <el-dialog
      :title="(add) ? '增加用户' : '编辑用户'"
      :visible.sync="dialogVisible"
      width="600px"
    >
      <el-form
        ref="userForm"
        :model="userForm"
        label-width="90px"
        :rules="userFormRules"
      >
        <el-form-item label="账号:" prop="account">
          <el-input v-model="userForm.account" :disabled="!add" />
        </el-form-item>
        <el-form-item label="姓名:" prop="realName">
          <el-input v-model="userForm.realName" :disabled="!userForm.canEdited" />
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input v-model="userForm.mobile" />
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="所属部门:" prop="departmentId">
          {{ (currentDepartment !== null ) ? currentDepartment.departmentName : null }}
        </el-form-item>
        <el-form-item v-if="add" label="初始密码:" prop="password">
          <el-input v-model="userForm.password" />
        </el-form-item>
        <el-form-item v-if="!add" label="新密码:">
          <el-input v-model="userForm.password" />
          <div>如果不更改密码，此处请留空</div>
        </el-form-item>
        <el-form-item label="角色:" prop="roleId">
          <el-select
            v-model="userForm.roleId"
            multiple
            placeholder="请选择"
            style="width: 100%"
            :disabled="!userForm.canEdited"
          >
            <el-option-group
              v-for="group in roleList"
              :key="group.label"
              :label="group.tenantName"
            >
              <el-option
                v-for="item in group.roles"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              />
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="状态:" prop="status">
          <el-radio-group v-model="userForm.status" :disabled="!userForm.canEdited">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">锁定</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listTree } from '@/api/system-management/organization-management'
import { addUser, updateUser, getUserList } from '@/api/system-management/user-management'
import { getAllRoleCategoryList } from '@/api/system-management/auth-management'
import md5 from 'md5'
import { validUserName } from '@/utils/validate'

export default {
  name: 'UserManagement',
  data() {
    const validatePass = (rule, value, callback) => {
      if (!validUserName(value)) {
        callback(new Error('仅可输入字母和数字'))
      } else {
        callback()
      }
    }
    return {
      searchForm: {
        realName: null,
        roleId: null
      },
      tableData: [],
      organizationList: [],
      defaultProps: {
        children: 'children',
        label: 'departmentName'
      },
      currentDepartment: null,
      filterText: null,
      dialogVisible: false,
      userForm: {
        account: null,
        password: null,
        departmentId: null,
        realName: null,
        roleId: null,
        email: null,
        status: 1,
        mobile: null,
        canEdited: null
      },
      userFormRules: {
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: validatePass, trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      },
      roleList: [],
      add: true,
      currentUser: {
        id: null
      },
      pageForm: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    listTree({ parentId: 0 })
      .then(res => {
        const { data } = res
        this.organizationList = data
        if (data.length > 0) {
          this.currentDepartment = data[0]
          this.$nextTick()
            .then(_ => this.$refs.tree.setCurrentKey(this.currentDepartment.id))
            .catch(_ => {})
          this.getUserList(1)
        }
      })
      .catch(err => {
        this.$message.error('操作失败')
        console.error(err.message)
      })
  },
  methods: {
    formatterStatus(row, column, cellValue) {
      return (cellValue === 1) ? '正常' : '锁定'
    },
    getUserList(pageNum) {
      const params = {
        current: pageNum,
        size: this.pageForm.pageSize,
        realName: this.searchForm.realName,
        roleId: this.searchForm.roleId,
        departmentId: this.currentDepartment.id
      }
      getUserList(params)
        .then(res => {
          const { records, total } = res.data
          this.tableData = records
          this.pageForm.total = total
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    handleSizeChange(val) {
      this.pageForm.pageSize = val
      this.getUserList(1)
    },
    handleCurrentChange(val) {
      this.pageForm.pageNum = val
      this.getUserList(val)
    },
    resetForm() {
      this.$refs.searchForm.resetFields()
    },
    saveUser() {
      this.$refs.userForm.validate()
        .then(_ => {
          const { account, password, realName, email, mobile, roleId, status } = this.userForm
          const params = {
            account,
            departmentId: this.currentDepartment.id,
            realName,
            email,
            mobile,
            roleId: roleId.join(','),
            status
          }
          if (password !== null) {
            params.password = md5(password)
          }
          if (this.add) {
            addUser(params)
              .then(res => {
                this.$message.success('操作成功')
                this.dialogVisible = false
                this.getUserList(1)
              })
              .catch(err => {
                this.$message.error(err.message)
                console.error(err.message)
              })
          } else {
            params.id = this.currentUser.id
            updateUser(params)
              .then(res => {
                this.$message.success('操作成功')
                this.dialogVisible = false
                this.getUserList(this.pageForm.pageNum)
              })
              .catch(err => {
                this.$message.error(err.message)
                console.error(err.message)
              })
          }
        })
        .catch(_ => {})
    },
    addUser() {
      this.userForm = {
        account: null,
        password: null,
        departmentId: null,
        realName: null,
        roleId: null,
        email: null,
        status: 1,
        mobile: null,
        canEdited: true
      }
      getAllRoleCategoryList({ departmentId: this.currentDepartment.id })
        .then(res => {
          const { data } = res
          this.roleList = data
          this.dialogVisible = true
          this.add = true
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    editUser(row) {
      this.currentUser = row
      const { account, departmentId, realName, email, mobile, roleId, status, canEdited } = row
      this.userForm = {
        account,
        password: null,
        departmentId,
        realName,
        email,
        mobile,
        status,
        roleId: (roleId !== null) ? roleId.split(',').map(v => parseInt(v)) : null,
        canEdited
      }
      getAllRoleCategoryList({ departmentId: this.currentDepartment.id })
        .then(res => {
          const { data } = res
          this.roleList = data
          this.dialogVisible = true
          this.add = false
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    deleteUser() {},
    filterNode(value, data) {
      if (!value) return true
      return data.departmentName.indexOf(value) !== -1
    },
    tagType(data) {
      const typeName = {
        '1': 'danger',
        '2': '',
        '3': 'success'
      }
      return typeName[data.category]
    },
    tagName(data) {
      const tagName = {
        '1': '集团',
        '2': '分公司',
        '3': '部门'
      }
      return tagName[data.category]
    },
    handleNodeClick(data, node) {
      this.currentDepartment = data
      this.getUserList(1)
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath)
    }
  }
}
</script>

<style scoped lang="scss">
  .custom-menu .el-menu{
    border-right: none;
  }
  .box-card{
    ::v-deep .el-card__body{
      min-height: calc(100vh - 150px);
    }
  }

</style>
