<template>
  <div class="sy-content">
    <div>
      <el-row v-if="$route.meta.showRole">
        <el-col :span="12">
          <!-- 搜索信息 -->
          <el-form
            v-show="showSearch"
            ref="queryForm"
            :model="queryParams"
            size="small"
            :inline="true"
            label-width="80px"
          >
            <el-form-item label="" prop="roleName">
              <el-input
                v-model="queryParams.roleName"
                placeholder="请输入名称"
                prefix-icon="el-icon-search"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
              <el-button type="info" icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12">
          <!-- 操作按钮 -->
          <el-row class="czBtns" style="float: right;">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5" style="margin-left: 15px;">
              <el-button
                type="danger"
                size="small"
                :disabled="multiple"
                icon="el-icon-delete-solid"
                @click="handleDelete"
              >
                批量删除
              </el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row v-if="$route.meta.showRole">
        <el-col>
          <!-- 表格数据信息 -->
          <el-table
            ref="roleTable"
            v-loading="loading"
            :data="roleList"
            stripe
            border
            header-row-class-name="headBackground"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="left" />
            <el-table-column v-if="false" key="id" label="编号" align="left" prop="id" />
            <el-table-column key="roleName" label="名称" align="left" prop="roleName" :show-overflow-tooltip="true" />
            <el-table-column key="roleCode" label="权限字符" align="left" prop="roleCode" :show-overflow-tooltip="true" />
            <el-table-column label="操作" align="left" width="400" class-name="small-padding fixed-width">
              <template v-if="scope.row.userId !== 1" slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  :disabled="!multiple"
                  @click="handleDelete(scope.row)"
                >删除</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-user"
                  @click="handleAuthUser(scope.row)"
                >分配用户</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-menu"
                  @click="handleAuthMenu(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="getRoleList"
          />
        </el-col>
      </el-row>

      <!-- 添加或修改对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col>
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="form.roleName" placeholder="请输入名称" maxlength="20" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="权限字符" prop="roleCode">
                <el-input v-model="form.roleCode" placeholder="请输入权限字符" maxlength="20" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" size="mini" @click="submitForm">确定</el-button>
          <el-button size="mini" @click="cancel">取消</el-button>
        </div>
      </el-dialog>
    </div>
    <router-view />
  </div>
</template>

<script>
import { getRoleList, addRoleInfo, updateRoleInfo, delRolesById } from '@/api/system/role'

export default {
  name: 'Index',
  data() {
    // 添加角色名称验证
    const validatePass = (rule, value, callback) => {
      var reg = /^[^\s]{2,20}$/
      if (!(reg.test(value))) {
        callback(new Error('名称长度必须介于 2 和 20 之间 不能有空格'))
      }
      callback()
    }
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 非多个禁用
      multiple: true,
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        roleName: undefined,
        roleCode: undefined
      },
      // 总条数
      total: 0,
      // 用户表格数据
      roleList: null,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        roleName: null,
        roleCode: null
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: '名称不能为空', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        roleCode: [
          { required: true, message: '权限字符不能为空', trigger: 'blur' },
          { min: 5, max: 20, message: '权限字符长度必须介于 5 和 20 之间', trigger: 'blur' },
          { validator: this.testKey }
        ]
      }
    }
  },
  created() {
    if (this.$route.meta.showRole) {
      this.getRoleList()
    }
  },
  methods: {
    /** 表单验证判断只能输入数字和字母 */
    testKey(rule, value, callback) {
      const key = /^[\a-\z\A-\Z0-9]+$/
      if (!key.test(value)) {
        callback(new Error('只能输入数字和字母'))
      } else {
        callback()
      }
    },
    /** 搜索按钮操作 */
    handleQuery(event) {
      this.$resetBtn(event)
      this.queryParams.page = 1
      this.getRoleList()
    },
    /** 重置按钮操作 */
    resetQuery(event) {
      this.$refs['queryForm'].resetFields()
      this.handleQuery(event)
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    /** 查询用户列表 */
    getRoleList() {
      this.loading = true
      getRoleList(this.queryParams).then(response => {
        const data = response.data
        this.roleList = data.roleList
        this.total = data.count
        this.loading = false
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleId = row.id
      if (!roleId) {
        const roleIdList = this.ids
        if (!roleIdList || roleIdList.length === 0) {
          this.$message({
            message: '请选择您要删除的角色',
            type: 'warning'
          })
          return
        }
        this.$confirm('您确定要删除选中的角色吗？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'btn_custom_cancel',
          closeOnClickModal: false,
          type: 'warning'
        }).then(() => {
          if (this.roleList.length === roleIdList.length && this.queryParams.page > 1) {
            this.queryParams.page -= 1
          }
          this.delRolesById(roleIdList)
        }).catch(() => {
          this.$refs.roleTable.clearSelection()
        })
        return
      }
      this.$confirm('您确定要删除角色【' + row.roleName + '】吗？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'btn_custom_cancel',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        if (this.roleList.length === 1 && this.queryParams.page > 1) {
          this.queryParams.page -= 1
        }
        this.delRolesById([roleId])
      }).catch(() => {
      })
    },
    /** 删除角色请求 */
    delRolesById(ids) {
      delRolesById(ids).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '删除角色成功！',
            type: 'success'
          })
          this.getRoleList()
        }
      }).catch(() => {
        this.$refs.roleTable.clearSelection()
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.form = {
        id: row.id,
        roleName: row.roleName,
        roleCode: row.roleCode
      }
      this.open = true
      this.title = '修改角色'
    },
    /** 分配角色人员 */
    handleAuthUser(row) {
      const roleId = row.id
      this.$router.push({
        path: '/system/role/role-auth',
        query: {
          id: roleId
        }
      })
    },
    /** 分配角色菜单 */
    handleAuthMenu(row) {
      const roleId = row.id
      this.$router.push({
        path: '/system/role/role-menu',
        query: {
          id: roleId
        }
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增角色'
    },
    /** 表单提交 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateRoleInfo(this.form).then(response => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.open = false
              this.getRoleList()
            })
          } else {
            addRoleInfo(this.form).then(response => {
              this.$message({
                message: '新增成功',
                type: 'success'
              })
              this.open = false
              this.getRoleList()
            })
          }
        }
      })
    },
    /** 表单重置 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        roleName: undefined,
        roleCode: undefined
      }
      if (this.$refs['form']) {
        this.$refs['form'].resetFields()
      }
    }
  }
}
</script>

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

</style>
