<template>
  <div class="app-container">
    <!--表单组件-->
    <eForm ref="form" :is-add="isAdd" />
    <!--工具栏-->
    <div class="head-container">
      <!-- 搜索 -->
      <el-input
        v-model="query.value"
        clearable
        placeholder="输入名称搜索"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="toQuery"
      />
      <el-button
        class="filter-item"
        size="mini"
        type="success"
        icon="el-icon-search"
        @click="toQuery"
      >搜索</el-button>
      <!-- 新增 -->
      <div
        style="display: inline-block;margin: 0px 2px;"
      >
        <el-button
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="add"
        >新增</el-button>
      </div>
    </div>
    <el-row :gutter="15">
      <!--角色管理-->
      <el-col :span="14">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
            <!-- <div id="opt" style="float: right">
              <el-radio-group v-model="opt" size="mini">
                <el-radio-button label="菜单分配" />
                <el-radio-button label="权限分配" />
              </el-radio-group>
            </div> -->
          </div>
          <el-table
            v-loading="loading"
            :data="data"
            highlight-current-row
            size="small"
            style="width: 100%;"
            @current-change="handleCurrentChange"
          >
            <el-table-column prop="name" label="名称" />
            <!-- <el-table-column prop="level" label="角色级别" /> -->
            <el-table-column :show-overflow-tooltip="true" prop="remark" label="描述" />
            <el-table-column :show-overflow-tooltip="true" prop="createTime" label="创建日期">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="130px"
              align="center"
              fixed="right" 
            >
              <template slot-scope="scope">
                <el-button
                  v-if="defaultRoleId.findIndex(item => item === scope.row.id) === -1"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="edit(scope.row)"
                />
                <el-popover
                  :ref="scope.row.id"
                  placement="top"
                  width="180"
                >
                  <p>确定删除本条数据吗？</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
                    <el-button
                      :loading="delLoading"
                      type="primary"
                      size="mini"
                      @click="subDelete(scope.row.id)"
                    >确定</el-button>
                  </div>
                  <el-button
                    v-if="defaultRoleId.findIndex(item => item === scope.row.id) === -1"
                    slot="reference"
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    />
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <el-pagination
            :total="total"
            :current-page="page + 1"
            style="margin-top: 8px;"
            layout="total, prev, pager, next, sizes"
            @size-change="sizeChange"
            @current-change="pageChange"
          />
        </el-card>
      </el-col>
      <!-- 授权 -->
      <el-col :span="5">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配菜单" placement="top">
              <span class="role-span">菜单分配</span>
            </el-tooltip>
            <el-button
              :disabled="!showButton || !currentId"
              :loading="menuLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu"
            >保存</el-button>
          </div>
          <el-tree
            ref="menu"
            :data="menus"
            :default-checked-keys="menuIds"
            :props="defaultProps"
            accordion
            show-checkbox
            node-key="id"
            @node-click="selectMenu"
          />
        </el-card>
      </el-col>
      <el-col :span="5">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配权限" placement="top">
              <span class="role-span">权限分配</span>
            </el-tooltip>
            <el-button
              :disabled="!showButton || !savePermissionParams.roleId"
              :loading="permissionLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="savePermission"
            >保存</el-button>
          </div>
          <el-tree
            ref="permission"
            :data="permissionData"
            :default-checked-keys="permissionIds"
            :props="permissionProps"
            show-checkbox
            accordion
            node-key="id"
            @check="selectPermission"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import checkPermission from '@/utils/permission'
