<template>
  <div class="menuManagePage 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="menuName"  ></el-table-column>
          <el-table-column show-overflow-tooltip label="地址" prop="menuUrl" ></el-table-column>
          <el-table-column label="排序值" prop="sort"></el-table-column>
          <el-table-column label="操作"  header-align="center" align="center" >
            <template slot-scope="scope" width="220">
              <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" id="ruleo" label-position="left">
            <el-form-item label="排序值：" prop="sort" :label-width="formLabelWidth">
              <el-input size="small" v-model="permisform.sort" auto-complete="off" clearable placeholder="请输入排序值" ></el-input>
            </el-form-item>
            <el-form-item label="菜单名称：" prop="menuName" :label-width="formLabelWidth">
              <el-input  size="small" v-model="permisform.menuName" onkeyup="this.value=this.value.replace(/\s+/g,'')" auto-complete="off" clearable placeholder="请输入您的菜单名称" ></el-input>
            </el-form-item>
            <el-form-item label="地址：" prop="menuUrl" :label-width="formLabelWidth">
              <el-input size="small" v-model="permisform.menuUrl" onkeyup="this.value=this.value.replace(/\s+/g,'')" auto-complete="off" clearable placeholder="请输入您的菜单地址" ></el-input>
            </el-form-item>
            <el-form-item label="父级菜单：" prop="parentId" :label-width="formLabelWidth">
              <el-select  size="small" v-model="permisform.parentId" value-key="name" clearable placeholder="请选择父级菜单" >
                <el-option v-for="(item,index) in typeList"   :key="index" :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="sort" :label-width="formLabelWidth">
              <el-input size="small" v-model="editform.sort" auto-complete="off" clearable placeholder="请输入排序值" ></el-input>
            </el-form-item>
            <el-form-item label="菜单名称：" prop="menuName"  :label-width="formLabelWidth" >
              <el-input size="small" v-model="editform.menuName" auto-complete="off"  clearable onkeyup="this.value=this.value.replace(/^ +| +$/g,'')"></el-input>
            </el-form-item>
            <el-form-item label="菜单地址：" prop="menuUrl"  :label-width="formLabelWidth">
              <el-input size="small" v-model="editform.menuUrl" auto-complete="off" clearable  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() {
      var checkIsNull = (rule, value, callback) => {
        if(value) {
          if(value.trim() == '') {
            callback(new Error('不允许只输入空格'))
          } else {
            callback()
          }
        }
      };
      return {
        page: {currentPage: 1,pageSize:10,total:0},
        tableData: [],
        FormVisible: false,
        FormVisible1: false,
        formLabelWidth: "100px",
        form: {
          name: '',
        },
        editform: {
          menuName: '',
          menuUrl: '',
          parentId: '',
          sort:'',
          id:'',
        },
        permisform: {
          menuName: '',
          menuUrl: '',
          parentId: '',
          sort:'',
        },
        typeList: [],
        rules: {
          sort:[
            {required: true, message: '请输入顺序值',trigger: 'change'},
            {pattern:  /^(\d{1,5})?$/, message: '排序值为低于5位数的纯数字'}
          ],
          menuName: [
            {required: true, message: '请输入菜单名称',trigger: 'change'},
            {max: 20, message: '不能超过20个字符',trigger: 'change'},
            {validator: checkIsNull, trigger: 'blur'}
          ],
          menuUrl:[
            {required: true, message: '请输入菜单地址',trigger: 'change'},
            {validator: checkIsNull, trigger: 'blur'}
          ],
          parentId: [
            {required: true, message: '请输入父级菜单',trigger: 'change'},
          ],
        },
        value: '',
        name: '',
      }
    },
    computed: {
    },
    mounted() {
      this.onSearch();
      this.getPermis();
    },
    components: {

    },
    methods: {
      // 渲染父级权限
      getPermis() {
        let vm = this;
        vm.$https({
          method: 'get',
          url: 'menu/getRoleMenu?roleId='+sessionStorage.getItem('roleId'),
          authType: this.backToken
        }).then((res) => {
            let data = res.data;
            vm.typeList = data.map((e, i) => {
              return  {
                id: e.id,
                name: e.menuName.indexOf('-')==-1?e.menuName:e.menuName.split('-')[1],
              }
            })
          }, (error) => {
            console.log(error)
          }
        )

      },
      // 获得数据接口
      getTableData(param) {
        let vm = this;
        vm.$https({
          url : "menu/getMenuList",
          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) {
            _this.$https({url: 'menu/add', method: 'post', authType: this.backToken
            }, _this.$qs.stringify(_this.permisform))
              .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: 'menu/delete?menuId='+ row.id,
            authType: this.backToken
          }).then((res) => {
              this.$message({type: 'success', message: '删除成功!'});
              _this.Search();
            }, (error) => {
              this.$message({type: 'fail', message: "删除失败!" + error.response.data});
            }
          )
        }).catch(() => {
        });
      },
      // 保存编辑信息
      submitForm() {
        let _this = this;
        _this.$refs.editform.validate((valid) => {
          if (valid) {
            let searchObj = {}
            for (let key in _this.editform) {
              if (this.editform[key]) {
                searchObj[key] = _this.editform[key];
              }
            }
            let str = _this.editform.menuName;
            let index = str.lastIndexOf("\-");
            str  = str.substring(index + 1, str.length);
            searchObj.menuName = str;
            _this.$https({
              url: 'menu/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:'menu/batchDel?menuIds='+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';
  .menuManagePage{
    .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__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>
