<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" type="primary" icon="el-icon-circle-plus-outline"
            v-if="checkPermission(['administratorManage:add'])" @click="handleAddAdmin">添加</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" placeholder="请输入关键字" @advancedSearch="advancedSearchEvent" advanced>
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                <el-form-item label="状态">
                  <el-select v-model="advancedForm.user_state">
                    <el-option :key="0" label="正常" :value="0" />
                    <el-option :key="-1" label="删除" :value="-1" />
                  </el-select>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column prop="username" label="登录名" />
        <el-table-column prop="real_name" label="用户名" />
        <el-table-column prop="nickname" label="用户昵称" />
        <el-table-column prop="sn" label="用户编码" />
        <el-table-column prop="dept_name" label="部门" />
        <el-table-column prop="post_name" label="岗位" />
        <el-table-column prop="user_state" label="状态">
          <template slot-scope="scope">
            {{ scope.row.user_state === 0 ? '正常' : '删除' }}
          </template>
        </el-table-column>
        <el-table-column prop="role_name" label="所属角色" />
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" v-if="checkPermission(['administratorManage:edit'])"
              @click="handleEditAdmin(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger"
              v-if="scope.row.user_state === 0 && checkPermission(['administratorManage:del'])"
              @click="handleDeleteAdmin(scope.$index, scope.row)">删除</el-button>
            <el-button size="mini" type="success"
              v-if="scope.row.user_state !== 0 && checkPermission(['administratorManage:restore'])"
              @click="handleRestoreAdmin(scope.$index, scope.row)">恢复</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>
    <el-dialog :title="adminForm.id ? '编辑人员' : '添加人员'" :visible.sync="dialogVisible" width="500px"
      @open="handleDialogOpen" :modal-append-to-body="false" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="adminForm" :rules="adminRules" ref="adminForm" label-width="120px">
        <el-form-item label="用户姓名" prop="real_name">
          <el-input v-model="adminForm.real_name" :minlength="2" :maxlength="20" clearable
                    placeholder="请输入用户姓名"></el-input>
        </el-form-item>
        <el-form-item label="用户编码" prop="sn">
          <el-input v-model="adminForm.sn" :maxlength="20" clearable placeholder="请输入用户编码"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="adminForm.nickname" :maxlength="20" clearable placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="登录名" prop="username">
          <el-input v-model="adminForm.username" :maxlength="20" clearable placeholder="请输入登录名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" autocompete="off" v-model="adminForm.password" :maxlength="20" clearable
            :placeholder="adminForm.id ? '不修改请留空' : '6-20位数字、英文字母，或者特殊字符'"></el-input>
        </el-form-item>
        <el-form-item label="所属角色" prop="role_id">
          <el-select v-model="adminForm.role_id" :disabled="adminForm.founder === 1"
            :placeholder="adminForm.founder === 1 ? '超级管理员无须选择角色' : '请选择角色'" clearable>
            <el-option v-for="item in rolesOptions" :key="item.role_id" :label="item.role_name" :value="item.role_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="dept_id">
          <el-cascader v-model="adminForm.dept_id" :options="deptList" :props="{
            label: 'name',
            value: 'id',
            emitPath: false,
            checkStrictly: true
          }" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="所属岗位" prop="post_id">
          <el-select v-model="adminForm.post_id">
            <el-option v-for="item in postList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAdminForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as API_Auth from '@/api/auth'
