<template>
  <div class="app-container">
    <!-- 查询表单区域 -->
    <el-form :model="listQuery" size="small" :inline="true" label-position="top">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="角色名称">
            <el-input v-model="listQuery.roleName" placeholder="请输入角色名称" style="width: 100%" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="搜索">
            <el-button style="width: 100%;" type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="重置">
            <el-button style="width: 100%;" icon="el-icon-refresh" type="primary" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" class="editButton" size="small" icon="el-icon-plus" @click="handleCreate">添加</el-button>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <div class="border-card">
      <el-table height="450" size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>
        <el-table-column type="index" label="序号" header-align="center" align="center" width="55"></el-table-column>
        <el-table-column align="center" min-width="100px" label="角色名称" prop="roleName"></el-table-column>
        <el-table-column align="center" label="操作" width="240px" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" class="editText" size="small" @click="handleUpdate(scope.row, false)">编辑</el-button>
            <el-button type="text" icon="el-icon-lock" class="plusText" size="small" @click="handleUpdate(scope.row, true)">权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
          :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="40%">
      <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px">
        <template v-if="!dialogMain">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="dataForm.roleName" placeholder="请输入角色名称"></el-input>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="角色权限">
            <el-tree
              :data="router"
              show-checkbox
              node-key="name"
              ref="tree"
              :props="defaultProps">
            </el-tree>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <template v-else>
          <el-button v-if="!dialogMain" type="primary" @click="updateRoleNames">确定</el-button>
          <el-button v-else type="primary" @click="updateRoleList">确定</el-button>
        </template>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { asyncRouterMap } from '@/router'
import { addRole, roleList, updateRoleName, getRoleMenu, updateRoleMenu } from '@/api/role'
import waves from '@/directive/waves' // 水波纹指令

export default {
  name: 'role',
  directives: {
    waves
  },
  data() {
    return {
      list: null,
      total: null,
      listLoading: true,
      dialogMain: false,
      router: asyncRouterMap,
      listQuery: {
        page: 1,
        limit: 20,
        roleName: ''
      },
      dataForm: {
        roleName: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑角色',
        create: '添加角色'
      },
      rules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      downloadLoading: false,
      data2: [
        {
          id: 1,
          label: '一级 1',
          children: [
            {
              id: 4,
              label: '二级 1-1',
              children: [
                {
                  id: 9,
                  label: '三级 1-1-1'
                },
                {
                  id: 10,
                  label: '三级 1-1-2'
                }
              ]
            }
          ]
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  created() {
    this.getList()
    this.router = this.initRouter(this.router)
  },
  methods: {
    getList() {
      this.listLoading = true
      roleList(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleQuery() {
      this.listQuery.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.listQuery = {
        roleName: ''
      }
      this.handleQuery()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        role: undefined
      }
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedKeys([])
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogMain = false
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          addRole(this.dataForm).then(response => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row, type) {
      this.dialogMain = type
      this.dataForm = Object.assign({}, { roleName: row.roleName, id: row.id })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      if (type) {
        this.getRoleList()
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateRoleNames() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateRoleName(this.dataForm).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    updateRoleList() {
      var roleList = this.$refs.tree.getCheckedKeys().join(',')
      updateRoleMenu({
        roleId: this.dataForm.id,
        menuList: roleList
      }).then(() => {
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    initRouter(list) {
      var router = []
      list.map((obj) => {
        if (obj.meta) {
          obj.label = obj.meta.title
          if (obj.children) this.initRouter(obj.children)
          router.push(obj)
        }
      })
      return router
    },
    getRoleList() {
      getRoleMenu({ roleId: this.dataForm.id }).then(response => {
        this.$refs.tree.setCheckedKeys(response.data.data)
      })
    }
  }
}
</script>