<template>
  <div>
    <div>
      <el-form :inline="true" class="orderform" size="mini">
        <el-row>
          <el-form-item label="角色名称:">
            <el-input v-model="tag" style="width: 250px" placeholder="请输入..." class="search_tag" clearable/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="btn_search()"><i class="el-icon-search"/> 搜索</el-button>
            <el-button @click="btn_clear()"><i class="el-icon-remove-outline"/> 重置</el-button>
            <el-button type="primary" icon="el-icon-plus" @click="addRole">添加</el-button>
          </el-form-item>
        </el-row>
      </el-form>
      <el-table
        ref="multipleTable"
        :data="tableData"
        :highlight-current-row="true"
        :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
        :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}"
        border>
        <el-table-column
          prop="id"
          label="序列号"/>
        <el-table-column
          prop="roleName"
          label="角色名称"/>
        <el-table-column
          prop="description"
          label="备注"/>
        <el-table-column
          fixed="right"
          label="操作">
          <template slot-scope="scope">
            <el-button v-if="scope.row.roleName !== '管理员'" type="text" @click="editRole(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.roleName !== '管理员'" type="text" @click="deleteRoleConfirm(scope.row)">删除</el-button>
            <el-button type="text" @click="setRoleAuth(scope.row.id)">授权</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mydiv">
        <el-pagination
          :current-page.sync="pageNo"
          :page-sizes="[10, 50, 100, 300,1000]"
          :page-size="pageSize"
          :total="totalDataNumber"
          layout="sizes,total, prev, pager, next"
          class="table-pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>

    </div>
    <!--弹出框-->
    <el-dialog :visible.sync="dialogFormVisiable" title="添加角色">
      <el-form :rules="rules" :model="addForm" label-width="100px" >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" placeholder="请输入角色名称" size="mini"/>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="addForm.description" rows="3" type="textarea" show-word-limit maxlength="100" placeholder="请输入备注，最长100字"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="addRoleCancel">取 消</el-button>
        <el-button size="mini" type="primary" @click="addRoleSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogModifyVisiable" title="修改角色">
      <el-form :rules="rules" :model="modifyForm" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="modifyForm.roleName" placeholder="请输入角色名称" size="mini"/>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="modifyForm.description" rows="3" type="textarea" show-word-limit maxlength="100" placeholder="请输入备注，最长100字"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="updateRoleCancel">取 消</el-button>
        <el-button size="mini" type="primary" @click="updateRole">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 点击删除按钮，删除确认框-->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="提示"
      width="30%">
      <span>确定删除选择的角色? </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleClickDelete">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 授权框-->
    <el-dialog :visible.sync="dialogAuthVisiable" title="设置权限">
      <el-form>
        <!-- <el-collapse
          v-for="book in apiList"
          v-model="activeNames"
          :key="book.name">
          <el-collapse-item :title = "book.name" :name="book.name">
            <el-checkbox-group v-model="dataModel">
              <el-checkbox
                v-for="api in book.apis"
                :key="api.value"
                :label="api.value"
              >{{ api.label }}</el-checkbox>
            </el-checkbox-group>
          </el-collapse-item>
        </el-collapse> -->
        <el-tabs tab-position="left" style="height: 300px;">
          <el-tab-pane v-for="(book,index) in apiList" :key="index" :label="book.name">
            <el-checkbox :indeterminate="!book.isAll&&dataModel.length>0" v-model="book.isAll" @change="handleCheckAllChange(book)">全选当前分类</el-checkbox>
            <el-checkbox-group v-model="dataModel">
              <el-checkbox
                v-for="api in book.apis"
                :key="api.value"
                :label="api.value"
                @change="($event)=>{
                  if(!$event){
                    book.isAll = false
                  }
                }"
              >{{ api.label }}</el-checkbox>
            </el-checkbox-group>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" >
        <el-button type="primary" @click="setAuthCancel">取 消</el-button>
        <el-button type="primary" @click="setAuthSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import APP_CONFIG from "../../../public/config";

