<template>
  <div class="permissionsPage H100">
    <div class="head_box">
      <h6>系统管理&nbsp;/&nbsp;权限管理</h6>
      <h4>权限管理</h4>
    </div>
    <div class="content_box">
      <div class="form_box h778px" >
        <el-form :inline="true" :model="form" class="search-form" onsubmit="return false;">
          <el-form-item label="">
            <el-input size="mini"  placeholder="请输入权限名称"  v-model="form.name" @keyup.enter.native="Search" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="mini"  type="primary" class="btn_form_search" @click="Search">查询</el-button>
          </el-form-item>
          <el-form-item class="r-float">
            <el-button size="mini" type="primary" class="btn_form_add" icon="el-icon-plus" @click="addPermis()">新&nbsp;&nbsp;&nbsp;建</el-button>
            <el-dropdown >
              <el-button style="margin-left: 10px;" size="mini" class="btn_form_add">批量操作</el-button>
              <el-dropdown-menu slot="dropdown" >
                <el-dropdown-item @click.native="multipleDelete">批量删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-form-item>
        </el-form>
        <div class="scrool">
          <el-table style="width:100%;" ref="multipleTable"  :data="tableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column show-overflow-tooltip label="权限名称" prop="name"  ></el-table-column>
          <el-table-column show-overflow-tooltip label="地址" prop="url" ></el-table-column>
          <el-table-column label="操作"  header-align="center" align="center" >
            <template slot-scope="scope" width="200">
              <el-button-group>
                <el-button title="编辑" size="mini" type="text" @click="openEdit(scope.row)">编辑&nbsp;|&nbsp;</el-button>
                <el-button title="删除" type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
        </div>
        <el-pagination small background
                       @current-change="handleCurrentChange"
                       :current-page="page.currentPage"
                       :page-size="page.pageSize"
                       layout="prev, pager, next"
                       :total="page.total">
        </el-pagination>
      </div>
      <!--新增弹框-->
      <el-dialog title="新建" class="newPermis" :visible.sync="FormVisible1"  :before-close="close1">
        <div class="form_box">
          <el-form :model="permisform"  ref="permisform"  :rules="rules" label-position="left">
            <el-form-item label="权限名称：" prop="name" :label-width="formLabelWidth">
              <el-input v-model="permisform.name" size="small" clearable auto-complete="off" placeholder="请输入您的权限名称"
                        onkeyup="this.value=this.value.replace(/^ +| +$/g,'')"></el-input>
            </el-form-item>
            <el-form-item label="地址：" prop="url" :label-width="formLabelWidth">
              <el-input v-model="permisform.url" size="small" clearable auto-complete="off" placeholder="请输入您的权限地址"
                        onkeyup="this.value=this.value.replace(/^ +| +$/g,'')"></el-input>
            </el-form-item>
            <el-form-item label="父级权限：" prop="pid" :label-width="formLabelWidth">
              <el-select v-model="permisform.pid" size="small" clearable value-key="name" placeholder="请选择权限" >
                <el-option v-for="item in typeList"   :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button class="r-float" size="mini" type="primary" @click="permisSave">确定</el-button>
            <el-button class="r-float" size="mini" @click="close1">取消</el-button>
          </div>
        </div>
      </el-dialog>
      <!--编辑弹框-->
      <el-dialog title="编辑" :visible.sync="FormVisible"  :before-close="close">
        <div class="form_box">
          <el-form :model="editform"  ref="editform"  :rules="rules"  >
            <el-form-item label="权限名称：" prop="name" :label-width="formLabelWidth" >
              <el-input v-model="editform.name" size="small" clearable auto-complete="off"  onkeyup="this.value=this.value.replace(/^ +| +$/g,'')"></el-input>
            </el-form-item>
            <el-form-item label="地址：" prop="url" :label-width="formLabelWidth">
              <el-input v-model="editform.url" size="small" clearable auto-complete="off"  onkeyup="this.value=this.value.replace(/^ +| +$/g,'')"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button class="r-float" size="mini" type="primary" @click="submitForm('editform')">确定</el-button>
            <el-button class="r-float" size="mini" @click="close">取 消</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        page: {
          currentPage: 1, //当前页
          pageSize: null, //每页条数
          total: null, //总条数
        },
        tableData: [],
        FormVisible: false,
        FormVisible1: false,
        formLabelWidth: "100px",
        editform: {
          realname: '',
          username: '',
          id: '',
          mobile: '',
          enabled: '',
          roleId: ''
        },
        form: {
          name: '',
        },
        permisform: {
          name: '',
          url: '',
          pid: ''
        },
        typeList: [],
        rules: {
          name: [
            {required: true, message: '请输入权限名称'},
            {max: 20, message: '不能超过20个字符'},
          ],
          url: [
            {required: true, message: '请输入权限地址'},
            {max: 50, message: '不能超过50个字符'}
          ],
          pid: [
            {required: true, message: '请选择父级权限',trigger: 'change'},
          ],

        },
        value: '',


      }
    },
    computed: {
    },
    mounted() {
      this.Search();
      this.getPermis();
    },
    components: {

    },
    methods: {
      // 渲染父级权限
      getPermis() {
        let _this = this;
        _this.$https({
          method: 'get',
          url: 'permission/getTopPermissionList',
          authType: this.backToken
        }).then((res) => {
            let data = res.data;
          data.map((e, i) => {
              let a = {
                id: e.id,
                name: e.name,
              }
              _this.typeList.push(a);
              _this.typeListIds = _this.typeList.map((e, i) => {
                return e.i
              })
            })

          }, (error) => {
            console.log(error)
          }
        )

      },
      // 获得数据接口
      getTableData(param) {
        let vm = this;
        vm.$https({
          url : "permission/getPermissionList",
          method: 'get',
          authType: this.backToken
        },param).then((res)=>{
          let data = res.data;
          vm.page.pageSize = data.size;
          vm.page.total = data.total;
          vm.tableData = data.records;
        }).catch(function(err){
          console.log(err);
        })
      },
      // 分页
      handleCurrentChange(val) {
        let _this = this;
        _this.page.currentPage = val;
        _this.onSearch();
      },
      onSearch() {
        let _this = this;
        let param = _this.getSearchQuery();
        _this.getTableData(param)
      },
      Search(){
        let _this = this;
        _this.page.currentPage = 1;
        let searchObj = {
          "_index": 1,
          "_size":  _this.page.pageSize,
          "name": _this.form.name,
        };
        this.getTableData(searchObj);
      },
      // // 获取当前查询参数
      getSearchQuery() {
        let _this = this;
        let searchObj = {
          "_index":  _this.page.currentPage,
          "_size": _this.page.pageSize
        };
        for (let key in _this.form) {
          if (_this.form[key]) {
            searchObj[key] = _this.form[key];
          }
        }
        return searchObj;
      },
      addPermis(){
        $('.el-dialog__title').html('新建');
        this.FormVisible1 = true;
      },
      // 添加权限
      permisSave() {
        let _this = this;
        _this.$refs.permisform.validate((valid) => {
          if (valid) {
            let searchObj = {}
            for (let key in _this.permisform) {
              if (_this.permisform[key]) {
                searchObj[key] = _this.permisform[key];
              }
            }
            _this.$https({
              url: 'permission/add',
              method: 'post',
              authType: this.backToken
            }, _this.$qs.stringify(searchObj))
              .then((res) => {
                  if (res.data.status == 200 || res.data.status == 201) {
                    _this.$message({
                      type: 'success',
                      message: res.data.message
                    });
                    //跳回用户列表
                    _this.onSearch();
                    _this.FormVisible1 = false;
                    for (let key in _this.permisform) {
                      _this.permisform[key]=null;
                    }
                    _this.$refs['permisform'].resetFields();
                  } else {
                    _this.$message({
                      type: 'error',
                      message: res.data.message
                    });
                  }
                }, (error) => {
                  _this.$message({
                    type: 'error',
                    message: error
                  });
                }
              )
            }
        });
      },
      // 编辑关闭
      close() {
        this.FormVisible=false;
        this.$refs['editform'].resetFields();
      },
       // 新增关闭
      close1() {
          this.FormVisible1 = false;
          for (let key in this.permisform) {
            this.permisform[key]=null;
          }
          this.$refs['permisform'].resetFields();
      },
      // 编辑弹框
      openEdit(row){
        $('.el-dialog__title').html('编辑');
        let  _this=this;
        //成功之后清除数据
        for (let key in this.editform) {
          _this.editform[key]=null;
        }
        _this.editform= Object.assign({}, row);
        _this.FormVisible = true;
      },
      // 删除
      handleDelete(row) {
        let _this = this;
        this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          _this.$https({
            method: 'delete',
            url: 'permission/delete?permissionId='+ row.id,
            authType: this.backToken
          }).then((res) => {
              this.$message({type: 'success', message: '删除成功!'});
              _this.Search();
            }, (error) => {
              this.$message({type: 'fail', message: "删除失败!" + error.response.data});
            }
          )
        })
      },

      // 保存编辑信息
      submitForm() {
          let _this = this;
          let searchObj = {}
          for (let key in _this.editform) {
            if (_this.editform[key]) {
              searchObj[key] = _this.editform[key];
            }
          }
        let str = _this.editform.name;
        let index = str .lastIndexOf("\-");
        str  = str .substring(index + 1, str .length);
        searchObj.name = str;
        _this.$https({
            url: 'permission/edit',
            method: 'put',
            authType: this.backToken
          }, _this.$qs.stringify(searchObj))
            .then((res) => {
                if (res.data.status == 200 || res.data.status == 201) {
                  _this.$message({
                    type: 'success',
                    message: res.data.message
                  });
                  _this.onSearch();
                  _this.FormVisible=false;
                  _this.$refs['editform'].resetFields();
                } else {
                  _this.$message({
                    type: 'error',
                    message: res.data.message
                  });
                }
              }, (error) => {
                _this.$message({
                  type: 'error',
                  message: error
                });
              }
            )
      },

      // 批量操作
      handleSelectionChange(selection){
        let _this = this;
        _this.selection = selection;
      },
      getMultipleSelect () {
        let _this = this;
        let arr = [];
        let str = '';
        if (_this.selection){
          _this.selection.forEach(function (e) {
            arr.push(e.id);
          })
          str = arr.join(',');
        }else{
          str = '';
        }
        return str;
      },
      // 批量删除
      multipleDelete () {
        let _this = this;
        let str = _this.getMultipleSelect();
        if (str) {
          this.$confirm('此操作将删除选中用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            _this.$https({
              url:'permission/batchDel?permissionIds='+str,
              method:'DELETE',
              authType: this.backToken
            }).then((res) => {
                  if(res.data.status == 201 || res.data.status == 200){
                    this.$message({
                      type: 'success',
                      message: '删除成功!'
                    });
                  }
                  //重新查询数据
                  _this.onSearch();

                }, (error) => {
                }
              )
          })
        } else {
          this.$message({
            type: 'info',
            message: '请至少选择一个选项！'
          });
        }
      },
    }

  }
