<template>
   <!-- 授权用户 -->
   <el-dialog title="选择用户" v-model="visible" width="800px" top="5vh" append-to-body>
      <basic-table
         ref="tableRef"
         :columns="columns"
         :search-columns="searchColumns"
         :query="queryList"
         :extra-params="{ roleId: props.roleId }"
         row-key="userId"
         size="small"
         height="260px"
         :show-toolbar="false"
         :auto-load="false"
         @row-click="clickRow"
         @selection-change="handleSelectionChange"
      />
      <template #footer>
         <div class="dialog-footer">
            <el-button type="primary" @click="handleSelectUser">确 定</el-button>
            <el-button @click="visible = false">取 消</el-button>
         </div>
      </template>
   </el-dialog>
</template>

<script setup name="SelectUser">
import { authUserSelectAll, unallocatedUserList } from "@/api/system/role"

const props = defineProps({
  roleId: {
    type: [Number, String]
  }
})

const { proxy } = getCurrentInstance()

const tableRef = ref()
const visible = ref(false)
const userIds = ref([])

// 搜索项配置
const searchColumns = [
  { label: "用户名称", prop: "userName", component: "input", placeholder: "请输入用户名称", width: "200px" },
  { label: "手机号码", prop: "phonenumber", component: "input", placeholder: "请输入手机号码", width: "200px" }
]

// 表格列配置
const columns = [
  { label: "用户名称", prop: "userName", align: "center" },
  { label: "用户昵称", prop: "nickName", align: "center" },
  { label: "邮箱", prop: "email", align: "center" },
  { label: "手机", prop: "phonenumber", align: "center" },
  { label: "状态", prop: "status", align: "center", dict: "sys_normal_disable" },
  { label: "创建时间", prop: "createTime", align: "center", width: 180, parseTime: true }
]

// 查询函数（BasicTable 调用，返回 { rows, total }）
function queryList(params) {
  return unallocatedUserList(params)
}

// 显示弹框
function show() {
  visible.value = true
  nextTick(() => {
    tableRef.value?.reload()
  })
}

/** 选择行 */
function clickRow(row) {
  tableRef.value?.getTableRef()?.toggleRowSelection(row)
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  userIds.value = selection.map(item => item.userId)
}

const emit = defineEmits(["ok"])
/** 选择授权用户操作 */
function handleSelectUser() {
  const uIds = tableRef.value?.getSelection().map(u => u.userId).join(",") || ""
  if (uIds === "") {
    proxy.$modal.msgError("请选择要分配的用户")
    return
  }
  authUserSelectAll({ roleId: props.roleId, userIds: uIds }).then(res => {
    proxy.$modal.msgSuccess(res.msg)
    visible.value = false
    emit("ok")
  })
}

defineExpose({
  show,
})
</script>
