<template>
  <div class="role-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="roleList.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="name" label="名称" align="center"/>
          <el-table-column show-overflow-tooltip prop="remark" label="备注" align="center"/>
          <el-table-column show-overflow-tooltip prop="format_create_user" label="添加人" align="center"/>
          <el-table-column show-overflow-tooltip prop="format_create_time" label="添加时间" align="center" width="160">
            <!--            <template slot-scope="{row}">-->
            <!--              {{row.create_time | datetime}}-->
            <!--            </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="isAdmin||btnRule.some(btn=>btn=='status')" v-model="row.status" :active-value="1"
                         :inactive-value="2" size="small"
                         @change="changeStatus(row)"/>
            </template>
          </el-table-column>
          <el-table-column
            v-if="isAdmin||(btnRule.filter(value=>value=='edit'||value=='drop'||value=='setRules'||value=='add').length>0)"
            label="操作" align="left" width="240">
            <template slot-scope="scope">
              <el-tooltip v-if="isAdmin||btnRule.some(btn=>btn=='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="isAdmin||btnRule.some(btn=>btn=='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="isAdmin||btnRule.some(btn=>btn=='setRules')" type="success" size="mini"
                         icon="el-icon-share" @click="limitDetail(scope.row)">权限
              </el-button>
              <el-button v-if="scope.row.has_child === 1&&(isAdmin||btnRule.some(btn=>btn=='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 class="page-current">
          <el-pagination
            style="text-align: center"
            background
            layout="total, prev, pager, next, jumper"
            :current-page.sync="currentPage"
            :page-size="pageSize"
            @current-change="handleCurrentChange"
            :total="count">
          </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane v-if="isAdmin||btnRule.some(btn=>btn=='add')" label="添加角色" name="add">
        <el-form ref="ruleForm" v-loading="loading" :model="ruleForm" size="small" label-width="100px"
                 style="width: 50%">
          <el-form-item label="父级">
            <div class="block">
              <span class="demonstration"></span>
              <el-cascader
                placeholder="无"
                v-model="ruleForm.pid"
                ref="refHandle"
                :options="filterRoleList"
                :props="{ checkStrictly: true ,value:'id',label:'name'}"
              ></el-cascader>
            </div>
          </el-form-item>
          <el-form-item label="名称" prop="name"
                        :rules="[{
                    required: true, message: '名称不能为空', trigger: 'blur'
                  },
                {min: 2, max: 10, message: '长度在2 到 10 个字符', trigger: 'blur'}]">
            <el-input maxlength="10" clearable v-model="ruleForm.name" 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-switch v-model="ruleForm.status" :active-value="1" :inactive-value="2" size="small"/>
          </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="排序" 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" center :visible.sync="addDialogVisible" :title="dialogType==='edit'? '编辑角色' : '添加子级'">
      <el-form ref="ruleForm" v-loading="loading" :model="ruleForm" size="small" label-width="100px">
        <el-form-item label="父级">
          <div class="block">
            <span class="demonstration"></span>
            <el-cascader
              :disabled="ruleForm.disable"
              v-model="ruleForm.pid"
              ref="refHandle"
              placeholder="无"
              :options="filterRoleList"
              :props="{ checkStrictly: true ,value:'id',label:'name'}"
            ></el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="名称" prop="name" :rules="[{
                    required: true, message: '名称不能为空', trigger: 'blur'
                  },
                {min: 2, max: 10, message: '长度在2 到 10 个字符', trigger: 'blur'}]">
          <el-input maxlength="10" clearable v-model="ruleForm.name" 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-switch v-model="ruleForm.status" :active-value="1" :inactive-value="2" size="small"/>
        </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="排序" prop="sort">
          <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 icon="el-icon-document-add" :loading="addBtnLoading" type="primary" size="medium"
                       @click="submitForm('ruleForm',ruleForm.disable?3:2)">提交
            </el-button>
            <el-button icon="el-icon-back" size="medium" @click="resetForm('ruleForm') ; addDialogVisible = false">返回
            </el-button>
        </span>
    </el-dialog>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :center="true" v-loading="treeLoading" class="menu-dialog" :visible.sync="menuVisible" title="设置权限">
      <el-tree
        ref="tree"
        :data="menuList"
        highlight-current
        check-strictly
        show-checkbox
        default-expand-all
        node-key="id"
        @check-change="handleCheckChange"
        :props="defaultProps">
      </el-tree>
      <span slot="footer" class="dialog-footer">
          <el-button icon="el-icon-document-add" :loading="roleMenuLoading" type="primary" @click="roleMenuSubmit">提交</el-button>
          <el-button icon="el-icon-back" @click="menuVisible = false;initRuleForm()">取 消</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
  import roleApi from '@/api/permission/authRule'
  import menuApi from '@/api/permission/menu'

  export default {
    name: "authgroup",
    data() {
      return {
        // 当前页
        currentPage: 1,
        treeLoading: false,
        // 总条数
        count: 0,
        // 每页条数
        pageSize: 10,
        menuVisible: false,
        roleMenuLoading: false,
        addBtnLoading: false,
        delBtnLoading: false,
        // 显示编辑角色弹框
        addDialogVisible: false,
        checkedKeys: [],
        dialogType: 'new',
        // 用户按钮权限
        btnRoles: [],
        defaultProps: {
          children: 'children',
          label: 'title'
        },
        activeName: 'list',
        token: '',
        // 角色列表
        roleList: [],
        // 列表编辑
        ruleForm: {
          pid: '',
          name: '',
          status: 1,
          remark: '',
          sort: 1,
          hasChild: 2
        },
        menuList: [],
        tableLoading: false,
        loading: false,
        isShowParent: false,
        tableHeight: document.body.clientHeight - 245,
        btnRule: [],
        isAdmin: false,
        filterRoleList: []
      }
    },
    created() {
      this.pageSize = parseInt((document.body.clientHeight - 284) / 50)
      const {btnRule, isAdmin} = this.$store.state.user
      this.btnRule = btnRule
      this.isAdmin = isAdmin
    },
    mounted() {
      this.tableLoading = true
      this.getAllList()
    },
    watch: {
      activeName(val) {
        if (val == 'add') {
          this.initFilterList()
          this.initRuleForm()
        }
      }
    },
    methods: {
      handleCurrentChange(val) {
        this.currentPage = val
        this.$refs.table.bodyWrapper.scrollTop = 0;
      },
      roleMenuSubmit() {
        this.roleMenuLoading = true
        roleApi.setRules({
          id: this.ruleForm.id,
          rules: this.checkedKeys.length > 0 ? this.checkedKeys.join(',') : ''
        }).then(res => {
          this.menuVisible = false
          this.$message({
            type: 'success',
            message: '权限保存成功！'
          })
          this.roleMenuLoading = false
          this.tableLoading = true
          this.getAllList()
        }).catch(e => {
          this.roleMenuLoading = false
        })
      },
      handleCheckChange(data, checked, indeterminate) {
        if (!this.isTreeBl) {
          if (checked) {
            if (!this.checkedKeys.some(key => key == data.id)) {
              this.checkedKeys.push(data.id)
            }
            this.childNode(data.children)
            this.parentNode(data.pid)
          } else {
            for (let i = 0; i < this.checkedKeys.length; i++) {
              if (data.id == this.checkedKeys[i]) {
                this.checkedKeys.splice(i, 1)
                break
              }
            }
            this.childNode(data.children, 1)
          }
          this.isTreeBl = true
          this.$refs.tree.setCheckedKeys(this.checkedKeys);
          let me = this
          this.$nextTick(function () {
            me.isTreeBl = false
          })
        }
      },
      childNode(childList, type) {
        if (childList && childList.length > 0) {
          childList.map(item => {
            if (type) {
              for (let i = 0; i < this.checkedKeys.length; i++) {
                if (item.id == this.checkedKeys[i]) {
                  this.checkedKeys.splice(i, 1)
                  break
                }
              }
            } else {
              if (!this.checkedKeys.some(key => key == item.id)) {
                this.checkedKeys.push(item.id)
              }
            }
            this.childNode(item.children, type)
          })
        }
      },
      parentNode(pid, type) {
        if (pid) {
          this.findChild(this.menuList, pid, type)
        }
      },
      findChild(childList, pid, type) {
        let child = childList.find(item => item.id == pid)
        if (child) {
          if (!this.checkedKeys.some(key => key == child.id)) {
            this.checkedKeys.push(child.id)
            if (child.pid) {
              this.findChild(this.menuList, child.pid)
            }
          }
        } else {
          childList.map(item => {
            if (item.children && item.children.length > 0) {
              this.findChild(item.children, pid)
            }
          })
        }
      },
      initRuleForm() {
        this.ruleForm = {
          pid: '',
          name: '',
          status: 1,
          remark: '',
          sort: 1,
          hasChild: 2
        }
      },
      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)
            }
          }
        }
      },
      initFilterList(id) {
        let filerList = JSON.parse(JSON.stringify(this.roleList))
        this.findFilterList(filerList, id)
        this.filterRoleList = filerList
      },
      // 获取列表
      getAllList() {
        roleApi.roleList().then(res => {
          this.tableLoading = false
          this.roleList = res.data ? res.data : []
          this.count = res.data.length
        }).catch(e => {
          this.roleList = []
          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
          roleApi.editStatus(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) {
        this.dialogType = 'edit'
        data.hasChild = data.has_child
        this.ruleForm = JSON.parse(JSON.stringify(data))
        this.initFilterList(data.id)
        this.addDialogVisible = true
      },
      // 删除角色
      handleDelete(data) {
        this.$confirm('此操作将永久删除该角色，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delBtnLoading = true
          roleApi.del({id: data.id}).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            this.delBtnLoading = false
            this.tableLoading = true
            this.getAllList()
          }).catch(e => {
            this.delBtnLoading = false
          })
        })
      },
      // 重置缓存
      resetCache(res) {
        alert('直接调用接口，给提示')
      },
      // 权限
      limitDetail(data) {
        this.menuVisible = true
        let me = this
        this.$nextTick(function () {
          me.checkedKeys = data.ruleList ? data.ruleList : []
          me.$refs.tree.setCheckedKeys(me.checkedKeys);
          me.ruleForm = JSON.parse(JSON.stringify(data))
          if (me.menuList.length == 0) {
            me.queryMenuList()
          }
        })
        // if (this.btnRoles.indexOf('roleLimitBtn') > -1) {
        //   this.$message.error('您没有该权限！')
        // } else {
        //   this.$message.error('调用接口！')
        // }
      },
      queryMenuList() {
        // 设置分页
        menuApi.backMenuList().then(res => {
          this.menuList = res.data ? res.data : []
          this.treeLoading = false
        }).catch(e => {
          this.menuList = []
          this.treeLoading = false
        })
      },
      // 添加子级
      addMenu(data, type) {
        this.initRuleForm()
        this.initFilterList()
        this.$refs['ruleForm'].resetFields()
        this.addDialogVisible = 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) {
              roleApi.add(ruleForm).then(res => {
                this.addBtnLoading = false
                this.initRuleForm()
                this.$refs[formName].resetFields()
                if (type == 3) {
                  this.addDialogVisible = false
                }
                this.tableLoading = true
                this.$message({
                  type: 'success',
                  message: '添加成功！'
                })
                this.getAllList()
              }).catch(e => {
                this.addBtnLoading = false
              })
            } else {
              roleApi.edit(ruleForm).then(res => {
                this.addBtnLoading = false
                this.initRuleForm()
                this.$refs[formName].resetFields()
                this.addDialogVisible = 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">

  .role-container {
    width: 100%;

    .el-tabs {
      height: 100%;
    }

    .menu-dialog {
      .el-dialog__body {
        padding: 10px 10px;
        height: 400px;
        overflow-y: auto;
      }
    }

    .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;
      }
    }
  }

</style>
