<template>
  <a-modal :visible="visible" :title="formTitle" @ok="handleOk()" @cancel="handleClose()" width="820px">
    <a-form
      layout="inline"
      labelAlign="right"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 12 }"
      class="card-padding"
      @keydown.enter.native="handleQuery"
    >
      <a-form-item label="手机号" class="search-item-class">
        <a-input class="search-item-wrapper" v-model="queryParam.mobilePhone" placeholder="请输入手机号" allow-clear />
      </a-form-item>
      <a-form-item label="用户姓名" class="search-item-class">
        <a-input class="search-item-wrapper" v-model="queryParam.userName" placeholder="请输入用户姓名" allow-clear />
      </a-form-item>
      <span class="table-page-search-submitButtons">
        <a-button type="primary" @click="handleQuery"><a-icon type="search" />查询</a-button>
        <a-button style="margin-left: 8px" @click="resetQuery"><a-icon type="redo" />重置</a-button>
      </span>
    </a-form>
    <a-table
      :loading="loading"
      rowKey="userId"
      :columns="columns"
      :data-source="list"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :pagination="{
        current: queryParam.pageNum,
        pageSize: queryParam.pageSize,
        total: total,
        showTotal: (total) => `共 ${total} 条`,
        onChange: changeSize,
      }"
    >
    </a-table>
  </a-modal>
</template>

<script>
import { getListUnallocatedRoleUsers } from '@/api/system/role'
import { editUsersRole } from '@/api/system/role'
import md5 from 'md5'

const defaultQueryForm = {
  pageNum: 1,
  pageSize: 10,
  userName: undefined,
  mobilePhone: undefined,
  roleId: undefined,
}
export default {
  name: 'CreateUserForm',
  data() {
    return {
      visible: false,
      formTitle: undefined,
      roleId: undefined,
      queryParam: { ...defaultQueryForm },
      savedRoleUserIds: [],
      selectedRowKeys: [],
      selectedRows: [],
      loading: false,
      total: 0,
      list: [],
      columns: [
        {
          title: '登入账号',
          dataIndex: 'loginName',
          align: 'center',
        },
        {
          title: '手机号',
          dataIndex: 'mobilePhone',
          align: 'center',
        },
        {
          title: '用户姓名',
          dataIndex: 'userName',
          align: 'center',
        },
      ],
    }
  },
  methods: {
    handleQuery() {
      this.queryParam.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParam = { ...defaultQueryForm }
      this.handleQuery()
    },
    getList() {
      this.loading = true
      getListUnallocatedRoleUsers(this.queryParam).then((response) => {
        this.list = response.result.data
        this.total = response.result.totalCount
        const currentRoleUser =
          response.result.data &&
          response.result.data.filter(
            (item) => item.roles && item.roles.findIndex((roleItem) => roleItem.roleId === this.roleId) > -1
          )
        const savedRoleUserIds = currentRoleUser.map((item) => item.userId)
        this.selectedRowKeys = savedRoleUserIds
        this.savedRoleUserIds = savedRoleUserIds
        this.selectedRows = [...currentRoleUser]
        this.loading = false
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    handleAddUser(role) {
      if (!role || !role.roleId) {
        this.$message.error('请双击左侧其中一条角色信息')
        return
      }
      this.getList()
      this.roleId = role.roleId
      this.queryParam.roleId = this. roleId
      this.formTitle = `分配用户-${role.roleName}`
      this.visible = true
    },
    handleClose() {
      this.visible = false
      this.roleId = undefined
      this.total = 0
      this.list = []
      this.selectedRowKeys = []
      this.selectedRows = []
      this.queryParam = { ...defaultQueryForm }
    },
    handleOk() {
      const unSavedRoleUserIds = this.selectedRowKeys.filter((item) => !this.savedRoleUserIds.includes(item))
      if (unSavedRoleUserIds && unSavedRoleUserIds.length > 0) {
        const userIds = unSavedRoleUserIds.join(',')
        editUsersRole(this.roleId, userIds).then(() => {
          this.$message.success('添加成功', 3)
          this.handleClose()
          this.$emit('refresh-list')
        })
      } else {
        this.handleClose()
      }
    },
  },
}
</script>
