<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <div class="container_item">
        <span class="item_text">用户名：</span>
        <el-input v-model="query.account" placeholder="" class="filter-item input_item"   />
      </div> -->
      <div class="container_item">
        <span class="item_text">角色名称：</span>
        <el-input v-model="query.name" placeholder="" class="filter-item input_item"    />
      </div>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-my-search" @click="handleSearch">
        {{ $t('table.search') }}
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-my-reset" @click="query={};handleSearch()">
        {{ $t('table.reset') }}
      </el-button>
      <el-button v-if="permission.includes('role_add')" v-waves class="filter-item" type="primary" icon="el-icon-my-add" @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
    </div>
    <div class="wrapper_table">
      <el-table
        :data="tableData"
        fit
        stripe
        highlight-current-row
        style="width: 100%;"
        :header-cell-class-name="headerStyle"
        :max-height="tableHeight"
      >
        <el-table-column prop="name" :label="$t('role.name')"  align="left"></el-table-column>
        <el-table-column prop="roleCode" :label="$t('role.code')" align="left"></el-table-column>
        <el-table-column prop="description" :label="$t('role.description')" align="left" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" :label="$t('role.createTime')" align="left"></el-table-column>
        <el-table-column :label="$t('table.actions')" align="left"   class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <div class="flex_d">
              <el-button v-if="permission.includes('role_manage')" size="mini" type="text" icon="el-icon-my-permissions" @click="handleUpdate(row)">
                {{ $t('table.authority') }}
              </el-button>
              <el-button v-if="permission.includes('role_del')" type="text" size="mini" icon="el-icon-my-del-y" @click="handleDelete(row)">
                {{ $t('table.delete') }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="getData" />
    <el-dialog
      :title="handleType==1?'新增角色':'权限管理'"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="560px">
      <div class="userinfo">
        <p>角色信息</p>
        <el-form ref="dataForm"   :model="temp" label-position="right" label-width="100px" >
           <el-form-item class="require" :label="$t('role.name')+'：'">
            <el-input v-model="temp.name" class="filter-item " style="width:294px"  />
          </el-form-item>
          <el-form-item class="require"  :label="$t('role.code')+'：'">
            <el-input v-model="temp.roleCode" class="filter-item " style="width:294px"  />
          </el-form-item>
          <el-form-item :label="$t('role.description')+'：'">
            <el-input v-model="temp.description" class="filter-item " style="width:294px"  />
          </el-form-item>
        </el-form>
      </div>
       <div class="userinfo">
        <p>权限管理</p>
          <el-tree
          :data="treeData"
          show-checkbox
          :check-strictly="false"
          node-key="id"
          :props="defaultProps"
          :default-checked-keys="rList"
          @check="handleCheck"
          ref="rightsTree"
          >
        </el-tree>
       </div>
      <div slot="footer" class="dialog-footer" style="padding-right:26px">
        <el-button v-waves class="filter-item flex_align" type="primary" icon="el-icon-my-tijiao" @click="sbumitData">
            {{ $t('table.sbumit') }}
        </el-button>
        <el-button v-waves class="filter-item flex_align" type="primary" icon="el-icon-my-quxiao" @click="dialogFormVisible=false">
            {{ $t('table.cancel') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog'
import { mapGetters } from 'vuex'
import http from '@/api/http'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: '',
  components: { Pagination },
  computed: {
    ...mapGetters([
      'permission',
    ])
  },
  directives: { waves, elDragDialog },
  data() {
    return {
      total: 0,
      query:{},
      listRole:[],
      tableData:[],
      pageSize:20,
      pageNum:1,
      orgList:[],
      roles: [],
      form:{},
      temp: {},
      dialogFormVisible: false,
      handleType:'1',
      tableHeight: 0,
      pwdChangeData:{},
      treeData:[],
      defaultProps:{
        children: 'childs',
        label: 'name'
      },
      rList:[]
    }
  },
  created() {
    this.getData()
    this.getTree()
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 240
    })
  },
  methods: {
    getData() {
      http.post(`/sys/userRole/queryLists`,{cpage:this.pageNum,pageSize:this.pageSize,...this.query}).then((res)=>{
          this.tableData = res.data.list;
          this.total = res.data.total || 0;
      }).catch(err=>{});
    },
    getTree(){
      http.post(`/sys/menu/queryTree`,{cpage:1,pageSize:99}).then((res)=>{
          this.treeData = res.data;
      }).catch(err=>{});
    },
    getOrg(){
      http.post(`/sys/org/queryLists`,{cpage:1,pageSize:99}).then((res)=>{
          this.orgList = res.data.list;
      }).catch(err=>{});
    },
    handleSearch(){
      this.pageNum = 1
      this.getData()
    },
    sbumitPwd(){
      if(this.form.password != this.form.confirmPassword){
        this.$message.error('新密码和确认密码不一致')
        return false
      }
      this.form.id = this.pwdChangeData.id
      http.post(`/sys/userinfo/modifyPasswd`,this.form).then((res)=>{
        this.$message.success('修改成功！');
        this.chpwdVisible = false
      }).catch(err=>{});
    },

    handleChangePwd(row){
      this.form = {}
      this.pwdChangeData = row
      this.chpwdVisible = true
    },

    handleCreate() {
      this.temp = {}
      this.$nextTick(() => {
        this.$refs.rightsTree.setCheckedKeys([]);
      });
      this.handleType = 1
      this.dialogFormVisible = true
    },
    sbumitData() {
      if(!this.temp.name){
          this.$message.error('请输入角色名称')
          return false
      }
      if(!this.temp.roleCode){
          this.$message.error('请输入角色代码')
          return false
      }
      this.temp.ids = [...this.roles]
      this.temp.status = 1
      if (this.roles.length === 0) {
        this.$message.error('请勾选角色权限')
        return false
      }
      if(this.handleType==1){
        http.post(`/sys/userRole/create`,this.temp).then((res)=>{
            this.$message.success('提交成功！');
            this.getData();
            this.dialogFormVisible = false;
        }).catch(err=>{});
      }else{
        http.post(`/sys/userRole/update`,this.temp).then((res)=>{
            this.$message.success('提交成功！');
            this.getData();
            this.dialogFormVisible = false;
        }).catch(err=>{});
      }
    },
    handleUpdate(row) {
      this.getByRoleId(row.id)
      this.temp = Object.assign({}, row) // copy obj
      this.handleType = 2
      this.dialogFormVisible = true

    },
    getByRoleId(id){
      http.post(`/sys/menu/queryMenuByRoleId`,{id}).then((res)=>{
          let list = []
          for(let item of res.data){
              list.push(item.menuId)
          }
          this.rList = []
          this.roles = []
          this.rList = [...list]
          this.roles = [...list]
          this.$nextTick(() => {
            this.$refs.rightsTree.setCheckedKeys(this.rList);
          });
      }).catch(err=>{});
    },
    handleDelete(row, index) {
      // 二次确认删除
        this.$confirm('确定要删除吗？', '提示', {
            type: 'warning'
        }).then(() => {
          http.post(`/sys/userRole/delete`,{id:row.id}).then((res)=>{
              this.$message.success('删除成功！');
              this.getData();
          }).catch(err=>{});
        }).catch(() => {});
    },

    headerStyle() {
      return 'tableStyle'
    },
    authorization(){

    },
    handleCheck(p1, { checkedKeys, halfCheckedKeys }) {
      this.roles = [...checkedKeys, ...halfCheckedKeys]
      console.log('checkedKeys', checkedKeys);
      console.log('halfCheckedKeys', halfCheckedKeys);
      // console.log(this.roles);
    },
  }
}
</script>
<style scoped lang="scss">
  .el-table__header-wrapper{
    border-radius: 10px 10px 0 0;
  }
  .userinfo{
    margin: 20px 50px;
    width: 464px;
    // height: 313px;
    background: rgba(212,235,254,.1);
    border: 1px solid rgba(61,85,150,.1);
    p{
      margin-left: 20px;
      font-size: 14px;
      font-family: "SourceHanSansCN";
      font-weight: 500;
      color: #212121;
      border-left: 3px solid #3D5596;
      padding-left: 8px;
    }
    .input_item{
      width: 319px !important;
    }
    .tab{
      margin: 0 30px 20px;
    }
  }
  .userinfo ::v-deep .el-form-item__label{
    color: #212121 !important;
  }
</style>