export default {
  name: 'Index',
  computed: {
    APP_CONFIG() {
      return APP_CONFIG
    }
  },
  data() {
    return {
      rules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },
      tag: '',
      allData: [], // 所有前端分页数据
      tableData: [], // 表格数据 仅展示当前页的数据
      pageNo: 1, // 当前页数
      totalDataNumber: 0, // 总记录数
      pageSize: 10,
      formLabelWidth: '100px', // 弹出框form宽
      dialogAuthVisiable: false,
      dialogFormVisiable: false,
      dialogModifyVisiable: false,
      deleteDialogVisible: false,
      addForm: {
        roleName: '',
        description: ''
      },
      modifyForm: {
        id: '',
        roleName: '',
        description: ''
      },
      apiList: [],
      activeNames: [],
      dataModel: [],
      roleId: ''
    }
  },
  created() {
    this.btn_search()
    this.searchAllApis()
  },
  mounted() {
  },
  methods: {
    // 全选
    handleCheckAllChange(row) {
      const apis = row.apis
      const List = apis.map(item => item.value)
      this.dataModel = this.dataModel.filter(item => !List.includes(item))
      if (row.isAll) {
        this.dataModel.push(...List)
      } else {
        this.dataModel = this.dataModel.filter(item => !List.includes(item))
      }
    },
    btn_search() {
      const vm = this
      axios.get(process.env.BASE_API + '/role/list', {
        params: {
          tag: this.tag
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.totalDataNumber = 0
          vm.allData = []
          vm.tableData = []
        } else {
          vm.totalDataNumber = parseInt(obj.total)
          if (vm.totalDataNumber > 0) {
            vm.allData = obj.data
            vm.tableData = obj.data.slice(0, vm.pageSize)
          } else {
            vm.allData = []
            vm.tableData = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    btn_clear() {
      this.tag = ''
      this.btn_search()
    },
    handleCurrentChange() {
      this.tableData = this.allData.slice((this.pageNo - 1) * this.pageSize, this.pageNo * this.pageSize)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.tableData = this.allData.slice((this.pageNo - 1) * this.pageSize, this.pageNo * this.pageSize)
    },
    addRole() {
      this.dialogFormVisiable = true
    },
    addRoleCancel() {
      this.dialogFormVisiable = false
      this.clearForm()
    },
    clearForm() {
      this.addForm.roleName = ''
      this.addForm.description = ''
    },
    addRoleSubmit() {
      const vm = this
      var params = new URLSearchParams()
      if (vm.addForm.roleName === '') {
        this.$message.error('请输入角色名称')
        return
      }
      params.append('roleName', vm.addForm.roleName)
      params.append('description', vm.addForm.description)
      axios.post(process.env.BASE_API + '/role/create', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.pageNo = 1
          vm.clearForm()
          vm.btn_search()
        }
      }).catch(function(error) {
        alert(error)
      })
      this.dialogFormVisiable = false
    },
    editRole(row) {
      this.dialogModifyVisiable = true
      this.modifyForm = row
    },
    updateRoleCancel() {
      this.dialogModifyVisiable = false
      this.modifyForm = ''
      this.btn_search()
    },
    updateRole() {
      const vm = this
      var params = new URLSearchParams()
      params.append('id', vm.modifyForm.id)
      params.append('roleName', vm.modifyForm.roleName)
      params.append('description', vm.modifyForm.description)
      axios.post(process.env.BASE_API + '/role/update', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.pageNo = 1
          vm.btn_search()
        }
        vm.modifyForm = ''
      }).catch(function(error) {
        alert(error)
      })
      this.dialogModifyVisiable = false
    },
    deleteRoleConfirm(row) {
      this.roleId = row.id
      this.deleteDialogVisible = true
    },
    handleClickDelete() {
      const vm = this
      var params = new URLSearchParams()
      params.append('id', vm.roleId)
      axios.post(process.env.BASE_API + '/role/delete', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.pageNo = 1
          vm.btn_search()
        }
      })
      this.deleteDialogVisible = false
    },
    setRoleAuth(value) {
      this.roleId = value
      this.getAuth(value)
    },
    setAuthCancel() {
      this.dialogAuthVisiable = false
    },
    setAuthSubmit() {
      const vm = this
      const arr = []
      vm.apiList.forEach(item => {
        if (item.apis && item.apis.length > 0) {
          item.apis.forEach(api => {
            arr.push(api.value)
          })
        }
      })
      const noAuths = arr.filter(item => !vm.dataModel.includes(item))
      var params = new URLSearchParams()
      params.append('roleId', vm.roleId)
      params.append('auths', vm.dataModel)
      // 未勾选状态
      params.append('noAuths', noAuths)
      axios.post(process.env.BASE_API + '/role/setauth', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message.success('授权成功')
          vm.dialogAuthVisiable = false
        }
      })
    },
    searchAllApis() {
      const vm = this
      axios.get(process.env.BASE_API + '/apimngr/listapis', {
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.apiList = []
        } else {
          if (parseInt(obj.total) > 0) {
            vm.apiList = obj.data.map(val => {
              val.isAll = false
              return val
            })
            vm.activeNames = obj.apiTypeNames
          } else {
            vm.apiList = []
          }
        }
      })
    },
    getAuth(value) {
      const vm = this
      axios.get(process.env.BASE_API + '/role/getauth', {
        params: {
          roleId: value
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.dataModel = obj.auths

          vm.dialogAuthVisiable = true
        }
      })
    }
  }
}
</script>

<style scoped>
  .orderform {
    padding-top: 20px;
    padding-left: 10px;
    padding-right: 10px;
  }

  .mydiv {
    float: right;
    margin-right: 10px;
  }
</style>
