<template>
  <div class="system-auth-group">
    <div class="category-list">
      <div class="btns" style="display: flex; justify-content: space-between; margin-bottom: 20px">
        <el-button size="mini" type="primary" icon="el-icon-edit" plain @click="showType = true"> 编辑分类 </el-button>
        <el-button size="mini" type="primary" icon="el-icon-plus" @click="onEditType(null)"> 添加分类 </el-button>
      </div>
      <el-menu :default-active="nowTypeId.toString()" @select="onSelectType">
        <el-menu-item :index="'0'">
          <div class="name" style="flex: 1">全部分类</div>
        </el-menu-item>
        <template v-for="type in typeList">
          <el-menu-item :key="type.id" :index="type.id.toString()">
            <div class="name" style="flex: 1">{{ type.typeName }}</div>
          </el-menu-item>
        </template>
      </el-menu>
    </div>
    <div class="right-wrapper">
      <el-form inline class="my-menu">
        <div>
          <el-form-item title="权限组名称" style="margin-bottom: 0">
            <el-input v-model="searchName" size="mini" placeholder="输入名称查询" style="width: 200px" clearable></el-input>
          </el-form-item>
          <el-form-item style="margin-bottom: 0">
            <el-button size="mini" @click="getData"> 查询 </el-button>
          </el-form-item>
        </div>
        <el-form-item style="margin-bottom: 0">
          <el-button size="mini" type="primary" icon="el-icon-plus" @click="onEdit(null)">添加权限组</el-button>
        </el-form-item>
      </el-form>
      <div class="item" v-for="group of groupList" :key="group.id" @click="onSelect(group)" :class="{ selected: selected == group.id }">
        <div class="name">
          <div>{{ group.permName }}</div>
          <div style="flex: 1"></div>
          <el-button size="mini" type="primary" plain icon="el-icon-setting" v-show="!isSelect" @click="goSetting(group)"> 权限设置 </el-button>
          <el-button size="mini" type="primary" plain icon="el-icon-edit" @click="onEdit(group)"></el-button>
          <el-button size="mini" type="danger" plain icon="el-icon-delete" @click="onDel(group)"></el-button>
        </div>
        <div class="selected">
          <div class="tag" v-for="item of group.dpList" :key="item.id"><i class="el-icon-s-flag" style="color: #67c23a; margin-right: 5px"></i>{{ item.name }}</div>
          <div class="tag" v-for="item of group.roleList" :key="item.id"><i class="el-icon-user-solid" style="color: #e6a23c; margin-right: 5px"></i>{{ item.name }}</div>
          <div class="tag" v-for="item of group.userList" :key="item.id"><i class="el-icon-user" style="color: #909399; margin-right: 5px"></i>{{ item.name }}</div>
        </div>
      </div>
      <el-pagination
        class="my-paging"
        @size-change="sizeChange"
        @current-change="getData"
        :current-page.sync="page.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.size"
        background
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </div>
    <el-dialog title="分类管理" :visible.sync="showType" append-to-body width="600px">
      <el-table :data="typeList" border size="mini">
        <el-table-column label="分类名" prop="typeName"></el-table-column>
        <el-table-column label="排序号" prop="sortNum"></el-table-column>
        <el-table-column label="操作" width="180px" align="center">
          <template v-slot="{ row }">
            <el-button size="mini" type="primary" plain @click="onEditType(row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="onDelType(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="编辑分类" append-to-body :visible.sync="showTypeEdit" width="600px">
      <el-form size="mini" label-width="80px">
        <el-form-item label="分类名">
          <el-input v-model="typeForm.typeName"></el-input>
        </el-form-item>
        <el-form-item label="排序值">
          <el-input v-model="typeForm.sortNum" type="number"></el-input>
        </el-form-item>
      </el-form>
      <div class="btns" style="margin-top: 30px; display: flex; justify-content: space-evenly">
        <el-button size="mini" style="width: 100px">取消</el-button>
        <el-button size="mini" style="width: 100px" type="primary" @click="onEditTypeConfirm">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑权限组" append-to-body :visible.sync="show" width="800px" custom-class="auth-group-dialog">
      <el-form size="mini" label-width="85px">
        <el-form-item label="名称">
          <el-input v-model="form.permName"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="form.typeId">
            <el-option v-for="item of typeList" :key="item.id" :label="item.typeName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="已选择项">
          <div class="selected">
            <div class="tag" v-for="item of form.dpList" :key="item.id"><i class="el-icon-s-flag" style="color: #67c23a; margin-right: 5px"></i>{{ item.name }}</div>
            <div class="tag" v-for="item of form.roleList" :key="item.id"><i class="el-icon-user-solid" style="color: #e6a23c; margin-right: 5px"></i>{{ item.name }}</div>
            <div class="tag" v-for="item of form.userList" :key="item.id"><i class="el-icon-user" style="color: #909399; margin-right: 5px"></i>{{ item.name }}</div>
          </div>
        </el-form-item>
      </el-form>
      <el-tabs type="card" v-model="activeType">
        <el-tab-pane name="dept">
          <span slot="label"><i class="el-icon-s-flag" style="color: #67c23a; margin-right: 5px"></i>部门</span>
          <el-tree
            ref="dept"
            :data="deptList"
            node-key="id"
            :props="{ label: 'title' }"
            default-expand-all
            show-checkbox
            check-strictly
            check-on-click-node
            :expand-on-click-node="false"
            @check-change="onDeptChange"
          ></el-tree>
        </el-tab-pane>
        <el-tab-pane name="role">
          <span slot="label"><i class="el-icon-user-solid" style="color: #e6a23c; margin-right: 5px"></i>角色</span>
          <el-tree
            ref="role"
            :data="roleList"
            node-key="id"
            :props="{ label: 'title' }"
            default-expand-all
            show-checkbox
            check-strictly
            check-on-click-node
            :expand-on-click-node="false"
            @check-change="onRoleChange"
          ></el-tree>
        </el-tab-pane>
        <el-tab-pane name="user">
          <span slot="label"><i class="el-icon-user" style="color: #909399; margin-right: 5px"></i>用户</span>
          <el-tree
            ref="user"
            :data="userList"
            node-key="id"
            :props="{ children: 'list' }"
            default-expand-all
            show-checkbox
            check-strictly
            check-on-click-node
            :expand-on-click-node="false"
            @check-change="onUserChange"
          ></el-tree>
        </el-tab-pane>
      </el-tabs>
      <div class="btns">
        <el-button size="small" @click="show = false">取消</el-button>
        <el-button size="small" plain type="primary" @click="onSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getDeptTree } from '@/api/system/dept'
import { roleTree } from '@/api/newbi/app'
import { getList } from '@/api/system/user'
import { save, groupPage, groupDel, typeList, typeDel, typeSave } from '@/api/system/authGroup'
export default {
  props: ['selected', 'isSelect'],
  data() {
    return {
      groupList: [],
      deptList: [],
      roleList: [],
      userList: [],
      form: {},
      show: false,
      activeType: 'dept',
      searchName: '',
      showType: false,
      typeList: [],
      typeForm: {},
      showTypeEdit: false,
      nowTypeId: 0,
      page: { size: 10, current: 1, total: 0 }
    }
  },
  created() {
    this.getType()
    getDeptTree().then((res) => {
      this.deptList = res.data.data
      getList(1, 10000).then((userRes) => {
        let users = userRes.data.data.records
        users.forEach((item) => (item.deptId = item.deptId.split(',')[0]))
        let userListPlat = []
        this.getPlat(JSON.parse(JSON.stringify(res.data.data)), userListPlat)
        userListPlat.forEach((i) => (i.parent = userListPlat.find((j) => j.id == i.parentId)))
        this.userList = userListPlat
          .map((item) => {
            let id = item.id
            let label = item.title
            let parent = item.parent
            while (parent) {
              label = parent.title + ' / ' + label
              parent = parent.parent
            }
            let list = users.filter((i) => i.deptId == id).map((i) => ({ id: i.id, label: i.name }))
            return { id, label, list, disabled: true }
          })
          .filter((i) => i.list.length)
      })
    })
    roleTree().then((res) => {
      this.roleList = res.data.data
    })
  },
  methods: {
    goSetting(group) {
      this.$router.push('/system/authGroupSetting?id=' + group.id)
    },
    sizeChange(size) {
      this.page.size = size
      this.getData()
    },
    onSelectType(index) {
      this.nowTypeId = index
      this.page.current = 1
      this.getData()
    },
    onDelType(type) {
      this.$confirm('是否删除此分类', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          typeDel({ id: type.id }).then((res) => {
            this.$message({ type: 'success', message: '已删除' })
            this.getType()
          })
        })
        .catch(() => {})
    },
    onEditTypeConfirm() {
      if (!this.typeForm.typeName) {
        return this.$message({ message: '请输入分类名', type: 'warning' })
      }
      typeSave(this.typeForm).then((res) => {
        this.$message({ message: '已保存', type: 'success' })
        this.getType()
        this.showTypeEdit = false
      })
    },
    onEditType(type) {
      if (type) {
        this.typeForm = { ...type }
      } else {
        this.typeForm = { typeName: '', sortNum: 0 }
      }
      this.showTypeEdit = true
    },
    getType() {
      typeList().then((res) => {
        this.typeList = res.data.data.sort((a, b) => (a.sortNum > b.sortNum ? 1 : -1))
        this.nowTypeId = 0
        this.getData()
      })
    },
    onSelect(group) {
      if (this.isSelect) {
        this.$emit('select', group.id, group.permName)
      }
    },
    onDel(group) {
      this.$confirm('是否删除此权限组', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          groupDel({ permId: group.id }).then((res) => {
            this.$message({ type: 'success', message: '已删除' })
            this.getData()
          })
        })
        .catch(() => {})
    },
    onUserChange() {
      this.$nextTick(() => {
        let nodes = this.$refs.user.getCheckedNodes()
        this.form.userList = nodes.map((i) => ({ id: i.id, name: i.label }))
      })
    },
    onDeptChange() {
      this.$nextTick(() => {
        let nodes = this.$refs.dept.getCheckedNodes()
        this.form.dpList = nodes.map((i) => ({ id: i.id, name: i.title }))
      })
    },
    onRoleChange() {
      this.$nextTick(() => {
        let nodes = this.$refs.role.getCheckedNodes()
        this.form.roleList = nodes.map((i) => ({ id: i.id, name: i.title }))
      })
    },
    getData() {
      let { size, current } = this.page
      let data = { current, size, permName: this.searchName }
      if (this.nowTypeId) {
        data.typeId = this.nowTypeId
      }
      groupPage(data).then((res) => {
        let { records, total } = res.data.data
        this.page.total = total
        this.groupList = records.map((i) => {
          let { dpList, roleList, userList } = JSON.parse(i.permJson)
          return { ...i, dpList, roleList, userList }
        })
      })
    },
    onSubmit() {
      let { permName, dpList, roleList, userList, typeId } = this.form
      if (!permName || !typeId) {
        return this.$message({ type: 'warning', message: '请填写完整' })
      }
      let data = { permName, typeId, permJson: JSON.stringify({ dpList, roleList, userList }) }
      if (this.form.id) {
        data.id = this.form.id
      }
      save(data).then((res) => {
        this.$message({ type: 'success', message: '已保存' })
        this.show = false
        this.getData()
      })
    },
    getPlat(source, target) {
      source.forEach((i) => {
        target.push(i)
        if (i.children && i.children.length) {
          this.getPlat(i.children, target)
        }
      })
    },
    onEdit(item) {
      if (item) {
        this.form = item
      } else {
        this.form = { permName: '', dpList: [], roleList: [], userList: [], typeId: 0 }
      }
      this.show = true
      this.$nextTick(() => {
        this.$refs.dept.setCheckedKeys(item ? item.dpList.map((i) => i.id) : [])
        this.$refs.role.setCheckedKeys(item ? item.roleList.map((i) => i.id) : [])
        this.$refs.user.setCheckedKeys(item ? item.userList.map((i) => i.id) : [])
      })
    }
  }
}
</script>
<style lang="scss">
.system-auth-group {
  height: 100%;
  overflow: hidden;
  display: flex;
  .category-list {
    flex: 0 0 260px;
    padding-top: 10px;
    padding-right: 10px;
    border-right: 1px solid #ccc;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    .el-menu {
      flex: 1;
      overflow-y: auto;
      .el-menu-item {
        padding: 0 5px 0 10px;
        display: flex;
        align-items: center;
        height: 50px;
        line-height: 50px;
        .name {
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
    }
  }
  .right-wrapper {
    padding: 10px 10px 0;
    flex: 1;
    overflow-y: auto;
    .item {
      margin: 10px;
      border: 1px solid #dcdfe6;
      transition: all 0.2s;
      &:hover {
        border: 1px solid #409eff;
      }
      &.selected {
        border: 1px solid #409eff;
        .name {
          color: #409eff;
        }
      }
      .name {
        display: flex;
        align-items: center;
        padding: 0 20px;
        line-height: 40px;
        font-weight: 600;
        color: #666;
        font-size: 16px;
      }
      .selected {
        max-height: 100px;
        overflow-y: auto;
        padding: 5px;
        .tag {
          display: inline-block;
          margin: 5px;
          font-size: 14px;
          line-height: 16px;
        }
      }
    }
  }
}
.auth-group-dialog {
  .selected {
    height: 100px;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    padding: 5px;
    .tag {
      display: inline-block;
      margin: 5px;
      font-size: 14px;
      line-height: 16px;
    }
  }
  .btns {
    display: flex;
    justify-content: space-evenly;
    margin-top: 30px;
    .el-button {
      width: 80px;
    }
  }
}
</style>
