<template>
  <div>
    <el-card v-if="showGoBack" style="margin-bottom: 20px">
      <el-page-header @back="goBack" />
    </el-card>
    <el-row :gutter="20">
      <el-col :xs="24" :sm="7" :md="6" :lg="5" :xl="4">
        <el-card class="custom-menu box-card">
          <div slot="header" class="clearfix">
            <span>角色列表</span>
          </div>
          <el-menu
            class="el-menu"
            :default-active="defaultActive"
            @select="handleSelect"
          >
            <el-menu-item-group
              v-for="category in roleCategoryList"
              :key="category.id"
            >
              <template slot="title">{{ category.tenantName }}</template>
              <el-menu-item
                v-for="role in category.roles"
                :key="role.id"
                :index="role.id.toString()"
              >
                {{ role.roleName }}
              </el-menu-item>
            </el-menu-item-group>
          </el-menu>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="17" :md="18" :lg="19" :xl="20">
        <el-card>
          <el-tabs v-model="activeName">
            <el-tab-pane label="功能权限" name="first">
              <el-tree
                ref="tree"
                :data="menuList"
                :props="defaultProps"
                show-checkbox
                node-key="rowKey"
                @check="handleCheck"
              >
                <span slot-scope="{ node, data }">
                  <el-tag size="mini" :type="tagType(data.type)">{{ tagName(data.type) }}</el-tag>
                  <span> {{ node.label }}</span>
                </span>
              </el-tree>
            </el-tab-pane>
            <el-tab-pane label="数据权限" name="second">
              <el-table
                :data="tableData"
                :show-header="false"
                style="width: 100%"
              >
                <el-table-column
                  prop="name"
                  label="姓名"
                />
                <el-table-column
                  prop="address"
                  label="地址"
                >
                  <template slot-scope="prop">
                    <el-radio-group v-model="prop.row.dataPerm" @change="(label) => onTableChange(prop.row)">
                      <el-radio :disabled="prop.row.userDataPerm > 0" :label="0">全部</el-radio>
                      <el-radio :disabled="prop.row.userDataPerm > 1" :label="1">租户</el-radio>
                      <el-radio :disabled="prop.row.userDataPerm > 2" :label="2">部门</el-radio>
                    </el-radio-group>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
          <div class="buttons-group" style="margin-top: 20px;text-align: center">
            <el-button
              v-permission="'AuthMgr_setting'"
              type="primary"
              @click="saveRoleAuth"
            >保存
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getMenuList } from '@/api/system-management/menu-management'
import { getAllRoleCategoryList, getRoleAuth, setRoleAuth } from '@/api/system-management/auth-management'
import _ from 'lodash'

