<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button type="danger" size="mini" icon="el-icon-circle-plus-outline" @click="addRoleDialog">新增</el-button>
      <!-- <el-button type="info" size="mini" icon="el-icon-delete">删除</el-button> -->
    </div>
    <el-table :data="roleData" style="width: 100%" header-row-class-name="">
      <el-table-column type="selection" width="55"></el-table-column>
      <!--<el-table-column prop="identityType" label="身份">
        <template slot-scope="scope">{{ userLevel.get(parseInt(scope.row.identityType)) }}
        </template>
      </el-table-column>-->
      <el-table-column prop="name" label="角色名"></el-table-column>
      <el-table-column prop="describe" label="描述"></el-table-column>
      <!--<el-table-column label="状态" width="150">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-color="#13ce66" inactive-color="#ff4949" :active-value="true"
                     :inactive-value="false" @change="openOrClose(scope.row.id,scope.row.status)"></el-switch>
        </template>
      </el-table-column>-->
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="openDetailsRoleDialog(scope.row)"><i class="el-icon-more"></i>详情</el-button>
          <el-button type="text" size="small" @click="openRoleDialog(scope.row)"><i class="el-icon-edit"></i>修改</el-button>
           <el-button type="text" size="small" @click="deleteRole(scope.row.id)"><i class="el-icon-delete"></i>移除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total,  prev, pager, next, sizes, jumper"
        :total="total">
    </el-pagination>
    <el-dialog :title="isEdit?'修改':'新增'" :visible.sync="dialogAddRoleVisible" width="500px" @close="resetForm('ruleForm')">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <!--<el-form-item label="身份：" :label-width="formLabelWidth" prop="identityId">
          <el-select v-if="identityId=='1'" v-model="form.identityId" placeholder="请选择身份（必填）" style="width:230px;">
            <el-option label="系统用户" :value="1"></el-option>
            <el-option label="公众用户" :value="2"></el-option>
            <el-option label="企业用户" :value="3"></el-option>
            <el-option label="政府用户" :value="4"></el-option>
          </el-select>
          <span v-else>{{ userLevel.get(parseInt(form.identityId)) }}</span>
        </el-form-item>-->
        <el-form-item label="角色名：" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off" placeholder="请输入角色名（必填）"></el-input>
        </el-form-item>
        <el-form-item label="描述：" :label-width="formLabelWidth" prop="describe">
          <el-input v-model="form.describe" autocomplete="off" placeholder="请输入角色名（必填）"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" size="mini" @click="submitForm('ruleForm')">保存</el-button>
        <el-button type="info" size="mini" @click="resetButton('ruleForm')">重置</el-button>
      </div>
    </el-dialog>
    <el-dialog title="详情" :visible.sync="dialogDetailsRoleVisible" width="500px" @close="resetForm('ruleForm')">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="角色名：" :label-width="formLabelWidth" prop="name">
          <span>{{ form.name }}</span>
        </el-form-item>
        <el-form-item label="描述：" :label-width="formLabelWidth" prop="describe">
          <span>{{ form.describe }}</span>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {getRoleList, getRoleInfo, addRole, editRole, deleteRole,existsRoleName} from "@/api/role"

