<template>
  <div class="menu-container">
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="菜单列表" name="list">
        <el-table stripe ref="table" :height="tableHeight" v-loading="tableLoading"
                  :data="menuList.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                  border row-key="id">
          <el-table-column show-overflow-tooltip prop="id" label="ID" align="center" width="100"/>
          <el-table-column show-overflow-tooltip prop="sort" label="排序" align="center" width="100"/>
          <el-table-column show-overflow-tooltip prop="title" label="名称" align="center"/>
          <el-table-column show-overflow-tooltip prop="name" label="地址" align="center"/>
          <el-table-column show-overflow-tooltip prop="icon" label="图标" align="center" width="100">
            <template slot-scope="{row}">
              <svg-icon v-if="row.icon" :iconClass='row.icon' className='icon'></svg-icon>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="type" label="类型" align="center" width="100">
            <template slot-scope="{row}">
              <el-tag type="success" size="small">{{ row.type === 1 ? '按钮' : '菜单' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="status" label="状态" align="center" width="120">
            <template slot-scope="{row}">
              <span v-show="row.status ==1" style="color: #666">显示</span>
              <span v-show="row.status ==2" style="color: #666">隐藏</span>
              <el-switch v-if="btnRule.userauthrule_status" v-model="row.status" :active-value="1"
                         :inactive-value="2" size="small"
                         @change="changeStatus(row)"/>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="format_create_user" label="添加人" align="center"/>
          <el-table-column label="操作" align="left" width="180">
            <template slot-scope="scope">
              <el-tooltip v-if="btnRule.userauthrule_edit" class="item" effect="dark" content="编辑菜单"
                          placement="bottom">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleAddRole(scope.row)"/>
              </el-tooltip>
              <el-tooltip v-if="btnRule.userauthrule_drop" class="item" effect="dark" content="删除"
                          placement="bottom">
                <el-button :loading="delBtnLoading" type="danger" size="mini" icon="el-icon-delete"
                           @click="handleDelete(scope.row)"/>
              </el-tooltip>
              <el-button v-if="scope.row.has_child === 1&&btnRule.userauthrule_add" type="primary"
                         size="mini" icon="el-icon-plus" class="add"
                         @click="addMenu(scope.row,1)">添加子级
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div><i class="iconfont ceshi"></i></div>
        <!-- 分页 -->
        <div  class="page-current">
          <el-pagination
            background
            :current-page="currentPage"
            :page-size="pageSize"
            prev-text="上一页"
            next-text="下一页"
            layout="total, prev, pager, next, jumper"
            style="display: inline-block;"
            :total="count"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane v-if="btnRule.userauthrule_add" label="添加菜单" name="add">
        <el-form ref="ruleForm" :model="ruleForm" size="small" label-width="100px"
                 style="width: 50%">
          <el-form-item label="菜单标题"
                        prop="title"
                        :rules="[{
                    required: true, message: '菜单标题不能为空', trigger: 'blur'
                  },
                {min: 1, max: 10, message: '长度在1 到 10 个字符', trigger: 'blur'}]"
          >
            <el-input maxlength="10" clearable v-model="ruleForm.title" size="small" placeholder="请输入菜单标题"/>
          </el-form-item>
          <el-form-item label="父级">
            <div class="block">
              <span class="demonstration"></span>
              <el-cascader
                placeholder="无"
                v-model="ruleForm.pid"
                ref="refHandle"
                :options="filterMenuList"
                :props="{ checkStrictly: true ,value:'id',label:'title'}"
                clearable></el-cascader>
            </div>
          </el-form-item>
          <el-form-item
            label="菜单地址"
            prop="name"
            :rules="[{
                    required: true, message: '菜单地址不能为空', trigger: 'blur'
                  },
                {min: 1, max: 30, message: '长度在1 到 30 个字符', trigger: 'blur'}]"
          >
            <el-input maxlength="30" clearable v-model="ruleForm.name" size="small" placeholder="请输入菜单地址"/>
          </el-form-item>
          <el-form-item label="图标" prop="icon" :rules="[
                {min: 0, max: 50, message: '不超过 50 个字符', trigger: 'blur'}]">
            <el-input maxlength="50" clearable v-model="ruleForm.icon" size="small" placeholder="请输入图标">
              <el-button @click="fontVisible=true;searchValue=''" slot="append">搜索图标</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="权限" prop="permission" :rules="[{
                    required: true, message: '权限不能为空', trigger: 'blur'
                  },
                {min: 1, max: 50, message: '长度在1 到 50 个字符', trigger: 'blur'}]">
            <el-input maxlength="50" clearable v-model="ruleForm.permission" size="small" placeholder="请输入权限"/>
          </el-form-item>
          <el-form-item label="备注" prop="remark" :rules="[
                {min: 0, max: 200, message: '不超过 200 个字符', trigger: 'blur'}]">
            <el-input maxlength="200" clearable v-model="ruleForm.remark" type="textarea" rows="5" size="small" placeholder="请输入内容"/>
          </el-form-item>
          <el-form-item label="分类">
            <el-radio-group v-model="ruleForm.type">
              <el-radio :label="1">按钮</el-radio>
              <el-radio :label="2">菜单</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="有无子级">
            <span v-show="ruleForm.hasChild == 1" style="color: #666">有</span>
            <span v-show="ruleForm.hasChild == 2" style="color: #666">无</span>
            <el-switch v-model="ruleForm.hasChild" :active-value="1" :inactive-value="2" size="small"/>
          </el-form-item>
          <el-form-item label="状态">
            <span v-show="ruleForm.status == 1" style="color: #666">显示</span>
            <span v-show="ruleForm.status == 2" style="color: #666">隐藏</span>
            <el-switch v-model="ruleForm.status" :active-value="1" :inactive-value="2" size="small"/>
          </el-form-item>
          <el-form-item clearable label="排序" prop="sort">
            <el-input-number size="small" v-model="ruleForm.sort"></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-document-add" :loading="addBtnLoading" type="primary" size="small" @click="submitForm('ruleForm',1)"
            >立即提交
            </el-button>
            <el-button icon="el-icon-back" size="small" @click="resetForm('ruleForm')">返回</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <!-- 编辑角色 -->
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" top="5vh" center :visible.sync="editDialogVisible" title="编辑菜单">
      <el-form ref="ruleForm" :model="ruleForm" size="small" label-width="100px"
               style="margin-right: 20px;">
        <el-form-item label="菜单标题" prop="title"
                      :rules="[{
                    required: true, message: '菜单标题不能为空', trigger: 'blur'
                  },
                {min: 1, max: 10, message: '长度在1 到 10 个字符', trigger: 'blur'}]"
        >
          <el-input maxlength="10" clearable v-model="ruleForm.title" size="small" placeholder="请输入菜单标题"/>
        </el-form-item>
        <el-form-item label="父级">
          <div class="block">
            <span class="demonstration"></span>
            <el-cascader
              :disabled="ruleForm.disable"
              placeholder="无"
              v-model="ruleForm.pid"
              ref="refHandle"
              :options="filterMenuList"
              :props="{ checkStrictly: true ,value:'id',label:'title'}"
              clearable></el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="菜单地址"
                      prop="name"
                      :rules="[{
                    required: true, message: '菜单地址不能为空', trigger: 'blur'
                  },
                {min: 1, max: 30, message: '长度在1 到 30 个字符', trigger: 'blur'}]"
        >
          <el-input maxlength="30" clearable v-model="ruleForm.name" size="small" placeholder="请输入菜单地址"/>
        </el-form-item>
        <el-form-item label="图标" prop="icon" :rules="[
                {min: 0, max: 50, message: '不超过 50 个字符', trigger: 'blur'}]">
          <el-input maxlength="50" clearable v-model="ruleForm.icon" size="small" placeholder="请输入图标">
            <el-button @click="fontVisible=true;searchValue=''" slot="append">搜索图标</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="权限" prop="permission" :rules="[{
                    required: true, message: '权限不能为空', trigger: 'blur'
                  },
                {min: 1, max: 50, message: '长度在1 到 50 个字符', trigger: 'blur'}]">
          <el-input maxlength="50" clearable v-model="ruleForm.permission" size="small" placeholder="请输入规则条件"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark" :rules="[
                {min: 0, max: 200, message: '不超过 200 个字符', trigger: 'blur'}]">
          <el-input maxlength="200" clearable v-model="ruleForm.remark" type="textarea" rows="5" size="small" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="分类">
          <el-radio-group v-model="ruleForm.type">
            <el-radio :label="1">按钮</el-radio>
            <el-radio :label="2">菜单</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="有无子级">
          <el-switch v-model="ruleForm.hasChild" :active-value="1" :inactive-value="2" size="small"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="ruleForm.status" :active-value="1" :inactive-value="2" size="small"/>
        </el-form-item>
        <el-form-item clearable label="排序" prop="sort" :rules="{
                    required: true, message: '排序不能为空', trigger: 'blur'
                  }">
          <el-input-number size="small" v-model="ruleForm.sort"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button :loading="addBtnLoading" type="primary" size="medium" icon="el-icon-document-add"
                       @click="submitForm('ruleForm',ruleForm.disable?3:2)"
            >提交
            </el-button>
            <el-button style="margin-left: 15px" size="medium" icon="el-icon-back"
                       @click="resetForm('ruleForm') ; editDialogVisible = false">返回
            </el-button>
        </span>
    </el-dialog>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" class="font-dialog" :visible.sync="fontVisible" title="信息">
      <el-input style="width: 50%;margin-left: 10px" placeholder="" v-model="searchValue">
        <el-button slot="append" icon="el-icon-search"></el-button>
      </el-input>
      <div class="icon-box">
        <div @click="menuIconClick(value)" :title="value" class="icon-item" :key="index"
             v-for="(value,index) in menuIcon.filter(value=>value.indexOf(searchValue)>-1)">
          <svg-icon :iconClass='value' className='icon'></svg-icon>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import api from '@/api/permission/menu'
  import {mapGetters} from "vuex";

  export default {
    name: "authrule",
    data() {
      return {
        addBtnLoading: false,
        delBtnLoading: false,
        tableLoading: true,
        // 当前页
        currentPage: 1,
        // 总条数
        count: 0,
        // 每页条数
        pageSize: 10,
        fontVisible: false,
        // 显示编辑角色弹框
        editDialogVisible: false,
        // 用户按钮权限
        menuIcon: [],
        activeName: 'list',
        menuList: [],
        filterMenuList: [],
        searchValue: '',
        ruleForm: {
          title: '',
          name: '',
          permission: '',
          icon: '',
          remark: '',
          type: 1,
          hasChild: '2',
          status: '2',
          sort: 1
        },
        tableHeight: document.body.clientHeight - 245,
      }
    },
    watch: {
      activeName(val) {
        if (val == 'add') {
          this.initRuleForm()
          this.initFilterList()
        }
      }
    },
    created() {
      this.pageSize = parseInt((document.body.clientHeight - 284) / 50)
      let req = require.context('../../assets/icons', false, /\.svg$/)
      let menuIcon = []
      req.keys().map(item => {
        menuIcon.push(item.replace(/.svg/g, "").replace(/.\//g, ""))
      })
      this.menuIcon = menuIcon
    },
    computed: {
      ...mapGetters(["btnRule"])
    },
    mounted() {
      this.tableLoading = true
      this.getAllList()
    },
    methods: {
      handleCurrentChange(val) {
        this.currentPage = val
        this.$refs.table.bodyWrapper.scrollTop = 0;
      },
      menuIconClick(value) {
        this.ruleForm.icon = value
        this.fontVisible = false
      },
      initRuleForm() {
        this.ruleForm = {
          permission: '',
          title: '',
          name: '',
          icon: '',
          remark: '',
          type: 1,
          hasChild: '2',
          status: '2',
          sort: 1
        }
      },
      findFilterList(list, id) {
        for (let i = list.length - 1; i >= 0; i--) {
          if (list[i].has_child != 1 || list[i].id == id) {
            list.splice(i, 1)
          } else {
            if (list[i].children && list[i].children.length > 0) {
              this.findFilterList(list[i].children, id)
            }
          }
        }
      },
      initFilterList(id) {
        let filerList = JSON.parse(JSON.stringify(this.menuList))
        this.findFilterList(filerList, id)
        this.filterMenuList = filerList
      },
      // 获取列表
      getAllList() {
        // 设置分页
        api.backMenuList({}).then(res => {
          this.tableLoading = false
          this.menuList = res.data
          this.count = res.data.length
        }).catch(e => {
          this.count = 0
          this.menuList = []
          this.tableLoading = false
        })
      },
      // 改变状态
      changeStatus(data) {
        var content = ''
        if (data.status === 1) {
          content = '确定要显示菜单吗？'
        } else {
          content = '确定要隐藏菜单吗？'
        }
        this.$confirm(content, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {
            status: data.status == 1 ? '1' : '2',
            id: data.id
          }
          this.tableLoading = true
          api.backEditStatus(params).then(res => {
            this.$message({
              type: 'success',
              message: '操作成功！'
            })
            this.getAllList()
          }).catch(e => {
            this.getAllList()
            this.tableLoading = false
          })
        }).catch(() => {
          this.tableLoading = true
          this.getAllList()
          this.$message({
            type: 'info',
            message: '已取消该操作！'
          })
        })
      },

      // 编辑角色
      handleAddRole(data) {
        data.hasChild = data.has_child
        this.ruleForm = JSON.parse(JSON.stringify(data))
        this.initFilterList(data.id)
        this.editDialogVisible = true
      },
      // 删除菜单
      handleDelete(data) {
        this.$confirm('此操作将永久删除该菜单，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delBtnLoading = true
          api.backMenuDel({id: data.id}).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            this.delBtnLoading = false
            this.tableLoading = true
            this.getAllList()
          }).catch(e => {
            this.delBtnLoading = false
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 重置缓存
      resetCache(res) {
        alert('直接调用接口，给提示')
      },
      // 添加子级
      addMenu(data, type) {
        this.initRuleForm()
        this.initFilterList()
        this.$refs['ruleForm'].resetFields()
        this.editDialogVisible = true
        if (type) {
          this.ruleForm.pid = data.id ? data.id : 0
          this.ruleForm.disable = 1
        }
      },
      submitForm(formName, type) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
            if (ruleForm.pid) {
              if (Array.isArray(ruleForm.pid) && ruleForm.pid.length > 0) {
                ruleForm.pid = ruleForm.pid[ruleForm.pid.length - 1]
              } else if (ruleForm.pid.length == 0) {
                ruleForm.pid = 0
              }
            } else {
              if (!ruleForm.pid) {
                ruleForm.pid = 0
              }
            }
            this.addBtnLoading = true
            if (type == 1 || type == 3) {
              api.backMenuAdd(ruleForm).then(res => {
                this.addBtnLoading = false
                this.initRuleForm()
                this.$refs[formName].resetFields()
                if (type == 3) {
                  this.editDialogVisible = false
                }
                this.tableLoading = true
                this.$message({
                  type: 'success',
                  message: '添加成功！'
                })
                this.getAllList()
              }).catch(e => {
                this.addBtnLoading = false
              })
            } else {
              api.backMenuEdit(ruleForm).then(res => {
                this.addBtnLoading = false
                this.initRuleForm()
                this.$refs[formName].resetFields()
                this.editDialogVisible = false
                this.tableLoading = true
                this.$message({
                  type: 'success',
                  message: '编辑成功！'
                })
                this.getAllList()
              }).catch(e => {
                this.addBtnLoading = false
              })
            }
          }
        })
      },
      resetForm(formName) {
        this.initRuleForm()
        this.$refs[formName].resetFields()
        this.activeName = 'list'
      }
    }
  }
</script>

<style lang="less">
  .menu-container {
    width: 100%;

    .svg-icon {
      width: 20px;
      height: 20px;
      background-color: #eeeeee;
    }

    .font-dialog {
      .el-dialog__body {
        padding: 10px 10px;
      }
    }

    .page-current {
      text-align: center;
      padding: 15px 5px;
      padding-bottom: 0px;

      .sure-page-btn {
        display: inline-block;
        height: 28px;
        line-height: 0;
        width: 46px;
        padding: 0;
        vertical-align: top;
      }
    }

    .icon-box {
      display: flex;
      flex-wrap: wrap;

      .icon-item {
        border: 1px solid #eeeeee;
        width: 41px;
        height: 42px;
        margin-top: 10px;
        line-height: 42px;
        font-size: 18px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 10px;
      }

      .icon-item:hover {
        border: 1px solid #409eff;
        cursor: pointer;
        color: #409eff;
      }
    }
  }

</style>