export default {
  name: 'RoleManagement',
  data() {
    return {
      showGoBack: false,
      form: {
        input: null,
        status: null
      },
      activeName: 'first',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      menuList: [],
      roleCategoryList: [],
      tableData: [],
      checkedKeys: [],
      currentRow: {},
      defaultActive: null,
      currentRole: null
    }
  },
  created() {
    this.showGoBack = this.$route.query.id !== undefined
    this.init()
      .then(_ => {})
      .catch(err => {
        console.error(err)
        this.$message.error('遇到问题请稍后再试')
      })
  },
  methods: {
    async init() {
      try {
        const { data } = await getMenuList()
        this.menuList = data
        const roleCategoryList = await getAllRoleCategoryList({ type: 2 })
        this.roleCategoryList = roleCategoryList.data
        if (!this.showGoBack) {
          this.setDefaultActive(roleCategoryList.data)
        } else {
          this.defaultActive = this.$route.query.id.toString()
          this.getRoleAuth(this.$route.query.id)
        }
        return {}
      } catch (e) {
        throw new Error(e)
      }
    },
    setDefaultActive(data) {
      if (data.length > 0) {
        this.defaultActive = data[0].roles[0].id.toString()
        this.getRoleAuth(data[0].roles[0].id)
      }
    },
    setDataPerm(data) {
      data.forEach(v => {
        if (!v.dataPerm) {
          v.dataPerm = null
        }
        if (v.children) {
          this.setDataPerm(v.children)
        }
      })
    },
    getMenuList() {
      getMenuList()
        .then(res => {
          const { data } = res
          this.menuList = data
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    goBack() {
      this.$router.go(-1)
    },
    handleSelect(i) {
      this.getRoleAuth(i)
    },
    getRoleAuth(id) {
      getRoleAuth({ roleId: id })
        .then(res => {
          const { data } = res
          this.setDataPerm(this.menuList)
          this.$nextTick()
            .then(_ => {
              // 设置目前勾选的节点
              const rowKeyList = data.rowKeyList.map(v => {
                return v.rowKey
              })
              this.$refs.tree.setCheckedKeys(rowKeyList)
              const checkedNodes = this.$refs.tree.getCheckedNodes()
              checkedNodes.forEach(v => {
                data.rowKeyList.forEach(i => {
                  if (i.rowKey === v.rowKey) {
                    v.dataPerm = i.dataPerm
                  }
                })
              })
              // 设置目前勾选的节点(更新 DataPerm)
              this.$refs.tree.setCheckedNodes(checkedNodes)
              // 设置 tableData
              this.setTableData()
              this.currentRole = id
            })
            .catch(err => {
              console.error(err)
            })
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    onTableChange(row) {
      // 根据 rowKey 去更新 dataPerm
      // this.$refs.tree.updateKeyChildren(row.rowKey, row)
      // eslint-disable-next-line no-unused-vars
      let node = this.$refs.tree.getNode(row.rowKey)
      node = row
      this.updateDataPerm(this.menuList, row.rowKey, row.dataPerm)
    },
    updateDataPerm(data, rowKey, dataPerm) {
      data.forEach(v => {
        if (v.rowKey === rowKey) {
          v.dataPerm = dataPerm
        } else if (v.children) {
          this.updateDataPerm(v.children, rowKey, dataPerm)
        }
      })
    },
    saveRoleAuth() {
      const rowKeyList = this.$refs.tree.getCheckedNodes().map(v => {
        return {
          rowKey: v.rowKey,
          dataPerm: v.dataPerm,
          type: v.type
        }
      })
      let warning = false
      rowKeyList.forEach(value => {
        if (value.type === 1 && value.dataPerm === null) warning = true
      })
      if (!warning) {
        const params = {
          roleId: this.currentRole,
          rowKeyList: rowKeyList.map(v => {
            return {
              rowKey: v.rowKey,
              dataPerm: v.dataPerm
            }
          })
        }
        setRoleAuth(params)
          .then(_ => {
            this.$message.success('操作成功')
          })
          .catch(err => {
            this.$message.error('操作失败')
            console.error(err.message)
          })
      } else {
        this.$message.warning('请选择数据权限')
      }
    },
    handleCheck(data, checked) {
      const { checkedKeys } = checked
      this.checkedKeys = checkedKeys
      // 节点选中状态发生变化后重新计算 tableData
      this.setTableData()
    },
    setTableData() {
      // 获取目前被选中的节点所组成的数组并且过滤出 type 为1的值
      const checkedNodes = this.$refs.tree.getCheckedNodes().filter(v => v.type === 1)
      this.tableData = _.cloneDeep(checkedNodes)
    },
    tagType(data) {
      const typeName = {
        '-1': 'danger',
        '0': '',
        '1': 'success',
        '2': 'warning'
      }
      return typeName[data]
    },
    tagName(data) {
      const tagName = {
        '-1': '系统',
        '0': '菜单',
        '1': '页面',
        '2': '按钮'
      }
      return tagName[data]
    }
  }
}
</script>

<style scoped lang="scss">
  .custom-menu .el-menu{
    border-right: none;
  }
  .box-card{
    ::v-deep .el-card__body{
      min-height: calc(100vh - 150px);
    }
  }
</style>