// import initData from '@/mixins/initData'
import { getPermissionTree } from '@/api/permission'
import { getMenusTree } from '@/api/menu'
import { parseTime } from '@/utils/index'
import eForm from './form'
import { editPermission, editMenu, get, del, getAll } from '@/api/role'
import { DATA_SCOPE } from '@/utils/options'
export default {
  name: 'role',
  components: { eForm },
  // mixins: [initData],
  data() {
    return {
      loading: true, data: [], page: 0, size: 10, total: 0, url: '', params: {}, query: {}, time: 170, isAdd: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      permissionProps: {
        children: 'children',
        label: 'name'
      },
      currentId: 0,
      permissionLoading: false,
      menuLoading: false,
      showButton: false,
      delLoading: false,
      permissionIds: [],
      menus: [],
      menuIds: [],
      defaultRoleId: [1, 2, 3, 4, 5],
      permissionData: [],
      savePermissionParams: {
        permissionIds: [],
        roleId: 0
      }
    }
  },
 computed: {
    ...mapGetters(['user'])
  },
  async created() {
    await this.getMenus()
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    parseTime,
    checkPermission,
    async init() {
      const data = await getAll({ current: this.page + 1, size: this.size, name: this.query.value })
      this.data = data.data.list
      this.total = data.data.total
      this.loading = false
      this.currentId = ''
      this.savePermissionParams.roleId = 0
      this.savePermissionParams.permissionIds = []
      this.permissionData.value = []
      this.$refs.menu.setCheckedKeys([])
      this.$refs.permission.setCheckedKeys([])
    },
    pageChange(e) {
      this.page = e - 1
      this.init()
    },
    sizeChange(e) {
      this.page = 0
      this.size = e
      this.init()
    },
    // 预防删除第二页最后一条数据时，或者多选删除第二页的数据时，页码错误导致请求无数据
    dleChangePage(size) {
      if (size === undefined) {
        size = 1
      }
      if (this.data.length === size && this.page !== 0) {
        this.page -= 1
      }
    },
    toQuery() {
      this.page = 0
      this.init()
    },
    beforeInit() {
      this.$refs.permission.setCheckedKeys([])
      this.$refs.menu.setCheckedKeys([])
      this.showButton = false
      this.url = 'roles'
      const sort = 'level,asc'
      const query = this.query
      const value = query.value
      this.params = { page: this.page, size: this.size, sort: sort }
      if (value) {
        this.params['name'] = value
      }
      return true
    },
    subDelete(id) {
      this.delLoading = true
      del({ id })
        .then(res => {
          this.delLoading = false
          this.$refs[id].doClose()
          this.dleChangePage()
          this.init()
          this.$notify({
            title: '删除成功',
            type: 'success',
            duration: 2500
          })
        })
        .catch(err => {
          this.delLoading = false
          this.$refs[id].doClose()
          console.log(err)
        })
    },
    async getMenus() {
      // { userId: this.user.user.userId }
     await getMenusTree({}).then(res => {
        this.menus = res.data
      })
    },
    handleCurrentChange(val) {
      if (val) {
        const _this = this
        // 清空权限与菜单的选中
        this.$refs.permission.setCheckedKeys([])
        this.$refs.menu.setCheckedKeys([])
        // 保存当前的角色id
        this.currentId = val.id
        // 点击后显示按钮
        this.showButton = true
        // 初始化
        this.menuIds = []
        this.permissionIds = []
        // 菜单数据需要特殊处理
        val.menuList.forEach(function(data, index) {
          let add = true
          for (let i = 0; i < val.menuList.length; i++) {
            if (data.id === val.menuList[i].pid) {
              add = false
              break
            }
          }
          if (add) {
            _this.menuIds.push(data.id)
          }
        })

        this.savePermissionParams.roleId = val.id
        this.savePermissionParams.permissionIds = val.permissionList.map((item) => item.id)
        this.$refs.permission.setCheckedKeys(this.savePermissionParams.permissionIds)
      }
    },
    savePermission() {
      this.permissionLoading = true
      // const role = { roleId: this.currentId, permissionIds: [] }
      // const permission = []
      // this.$refs.permission.getCheckedNodes(true).forEach(data => {
      //   permission.push(data.id)
      // })
      // role.permissionIds = permission
      editPermission(this.savePermissionParams)
        .then(res => {
          this.$notify({
            title: '保存成功',
            type: 'success',
            duration: 2500
          })
          this.permissionLoading = false
          this.update()
        })
        .catch(err => {
          this.permissionLoading = false
          console.log(err)
        })
    },
    saveMenu() {
      this.menuLoading = true
      const role = { roleId: this.currentId, menuIds: [] }
      const menus = []
      this.$refs.menu.getCheckedNodes(true).forEach(data => {
            menus.push(data.id)
      })
      role.menuIds = menus
      editMenu(role)
        .then(res => {
          if (res.code === 0) {
            this.$notify({
              title: '保存成功',
              type: 'success',
              duration: 2500
            })
            this.update()
          }
          this.menuLoading = false
        })
        .catch(err => {
          this.menuLoading = false
          console.log(err.response.data.message)
        })
    },
    update() {
      // 无刷新更新 表格数据
      get({ id: this.currentId }).then(res => {
        for (let i = 0; i < this.data.length; i++) {
          if (res.data.id === this.data[i].id) {
            this.data[i] = res.data
            break
          }
        }
      })
    },
    add() {
      this.isAdd = true
      this.$refs.form.dialog = true
    },
    edit(data) {
      this.isAdd = false
      const _this = this.$refs.form
      // _this.deptIds = []
      _this.form = {
        id: data.id,
        name: data.name,
        remark: data.remark,
        depts: data.depts,
        dataScope: data.dataScope,
        code: data.code,
        level: data.level
      }
      _this.dialog = true
    },
    dataScopeFmt(row, column, cellValue) {
      return DATA_SCOPE[cellValue]
    },
    // 选中菜单，展示菜单页面按钮权限列表
    selectMenu(row) {
      this.permissionData = row.permissions
      this.$refs.permission.setCheckedKeys(this.savePermissionParams.permissionIds)
    },
    selectPermission(row, status) {
      const indexOf = this.savePermissionParams.permissionIds.indexOf(row.id)
      if (indexOf === -1) {
        this.savePermissionParams.permissionIds.push(row.id)
      } else {
        this.savePermissionParams.permissionIds.splice(indexOf, indexOf + 1)
      }
    }
  }
}
</script>

<style>
.el-tree .el-tree-node__content {
  align-items: baseline !important;
}
</style>

<style rel="stylesheet/scss" lang="scss" >
.role-span {
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}
</style>