export default {
  name: "roleManage",
  data() {
    const checkRoleName = (rule, value, callback) => {
      if(value){
        const params={
          id:this.form.id,
          name: this.form.name,
        }
        existsRoleName(params).then(res => {
          callback()
        }).catch(err => {
          return callback(new Error(err.msg));
        })
      }else{
        callback()
      }
      /*if (validateChinese(value)) {
        return callback(new Error('用户名不可为中文'));
      } else {
        if (!this.isEdit) {
          existsRoleName({name: this.form.name}).then(res => {
            callback()
          }).catch(err => {
            return callback(new Error(err.msg));
          })
        } else {
          callback()
        }
      }*/

    };
    return {
      currentPage: 1,                      //当前页
      pageSize: 10,                        //每页条数
      total: 0,                            //总条数
      formLabelWidth: '130px',            //form表单的lable宽度
      //identityId: this.$store.getters.identity || '',   //用户级别
      form: {                              //form表单数据
        /*identityId: '',
        rName: '',*/
        id:0,//0是新增
        name: "",
        describe: "",
        version: "",
      },
      rules: {                            //form表单校验
        /*identityId: [
          {required: true, message: '请选择身份', trigger: 'blur'}
        ],*/
        /*rName: [
          {required: true, message: '请输入角色名', trigger: 'blur'},
          {min: 2, max: 10, message: '角色名长度在2~10字符之间', trigger: 'blur'},
        ],*/
        name: [
          {required: true, message: '请输入角色名', trigger: 'blur'},
          {min: 2, max: 10, message: '角色名长度在2~10字符之间', trigger: 'blur'},
          {validator: checkRoleName, trigger: 'blur'}
        ],
        describe: [
          {required: true, message: '请输入描述', trigger: 'blur'},
          {min: 2, max: 10, message: '描述长度在2~10字符之间', trigger: 'blur'},
        ]
      },
      roleData: [],                       //角色列表校验
      /*userLevel: new Map([                 //身份键值对
        [1, '系统用户'],
        [2, '公众用户'],
        [3, '企业用户'],
        [4, '政府用户']
      ]),*/
      isEdit: false,//判断是新增还是修改
      isDetails: false,//判断是详情
      dialogAddRoleVisible: false,//新增、修改dialog
      dialogDetailsRoleVisible: false,//详情dialog
    };

  },
  mounted() {
    this.initData()
  },
  methods: {
    //初始化数据
    initData() {
      const params = {
        page: this.currentPage,
        size: this.pageSize
      }
      getRoleList(params).then(res => {
        if (res.data) {
          this.roleData = res.data.roleList
          this.total = res.data.count
        }
      })
    },
    //开启关闭
    /*openOrClose(id, status) {
      deleteRole({'id': id, 'status': status ? 1 : 0}).then(res => {
        this.$message({
          message: res.msg,
          type: res.code == 200 ? 'success' : 'error'
        });
        this.initData()
      }).catch(err => {
        this.initData()
      })
    },*/
    //删除角色
    deleteRole(id) {
      this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole({id: id}).then(res => {
          this.$message({
            message: res.msg,
            type: res.code == 200 ? 'success' : 'error'
          });
          this.initData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //打开新增dialog
    addRoleDialog() {
      this.isEdit = false
      this.dialogAddRoleVisible = true
      /*if (this.identityId != '1') {
        this.form.identityId = this.identityId
      }*/
    },
    //打开修改dialog,并传递数据
    openRoleDialog(row) {
      this.form.id = row.id
      this.form.name = row.name
      this.form.describe = row.describe
      this.form.version = row.version
      this.isEdit = true
      this.dialogAddRoleVisible = true
      /*getRoleInfo({id: id}).then(res => {
        this.form.identityId = parseInt(res.data.identityType)
        this.form.rName = res.data.name
        this.form.id = res.data.id
        this.form.rid = res.data.rid
        this.form.version = res.data.version
      })*/
    },
    //打开详情dialog,并传递数据
    openDetailsRoleDialog(row) {
      this.form.id = row.id
      this.form.name = row.name
      this.form.describe = row.describe
      this.form.version = row.version
      this.isDetails = true
      this.dialogDetailsRoleVisible = true
    },
    //添加角色
    addRoleInfo() {
      addRole(this.form).then(res => {
        this.$message({
          message: '添加成功！',
          type: 'success'
        });
        this.dialogAddRoleVisible = false
        this.initData()
        this.resetForm('ruleForm')
      })
    },
    //修改角色
    editRoleInfo() {
      editRole(this.form).then(res => {
        this.$message({
          message: '修改成功！',
          type: 'success'
        });
        this.dialogAddRoleVisible = false
        this.initData()
        this.resetForm('ruleForm')
      })
    },
    //form表单校验
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            this.editRoleInfo()
          } else {
            this.addRoleInfo()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //form重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.form.id = 0
      this.form.name = ''
      this.form.describe = ''
      this.form.version = ''
    },
    //重置按钮
    resetButton(formName) {
      this.$refs[formName].resetFields();
      this.form.name = ''
      this.form.describe = ''
    },
    //每页条数变化
    handleSizeChange(val) {
      this.pageSize = val
      this.initData()
    },
    //当前页变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.initData()
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.el-input {
  width: 230px;
}
</style>