</script>

<style lang="less">
  @import '../../style/common';
.permissionsPage{
  .content_box{
    .input_box{
      width: 100%;
      min-width: 815px;
      margin-bottom: 30px;
      .el-input{
        max-width:272px;
        height:32px;
        background:rgba(255,255,255,1);
        border-radius:4px;
        .el-input__inner{
          height:32px;
        }
      }
      .btn_form_search,.btn_form_add{
        height: 32px;
        text-align: center;
        padding: 0 15px;
      }
    }
    .scrool {
      width: 100%;
      height: calc(100% - 100px);
      overflow-x: hidden;
      overflow-y: scroll;
      .el-table {
        .el-table__header-wrapper {
          .el-table__header {
            .has-gutter tr th {
              background: rgba(250, 250, 250, 1);
            }

          }
        }
        .el-table__body-wrapper {
          width: 100%;
          table tbody tr td {
            padding: 6px 0px;
          }
        }
      }
    }

    /*!*编辑弹框*!*/
    .el-dialog{
      width: 600px;
      background:rgba(255,255,255,1);
      box-shadow:0px 4px 12px 0px rgba(0,0,0,0.2);
      border-radius:4px;
      .el-dialog__header{
        padding: 15px;
       border-bottom: 1px solid rgba(0,0,0,0.09);
      }
     .el-dialog__body{
        padding: 0px!important;
        border: 1px solid transparent;
       .form_box{
         padding-bottom: 40px;
         .el-form {
           margin-bottom: 20px;
          .el-form-item{
            margin: 10px  50px 20px;
            .el-form-item__label{
              text-align:right;
            }
             .el-form-item__content{
               width: 280px;
             }
            }
             .el-input{
               width: 100%;
             }
            }
         .dialog-footer{
            border-top: 1px solid rgba(0,0,0,0.09);
            padding-top: 8px;
            .el-button{
             margin-right: 10px;
             padding: 8px 16px;
           }
         }
        }
      }
   }
  }
}



</style>