import * as API_Setting from '@/api/setting'
import md5 from 'js-md5'
import { RegExp, Foundation } from '~/ui-utils'
export default {
  name: 'administratorManage',
  data() {
    return {
      deptList: [],
      postList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10,
        user_state: 0
      },
      // 列表数据
      tableData: '',
      // 人员表单
      adminForm: {},
      advancedForm: {
        user_state: 0
      },
      // 人员表单 规则
      adminRules: {
        username: [
          this.MixinRequired('请输入人员名称！'),
          { min: 2, max: 20, message: '长度在 2 到 20 个字符' },
          {
            validator: (rule, value, callback) => {
              if (value && !RegExp.userName.test(value)) {
                callback(new Error('只支持汉字、字母、数字、“-”、“_”的组合！'))
              } else {
                callback()
              }
            }
          }],
        password: [
          { required: true, message: '请输入人员密码！', trigger: 'bulr' },
          {
            validator: (rule, value, callback) => {
              if (value && !RegExp.password.test(value)) {
                callback(new Error('密码应为6-20位数字、英文字母，或者特殊字符！'))
              } else {
                callback()
              }
            }
          }
        ],
        department: [this.MixinRequired('请输入所属部门！')],
        role_id: [{ required: true, message: '请选择所属角色！', trigger: 'change' }],
        face: [this.MixinRequired('请上传人员头像！')]
      },
      // 人员表单 dialog
      dialogVisible: false,
      // 角色列表
      rolesOptions: [],
      /** 存储上传的图片*/
      fileList: []
    }
  },
  watch: {
    'adminForm.id': function(newValue) {
      this.adminRules.username[0].required = !newValue
      this.adminRules.password[0].required = !newValue
    },
    'adminForm.founder': function(newValue) {
      this.adminRules.role_id[0].required = newValue === 0
      if (newValue === 1) this.adminForm.role_id = '超级人员'
    },
    dialogVisible: function(newVal) {
      if (!newVal) {
        this.fileList = []
      }
    }
  },
  mounted() {
    this.GET_AdministratorList()
    // 获取角色
    API_Auth.getRoleList({ page_size: 10000 }).then(response => {
      this.rolesOptions = response.data
    })
    this.GET_DeptList()
    this.GET_StationAllList()
  },
  methods: {
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      delete this.params.start_time
      delete this.params.end_time
      if (this.advancedForm.Contract_time_range) {
        this.params.start_time = parseInt(Number(this.advancedForm.Contract_time_range[0]) / 1000)
        this.params.end_time = parseInt(Number(this.advancedForm.Contract_time_range[1]) / 1000)
      }
      delete this.params.Contract_time_range
      this.params.page_no = 1
      this.GET_AdministratorList()
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    /** 获取岗位 */
    GET_StationAllList() {
      API_Setting.getStationAllList().then(response => {
        this.postList = response
      })
    },
    uploadSuccess(res) {
      this.$set(this.adminForm, 'face', res.url)
      this.$refs.faceImage.clearValidate()
    },
    /** 图片移除之后 */
    delGiftImg() {
      this.fileList = []
      this.adminForm.face = ''
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_AdministratorList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_AdministratorList()
    },

    /** 添加人员 */
    handleAddAdmin() {
      this.adminForm = {
        founder: 0,
        real_name: '',
        password: ''
      }
      this.fileList = []
      this.dialogVisible = true
    },

    /** 编辑人员 */
    handleEditAdmin(index, row) {
      this.adminForm = this.MixinClone(row)
      parseInt(this.adminForm.role_id) === 0 ? this.adminForm.role_id = '超级人员' : null
      this.fileList = this.adminForm.face ? [{ name: 'face', url: this.adminForm.face }] : []
      this.dialogVisible = true
    },
    handleRestoreAdmin(index, row) {
      API_Auth.restoreAdministrator(row.id).then(() => {
        this.$message.success('删除成功！')
        this.GET_AdministratorList()
      })
    },
    /** 删除人员 */
    handleDeleteAdmin(index, row) {
      this.$confirm('确定要删除这个人员吗？', '提示', { type: 'warning' }).then(() => {
        API_Auth.deleteAdministrator(row.id).then(() => {
          this.$message.success('删除成功！')
          this.GET_AdministratorList()
        })
      }).catch(() => { })
    },
    /** dialog打开后重置form表单校验结果 */
    handleDialogOpen() {
      setTimeout(() => { this.$refs['adminForm'].clearValidate() })
    },

    /** 提交人员表单 */
    submitAdminForm() {
      this.$refs['adminForm'].validate((valid) => {
        if (valid) {
          const { id } = this.adminForm
          const params = this.MixinClone(this.adminForm)
          if (params.password) params.password = md5(params.password)
          if (!params.real_name) delete params.real_name
          params.role_id === '超级人员' ? params.role_id = 0 : null
          if (id) {
            API_Auth.editAdministrator(id, params).then(response => {
              this.dialogVisible = false
              this.$message.success('修改成功！')
              this.GET_AdministratorList()
            })
          } else {
            API_Auth.addAdministrator(params).then(() => {
              this.dialogVisible = false
              this.$message.success('添加成功！')
              this.GET_AdministratorList()
            })
          }
        } else {
          this.$message.error('表单填写有误，请核对！')
          return false
        }
      })
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        keyword: data
      }
      this.params.page_no = 1
      this.GET_AdministratorList()
    },

    /** 获取人员列表 */
    GET_AdministratorList() {
      this.loading = true
      API_Auth.getAdministratorList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
