<template>
  <div class="app-container">
    <el-button type="primary" @click="handCreate">新增角色</el-button>

    <el-table 
    :data="rolesList" 
    style="width: 100%;margin-top:30px;" 
    v-loading="listLoading"
    border>
      <el-table-column align="center" label="角色名称" width="220">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="角色描述">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleUpdate(scope)" icon="el-icon-edit"></el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)" icon="el-icon-delete"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='update'?'编辑角色':'新增角色'">
      <el-form :model="role" label-width="80px" label-position="left">
        <el-form-item label="名称">
          <el-input v-model="role.name" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="role.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="角色描述"
          />
        </el-form-item>
        <el-form-item label="权限">
          <el-tree
            v-model="role.perms"
            ref="tree"
            :check-strictly="checkStrictly"
            :data="permsData"
            show-checkbox
            node-key="id"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { genTree,deepClone } from '@/utils'
import { getConsumerRoleAll, createConsumerRole, deleteConsumerRole, updateConsumerRole, getConsumerPermAll } from '@/api/crm'

const defaultRole = {
  id: '',
  name: '',
  description: '',
  perms: []
}

export default {
  data() {
    return {
      role: Object.assign({}, defaultRole),
      permsData: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'create',
      checkStrictly:true,
      listLoading:true
    }
  },
  computed: {
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getPerms()
    this.getRoles()
  },
  methods: {
    async getPerms() {
      const res = await getConsumerPermAll()
      // this.serviceRoutes = res.data
      this.permsData = genTree(res.data)
    },
    async getRoles() {
      this.listLoading = true
      const res = await getConsumerRoleAll()
      this.rolesList = res.data
      this.listLoading = false
    },

    handCreate() {
      this.role = Object.assign({}, defaultRole)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'create'
      this.dialogVisible = true
    },
    handleUpdate(scope) {
      this.dialogType = 'update'
      this.dialogVisible = true
      this.role = deepClone(scope.row)
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.role.perms)
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('确认删除该角色吗?该角色成员将丢失权限!', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteConsumerRole(row.id)
          this.rolesList.splice($index, 1)
          this.$message({
            type: 'success',
            message: '成功删除!'
          })
        })
        .catch(err => { console.error(err) })
    },

    async confirmRole() {
      const isEdit = this.dialogType === 'update'
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      this.role.perms = checkedKeys

      if (isEdit) {
        await updateConsumerRole(this.role.id, this.role)
        for (let index = 0; index < this.rolesList.length; index++) {
          if (this.rolesList[index].id === this.role.id) {
            this.rolesList.splice(index, 1, Object.assign({}, this.role))
            break
          }
        }
      } else {
        this.role.perms = this.$refs.tree.getCheckedKeys()
        const { data } = await createConsumerRole(this.role)
        this.getRoles()
      }

      const { description, name } = this.role
      this.dialogVisible = false
      this.$message.success('成功')
    },
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
