<template>
  <admin-layout>
    <div class='d-flex justify-between'>
      <div style='width: 49.5%;'>
        <admin-todo-list title='筛选条件' filters icon='filter'>
          <template #options>
            <a-button type="dashed" @click="resetQuery" icon="reload">重置 </a-button>
            <a-button type="primary" @click="searchQuery" icon="search">查询 </a-button>
          </template>
          <HSearchForm label='名称' span='8'>
            <a-input placeholder="请输入名称查询" v-model="queryParams.roleName" />
          </HSearchForm>
        </admin-todo-list>

        <admin-todo-list title='数据列表' icon='table'>
          <template #options>
            <a-button
              v-if="isDisabledAuth('roleUserList:add')"
              @click="handleAdd"
              type="primary"
              icon="plus"
              class="mt6 mr10"
            >角色录入
            </a-button>
            <a-button
              v-if="isDisabledAuth('roleUserList:export')"
              type="primary"
              icon="download"
              @click="handleExportFile"
              class="mt6"
            >导出
            </a-button>
          </template>
          <a-table
            ref="table"
            size="small"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="pagination"
            :loading="tableLoading"
            :rowSelection="{ selectedRowKeys: selectedRowKeys1, onChange: onSelectChange1, type: 'radio' }"
            @change="handlePaginationChange"
          >
            <span slot="action" slot-scope="text, record">
              <a-space>
                <a v-if="isDisabledAuth('roleUserList:user')" class="mr5" @click="handleOpen(record)">用户</a>
                <a-dropdown class="mr5">
                  <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
                  <a-menu slot="overlay">
                    <a-menu-item>
                      <a @click="handlePerssion(record.id)">授权</a>
                    </a-menu-item>
                    <a-menu-item v-if="isDisabledAuth('roleUserList:edit')">
                      <a @click="handleEdit(record)">编辑</a>
                    </a-menu-item>
                    <a-menu-item v-if="isDisabledAuth('roleUserList:del')">
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete1(record.id)">
                        <a style="color: #f5222d">删除</a>
                      </a-popconfirm>
                    </a-menu-item>
                  </a-menu>
                </a-dropdown>
              </a-space>
            </span>
          </a-table>
        </admin-todo-list>

        <!-- 右侧的角色权限配置 -->
        <UserRoleModal ref="modalUserRole"></UserRoleModal>
        <RoleModal ref="modalEditRef" @ok="handleOk"></RoleModal>
      </div>

      <div style='width: 49.5%;'>
        <admin-todo-list title='筛选条件' filters icon='filter'>
          <template #options>
            <a-button type="dashed" @click="searchReset2" icon="reload">重置</a-button>
            <a-button type="primary" @click="searchQuery2" icon="search">查询</a-button>
          </template>
          <HSearchForm label='用户账号' span='8'>
            <a-input placeholder="请输入用户账号" v-model="queryParam2.username" />
          </HSearchForm>
        </admin-todo-list>

        <admin-todo-list title='数据列表' icon='table'>
          <template #options>
            <a-button v-if="isDisabledAuth('roleUserList:addUser')" @click="handleAdd2" type="primary" icon="plus">
              用户录入
            </a-button>
            <!--<a-button @click="handleEdit2" type="primary" icon="edit" style="margin-top: 16px">用户编辑</a-button>-->
            <a-button
              v-if="isDisabledAuth('roleUserList:addExistingUser')"
              @click="handleAddUserRole"
              type="primary"
              icon="plus"
            >添加已有用户
            </a-button>

            <a-dropdown v-if="selectedRowKeys2.length > 0 && isDisabledAuth('roleUserList:batchDelUser')">
              <a-menu slot="overlay">
                <a-menu-item key="1" @click="batchDel2">
                  <a-icon type="delete" />
                  删除
                </a-menu-item>
              </a-menu>
              <a-button class="ml10">
                批量操作
                <a-icon type="down" />
              </a-button>
            </a-dropdown>
          </template>
          <a-table
            style="height: 500px"
            ref="table2"
            bordered
            size="small"
            rowKey="id"
            :columns="columns2"
            :dataSource="dataSource2"
            :pagination="ipagination2"
            :loading="loading2"
            :rowSelection="{ selectedRowKeys: selectedRowKeys2, onChange: onSelectChange2 }"
            @change="handleTableChange2"
          >
              <span slot="action" slot-scope="text, record">
                <a-space>
                  <a v-if="isDisabledAuth('roleUserList:editUser')" class="mr5" @click="handleEdit2(record)">编辑</a>
                  <a-popconfirm v-if="isDisabledAuth('roleUserList:delUser')" title="确定删除吗?" @confirm="() => handleDelete2(record.id)">
                    <a style="color: #f5222d">删除</a>
                  </a-popconfirm>
                </a-space>
              </span>
          </a-table>
        </admin-todo-list>

        <RoleModal ref="modalForm" @ok="handleOk"></RoleModal>
        <UserModal ref="modalForm2" @ok="modalFormOk2"></UserModal>
        <SelectUserModal ref="selectUserModal" @selectFinished="selectOK"></SelectUserModal>
      </div>
    </div>
  </admin-layout>
