<template>
  <div class="content-main-manage">
     <!-- <i class="iconfont icon-quanxian" style="cursor:not-allowed;color:#fb9c2c;fontSize:18px;marginRight:6px" v-if="row.roleId == 1"></i> -->
    <div class="content-main">
     <div class="content-body-wrap">
       <div class="content-body">
          <div class="search-list">
            <div class="search-left">
              <Form class="common-form common-form-list" ref="tableParams" :model="tableParams" inline>
                <FormItem label="" prop="isEnable">
                <Select v-model="tableParams.isEnable" placeholder="启用状态">
                  <Option v-for="item in isEnableData" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
              </FormItem>
                <FormItem label="" prop="keywords">
                  <Input placeholder="输入关键字查询" clearable search v-model="tableParams.keywords" />
                </FormItem>
                <FormItem label="" >
                  <Button type="primary" class="common-btn-search" @click="searchClick">
                    <Icon type="ios-search" style="margin-right:4px;font-size: 16px"/> 筛选
                  </Button> 
                  <Button type="primary" class="common-btn-search" style="margin-left:10px" @click="resetClick('tableParams')">
                    <Icon type="ios-search" style="margin-right:4px;font-size: 16px"/> 重置
                  </Button>   
                </FormItem>
              </Form>
            </div>
            <div class="btn-container">
              <Button icon="ios-add" class="common-add-btn" @click="addClick">新增角色</Button>
            </div>
            </div>
            <div class="manage-main-center">
              <Table :columns="columns" :data="tableData" class="common-table app-table" no-data-text="" :row-class-name="rowClassName" :loading="loading">
                <template slot="loading">
                    <Loading-animation></Loading-animation>
                </template>
                <template slot-scope="{ row }" slot="action">
                  <Tooltip content="配置权限" placement="top">
                      <i class="iconfont icon-quanxian" style="cursor:pointer;color:#fb9c2c;fontSize:18px;marginRight:6px" @click="permissionConfig(row)"></i>
                  </Tooltip>
                  <Tooltip content="编辑" placement="top">
                      <i class="iconfont icon-bianji" style="cursor:pointer;color:#64ACFE;fontSize:20px;marginRight:6px" @click="editClick(row)"></i>
                  </Tooltip>
                  <Tooltip content="删除" placement="top">
                      <i class="iconfont icon-shanchu" style="cursor:pointer;color:#E92E2E;fontSize:20px;marginRight:6px" @click="delClick(row)"></i>
                  </Tooltip>
                </template>
              </Table>
            </div>
            <div class="common-page">
              <div class="common-page-total">
                共<span>{{tablePage}}</span>页 / <span>{{tableTotal}}</span>条数据
              </div>
              <Page :total="tableTotal" :current="tableParams.pageNum" :page-size="tableParams.pageSize" @on-change="changePage" @on-page-size-change="sizeChange" show-elevator />
            </div>
       </div>      
     </div>
    </div>
    <Modal
          v-model="showModal"
          :title="title"
          width="34"
          ref="modalGrag"
          draggable
          reset-drag-position
          @on-visible-change="modalChange"
          :mask-closable="false"
          class-name="common-modal">
          <Form class="common-form" ref="formOption" :model="formOption" :rules="ruleValidate" :label-width="130">
            <FormItem label="角色ID：" prop="roleId" v-show="title == '编辑角色'">
              <span>{{formOption.roleId}}</span>
            </FormItem>
            <FormItem label="角色名称：" prop="roleName">
              <Input v-model.trim="formOption.roleName" maxlength="20" show-word-limit />
            </FormItem>
            <FormItem label="角色描述：" prop="roleDescribe">
              <Input v-model="formOption.roleDescribe" type="textarea" :rows="3" maxlength="100" show-word-limit />
            </FormItem>
            <FormItem label="启用状态：" prop="isEnable" v-if="title == '新增角色'">
              <i-switch true-color="#57C44F" v-model="formOption.isEnable" disabled></i-switch>
              <span style="color: #718EBD;margin-left:6px">关</span>
              <span style="color: #718EBD;margin-left:12px">（所有新增状态均为关闭，需在列表打开）</span>
            </FormItem>
          </Form>
          <div slot="footer">
              <Button @click="modalCancel">取消</Button>
              <Button type="primary" @click="modalOk('formOption')">确定</Button>
            </div>
    </Modal>
    <Modal
      v-model="modalStatus"
      :title="commonTitle"
      width="30"
      ref="modalGrag"
      draggable
      reset-drag-position
      :mask-closable="false"
      class-name="common-modal">
        <i :class="'iconfont '+ activeClass" :style="{ color: activeColor}" class="modal-icon" v-show="commonTitle!='确认删除'"></i>
      <Icon type="ios-information-circle" :style="{ color: activeColor}" class="modal-icon" v-show="commonTitle=='确认删除'"></Icon>
      <span class="modal-text">{{modalTitle}}</span>
      <div slot="footer">
          <Button @click="commonCancel">取消</Button>
          <Button type="primary" @click="commonOk">确定</Button>
       </div>
    </Modal>
    <Modal
      v-model="permissStatus"
      title="权限配置"
      width="20"
      ref="modalGrag"
      draggable
      reset-drag-position
      :mask-closable="false"
      class-name="common-modal common-modal-detail">
      <div class="tree-menu-list common-scroll" v-if="permissionMenu && permissionMenu.length>0">
        <Checkbox label="首页" v-model="homeChecked" :disabled="homeDisabled" class="home-menu-checkbox">
          <span>首页（必选）</span>
        </Checkbox>
        <Tree :data="permissionMenu" show-checkbox class="tree-menu" :check-directly="true" ref="treeMenu"></Tree>
      </div>
      <div slot="footer">
          <Button @click="commonPermissCancel">取消</Button>
          <Button type="primary" @click="commonPermissOk">确定</Button>
       </div>
    </Modal>
  </div>