</template>

<script>
import {PageListMixin} from '@/mixins/PageListMixin'
import {FileMixin} from '@/mixins/FileMixin'
import { deleteAction, downFile, getAction, postAction } from '@/api/manage'
import SelectUserModal from './modules/role/SelectUserModal'
import RoleModal from './modules/role/RoleModal'
import UserModal from './modules/role/UserModal'
import { filterObj } from '@/utils/util'
import UserRoleModal from './modules/role/UserRoleModal'
import moment from 'moment'
import HSearchForm from '@/components/hrhx/form/HSearchForm'

export default {
  name: 'RoleManageList',
  components: {
    HSearchForm,
    UserRoleModal,
    SelectUserModal,
    RoleModal,
    UserModal
  },
  mixins: [PageListMixin, FileMixin],
  data() {
    return {
      model1: {},
      model2: {},
      currentRoleId: '',
      queryParams: {},
      queryParam2: {},
      dataSource1: [],
      dataSource2: [],
      ipagination1: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      ipagination2: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isorter1: {
        column: 'createTime',
        order: 'desc'
      },
      isorter2: {
        column: 'createTime',
        order: 'desc'
      },
      filters1: {},
      filters2: {},
      loading1: false,
      loading2: false,
      selectedRowKeys1: [],
      selectedRowKeys2: [],
      selectionRows1: [],
      selectionRows2: [],
      test: {},
      rightcolval: 0,
      columns:
        [
          {
            title: '角色编码',
            align: 'center',
            ellipsis: true,
            dataIndex: 'roleCode'
          },
          {
            title: '角色名称',
            align: 'center',
            ellipsis: true,
            dataIndex: 'roleName'
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            align: 'center',
            width: '150px',
            sorter: true,
            customRender: (text) => {
              return moment(text).format('YYYY-MM-DD')
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            width: '130px',
            scopedSlots: { customRender: 'action' }
          }
        ],
      columns2: [
        {
          title: '用户账号',
          align: 'center',
          dataIndex: 'username',
          ellipsis: true
        },
        {
          title: '用户名称',
          align: 'center',
          width: 100,
          dataIndex: 'realname'
        },
        {
          title: '状态',
          align: 'center',
          width: 50,
          dataIndex: 'status_dictText'
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          width: 130,
          align: 'center'
        }],


      interface: {
        list: '/sys/role/list',
        delete: '/sys/role/delete',
        list2: '/sys/user/userRoleList',
        addUserRole: '/sys/user/addSysUserRole',
        delete2: '/sys/user/deleteUserRole',
        deleteBatch2: '/sys/user/deleteUserRoleBatch',
        file: 'sys/role/exportXls',
        importExcelUrl: '/sys/role/importExcel',
        excelTemplateUrl: '/sys/role/downLoadTemplated'
      }
    }
  },
  computed: {
    importExcelUrl: function() {
      // return `${window._CONFIG['domianURL']}/${this.interface.importExcelUrl}`
      return process.env.VUE_APP_BASE_API + `${this.interface.importExcelUrl}`
    },
    leftColMd() {
      return this.selectedRowKeys1.length === 0 ? 24 : 12
    },
    rightColMd() {
      return this.selectedRowKeys1.length === 0 ? 0 : 12
    }
  },
  methods: {
    onSelectChange2(selectedRowKeys, selectionRows) {
      this.selectedRowKeys2 = selectedRowKeys
      this.selectionRows2 = selectionRows
    },
    onClearSelected2() {
      this.selectedRowKeys2 = []
      this.selectionRows2 = []
    },
    onClearSelected1() {
      this.selectedRowKeys1 = []
      this.selectionRows1 = []
    },
    onSelectChange1(selectedRowKeys, selectionRows) {
      this.rightcolval = 1
      this.selectedRowKeys1 = selectedRowKeys
      this.selectionRows1 = selectionRows
      this.model1 = Object.assign({}, selectionRows[0])
      this.currentRoleId = selectedRowKeys[0]
      this.loadData2()
    },
    onClearSelected() {
    },

    getQueryParams2() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams2) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams2)
      }
      var param = Object.assign(sqp, this.queryParam2, this.isorter2, this.filters2)
      param.field = this.getQueryField2()
      param.pageNo = this.ipagination2.current
      param.pageSize = this.ipagination2.pageSize
      return filterObj(param)
    },
    getQueryField2() {
      //TODO 字段权限控制
      var str = 'id,'
      this.columns2.forEach(function(value) {
        str += ',' + value.dataIndex
      })
      return str
    },
    handleEdit2: function(record) {
      this.$refs.modalForm2.title = '编辑'
      this.$refs.modalForm2.roleDisabled = true
      this.$refs.modalForm2.handleEdit(record)
    },
    handleAdd2: function() {
      if (this.currentRoleId === '') {
        this.$message.error('请选择一个角色!')
      } else {
        this.$refs.modalForm2.roleDisabled = true
        this.$refs.modalForm2.selectedRole = [this.currentRoleId]

        this.$refs.modalForm2.handleAdd()

        this.$refs.modalForm2.title = '新增'
      }
    },
    modalFormOk2() {
      // 新增/修改 成功时，重载列表
      this.loadData2()
    },
    loadData2(arg) {
      if (!this.interface.list2) {
        this.$message.error('请设置url.list2属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination2.current = 1
      }
      if (this.currentRoleId === '') return
      let params = this.getQueryParams2()//查询条件
      params.roleId = this.currentRoleId
      this.loading2 = true
      getAction(this.interface.list2, params).then((res) => {
        if (res.code === '200') {
          this.dataSource2 = res.value.records
          this.ipagination2.total = res.value.total

        }
        this.loading2 = false
      })

    },
    handleDelete1: function(id) {
      this.handleDelete(id)
      this.dataSource2 = []
      this.currentRoleId = ''
    },
    handleDelete2: function(id) {
      if (!this.interface.delete2) {
        this.$message.error('请设置url.delete2属性!')
        return
      }
      var that = this
      deleteAction(that.url.delete2, { roleId: this.currentRoleId, userId: id }).then((res) => {
        if (res.code === '200') {
          that.$message.success(res.message)
          that.loadData2()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    batchDel2: function() {

      if (!this.interface.deleteBatch2) {
        this.$message.error('请设置url.deleteBatch2属性!')
        return
      }
      if (this.selectedRowKeys2.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys2.length; a++) {
          ids += this.selectedRowKeys2[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: function() {
            deleteAction(that.url.deleteBatch2, {
              roleId: that.currentRoleId,
              userIds: ids
            }).then((res) => {
              if (res.code === '200') {
                that.$message.success(res.message)
                that.loadData2()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },
    selectOK(data) {
      let params = {}
      params.roleId = this.currentRoleId
      params.userIdList = []
      for (var a = 0; a < data.length; a++) {
        params.userIdList.push(data[a])
      }
      postAction(this.interface.addUserRole, params).then((res) => {
        if (res.code === '200') {
          this.loadData2()
          this.$message.success(res.message)
        } else {
          this.$message.warning(res.message)
        }
      })
    },

    handleAddUserRole() {
      if (this.currentRoleId === '') {
        this.$message.error('请选择一个角色!')
      } else {
        this.$refs.selectUserModal.visible = true
      }
    },
    handleOpen(record) {
      this.rightcolval = 1
      this.selectedRowKeys1 = [record.id]
      this.model1 = Object.assign({}, record)
      this.currentRoleId = record.id
      this.onClearSelected2()
      this.loadData2()
    },
    /*handleEdit: function(record) {
      if (this.currentRoleId === '') {
      this.$message.error('请选择一个角色!')
      } else {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑'
      }
    },*/
    searchQuery2() {
      this.loadData2(1)
    },
    searchReset2() {
      this.queryParam2 = {}
      this.loadData2(1)
    },
    handleTableChange2(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter2.column = sorter.field
        this.isorter2.order = 'ascend' === sorter.order ? 'asc' : 'desc'
      }
      this.ipagination2 = pagination
      this.loadData2()
    },
    hideUserList() {
      //this.rightcolval = 0
      this.selectedRowKeys1 = []
    },
    handlePerssion(roleId) {
      this.$refs.modalUserRole.show(roleId)
    },
    //Excel模板下载
    downloadTheTemplate(fileName) {//ExcelConfigurationTemplate
      let param = {}
      downFile(this.interface.excelTemplateUrl, param).then((data) => {
        console.info('----' + data)
        console.info('----' + data.data)
        if (!data) {
          this.$message.warning('模板文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    }
  }
}
</script>
<style scoped>
.ant-drawer-left.ant-drawer-open, .ant-drawer-right.ant-drawer-open {
  width: 100%;
  height: 100% !important;
  -webkit-transition: -webkit-transform 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
  transition: -webkit-transform 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
  transition: transform 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
  transition: transform 0.3s cubic-bezier(0.7, 0.3, 0.1, 1), -webkit-transform 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
}

.query_name {
  display: block;
  float: left;
  width: 230px;
}

.query_btn {
  width: 50%;
}
</style>
}
</script>