</template>
<script>
const defaultFrom = {roleName: '',roleDescribe: '',isEnable: 0}
export default {
  name: "RolePermissions",
  components:{
  },
  data() {
    return {
      loading: true,
      tableParams: {
        keywords: '',
        isEnable: '',
        pageNum: 1,
        pageSize: 10
      },
      tableData: [],
      tableTotal: 0,
      tablePage: 0,
      columns: [
          {
            title: '序号',
            key: 'roleCode',
            align: 'center',
          },
          {
            title: '角色ID',
            key: 'roleId',
            align: 'center',
          },
          {
            title: '角色名称',
            key: 'roleName',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '角色描述',
            key: 'roleDescribe',
            align: 'center',
            ellipsis: true,
            tooltip: true
          },
          {
            title: '现有用户数量',
            key: 'userNum',
            align: 'center'
          },
          {
          title: '启用状态',
          key: 'isEnable',
          align: 'center',
          render: (h, params) => {
            return h('div', [                             
              h('i-switch', {
                props: { value: params.row.isEnable,'true-color': '#57C44F', trueValue:1,falseValue: 0
                },
                nativeOn:{
                    "mousedown":(event)=>{ // 监听组件原生事件mousedown,此事件在click之前触发
                      this.rowObj =  params.row
                      if (params.row.isEnable == 1) {
                        this.commonTitle = '确认关闭'
                        this.activeColor = '#E92E2E'
                        this.activeClass = 'icon-guanbi'
                        this.modalTitle = '关闭后，角色下所有用户状态将全部关闭。请谨慎操作。'
                        this.modalStatus = true
                      } else {
                         this.commonTitle = '确认启用'
                        this.activeColor = '#57C44F'
                        this.activeClass = 'icon-qiyong'
                        this.modalTitle = '启用角色后，之前请至人员列表中手动开启相关用户。'
                        this.modalStatus = true
                        
                      }
                    },
                  }
                }),
              ])
            }
          },
          {
            title: '操作',
            align: 'center',
            slot: 'action',
            width: 120,
          }
      ],   
      isEnableData: [
         {
          value: '-1',
          label: '启用状态'
        },
        {
          value: '1',
          label: '启用'
        },
        {
          value: '0',
          label: '关闭'
        },
      ], 
      showModal: false,
      permissStatus: false, 
      modalStatus: false,
      title: '新增角色',
      commonTitle: "确认删除",
      activeColor: '#E92E2E',
      activeClass: '',
      modalTitle: '',
      formOption: {roleName: '',roleDescribe: '',isEnable: 0},
      ruleValidate: {
        roleName: [{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        }],
      },
      permissionMenu: [],
      homeChecked: true,
      homeDisabled: true
    };
  },
  mounted() {
    this.getTableData()
  },
  methods: {
    changePicker (date) {
      this.tableParams.beginDate = date[0]
      this.tableParams.endDate = date[1]
    },
    rowClassName(row, index) {
      if (index % 2 == 0) {
        return "ivu-table-stripe-even";
      } else {
        return "ivu-table-stripe-odd";
      }
    },
    // 分页
    changePage (val) {
      this.tableParams.pageNum = val
      this.getTableData()
    },
    //跳转
    sizeChange (val) {
      this.tableParams.pageSize = val
      this.getTableData()
    },
    // 获取表格数据
    getTableData () {
      let params = JSON.parse(JSON.stringify(this.tableParams))
      params.isEnable= params.isEnable == '-1'?'':params.isEnable
      this.loading = true
      this.$get('metroapi/role/list', params).then(res=>{
        this.loading = false
          if (res.httpCode == 1 ){
            this.tableData = res.data.data
            this.tableTotal = res.data.count
            if (res.data.data.length==0) {
              this.tablePage = 0
            } else {
              this.tablePage = res.data.count<= 10 ? 1: Math.ceil(res.data.count/this.tableParams.pageSize)
            }
            if (res.data.data.length==0 && this.tableParams.pageNum>1) {
              this.tableParams.pageNum--
              return this.getTableData()
            }
          } else {
            this.tableData = []
            this.tableTotal = 0
          }
        })
    },
    searchClick () {
      this.tableParams.pageNum = 1
      this.getTableData()
    },
    resetClick (name) {
     this.$refs[name].resetFields()
     this.tableParams.pageNum = 1
     this.getTableData()
    },   
    addClick () {
      this.formOption = JSON.parse(JSON.stringify(defaultFrom))
      this.title = '新增角色'
      this.showModal = true
    },
    permissionConfig (row) {
      this.rowObj = row
      this.getMenus()
    },
    getMenus () {
      this.$get('metroapi/role/queryMenus', {roleId:this.rowObj.roleId}).then(res=>{
        if (res.httpCode == 1 ){
          this.permissStatus = true
          this.permissionMenu = res.data.menuList
        } else {
          this.$Message.info(res.msg)
        }
      })
    },
    editClick (row) {
      this.rowObj = row
      this.formOption = JSON.parse(JSON.stringify(row));
      this.title = '编辑角色'
      this.showModal = true
    },
    delClick (row) {
      this.rowObj = row
      this.commonTitle = '确认删除'
      this.activeColor = '#E92E2E'
      this.activeClass = ''
      this.modalTitle = '删除不影响用户已经产生的操作记录。'
      this.modalStatus = true
    },
    modalChange (modalStatus) {
     if (!modalStatus) {
      this.$refs.formOption.resetFields();
     }
    },
    modalOk (formName) {
      let params = JSON.parse(JSON.stringify(this.formOption)) //把对象中的数据给了某个变量，改变一个对象的值，另一个对象也变化的解决方法
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$post('metroapi/role/save', params).then(res=>{
            if (res.httpCode == 1 ){
              this.showModal = false
              this.$Message.info(res.msg)
              this.getTableData()
            } else {
              this.$Message.info(res.msg)
            }
          })
        } else {
          this.showModal = true
        }
      })
    },
    modalCancel () {
      this.showModal = false
    },
    commonOk () {
      if (this.commonTitle == '确认启用') {
        let params = JSON.parse(JSON.stringify(this.rowObj))
        params.isEnable = 1
        this.getSwitchStatus(params)
      } else if (this.commonTitle == '确认关闭') {
        let params = JSON.parse(JSON.stringify(this.rowObj))
        params.isEnable = 0
        this.getSwitchStatus(params)
      } else {
        let params = {
          roleId: this.rowObj.roleId
        }
        this.delData(params)
      }
    },
    commonCancel () {
      this.modalStatus = false
    },
    // 启用 关闭/接口
    getSwitchStatus (params) {
      this.$post('metroapi/role/save',params).then(res=>{
        if (res.httpCode == 1 ){
          if (params.isEnable == 0) {
            this.rowObj.isEnable = 0
          } else {
            this.rowObj.isEnable = 1
          }
          this.modalStatus = false
        } else {
          this.rowObj.isEnable = 0
          this.$Message.info(res.msg)
        }
      })
    },
    // 删除 关闭/接口
    delData (params) {
      // axios中this为undefined解决，this指向 使用箭头函数解决或let that = this，以前常用的存储this的方法
      this.$deletefn('metroapi/role/delete',params).then(res=>{
        if (res.httpCode == 1 ){
          this.modalStatus = false
          this.$Message.info(res.msg)
          this.getTableData()
        } else {
          this.$Message.info(res.msg)
        }
      })
    },
    commonPermissOk () { 
     let node = this.$refs.treeMenu.getCheckedAndIndeterminateNodes()
     let idArr = node.map(item => item.id);
     this.$put('metroapi/role/menus', {roleId: this.rowObj.roleId,menuIds: idArr}).then(res=>{
        if (res.httpCode == 1 ){
          this.permissStatus = false
          this.$Message.info(res.msg)
        } else {
          this.$Message.info(res.msg)
        }
      })
    },
    commonPermissCancel () {
      this.permissStatus = false
    }
  }
};
</script>
<style scoped lang="stylus">
.content-main-manage {
  overflow: hidden;
  height: calc(100% - 50px);
  width: 100%;
}
.content-main {
  width: 100%;
  height: 100%;
}
.content-body-wrap {
  width: 100%;
  height: 100%;
  background: #06214d;
  padding: 10px;
}
.content-body {
  height: 100%;
  position: relative;
}
.search-list {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
}
.search-left {
  display: flex;
  align-items: center;
   .ivu-select {
     width: 150px;
     height: 32px;
   }
   .ivu-select-single .ivu-select-selection {
     height: 100%;
   }
    >>> .ivu-input {
     width: 160px;
     height: 32px;
   }
    >>> .ivu-input-prefix, >>> .ivu-input-suffix {
     height: 32px;
     line-height: 32px;
   }
}
.manage-main-center {
  width: 100%;
  height: calc(100% - 150px);
}
.common-table {
  max-height: 100%;
}
>>> .common-table .ivu-table th {
  height: 54px;
 }
 >>> .common-table .ivu-table td {
  height: 55px;
 }
  >>> .common-table .ivu-spin-fix {
   top: 54px;
 }
  >>> .app-table .ivu-spin-fix {
   height: calc(100vh - 355px);
 }
 >>> .common-table .ivu-table-tip {
  background: url('../../../assets/images/noData.png') no-repeat center;
}
>>> .common-table .ivu-table-tip table {
 display: none;
}
>>> .app-table .ivu-table-tip {
   height: calc(100vh - 355px);
 }
 >>> .modal-table {
   overflow: auto !important;
 }
 >>> .modal-table .ivu-spin-fix {
   height: 200px;
 }
  >>> .modal-table .ivu-table-tip {
   height: 200px;
 }
.common-page {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  position: absolute;
  bottom: 0;
  right: 0;
}
.common-page-total {
  color: #fff;
  padding-right: 10px;
  font-size: 14px;
  span {
    color #409EFF;
  }
}
>>> .modal-tabs-item {
  margin-top: 10px;
}
// >>> .common-modal .ivu-modal-body {
//   min-height: 243px;
// }
.tree-menu-list {
  padding-left: 20%;
  max-height: 620px;
  overflow: hidden;
  overflow-y: auto;
  margin-bottom: 20px;
}
>>> .home-menu-checkbox{
  padding-left: 20PX;
}
>>> .home-menu-checkbox .ivu-checkbox-disabled+span{
  color: #fff;
 font-size: 14PX;
}
>>> .tree-menu .ivu-tree-title {
 color: #fff;
 font-size: 14PX;
}
>>> .tree-menu .ivu-tree-title:hover {
    background-color: transparent;
}
</style>