<template>
  <el-dialog v-model="visible" :title="`「${noticeTitle}」已读用户`" width="760px" top="6vh" append-to-body @close="handleClose">
    <basic-table
      ref="tableRef"
      :columns="columns"
      :search-columns="searchColumns"
      :query="queryList"
      :extra-params="extraParams"
      row-key="userId"
      size="small"
      height="340px"
      stripe
      :show-toolbar="false"
      :selection="false"
      :show-index="true"
      :auto-load="false"
    >
      <template #search-extra>
        <span class="read-stat">共 <strong>{{ readTotal }}</strong> 人已读</span>
      </template>
    </basic-table>
  </el-dialog>
</template>

<script setup name="ReadUsers">
import { Search } from "@element-plus/icons-vue"
import { listNoticeReadUsers } from "@/api/system/notice"

const { proxy } = getCurrentInstance()

const tableRef = ref()
const visible = ref(false)
const noticeTitle = ref("")
const readTotal = ref(0)

// 固定参数：公告 ID（每次请求合并，不参与搜索重置）
const extraParams = reactive({ noticeId: undefined })

// 搜索项配置
const searchColumns = [
  {
    label: "",
    prop: "searchValue",
    component: "input",
    placeholder: "登录名称 / 用户名称",
    width: "220px",
    formItemProps: { labelWidth: "0px" },
    props: {
      prefixIcon: Search,
      clearable: true,
      onKeyup: (e) => { if (e.key === "Enter") tableRef.value?.handleQuery() },
      onClear: () => tableRef.value?.handleQuery()
    }
  }
]

// 表格列配置
const columns = [
  { label: "登录名称", prop: "userName", align: "center" },
  { label: "用户名称", prop: "nickName", align: "center" },
  { label: "所属部门", prop: "deptName", align: "center" },
  { label: "手机号码", prop: "phonenumber", align: "center", width: 120 },
  { label: "阅读时间", prop: "readTime", align: "center", width: 160, parseTime: true }
]

// 查询函数（BasicTable 调用，返回 { rows, total }）；同时记录已读总数用于统计
function queryList(params) {
  return listNoticeReadUsers(params).then(res => {
    readTotal.value = res.total
    return res
  })
}

/** 打开弹框 */
function open(row) {
  extraParams.noticeId = row.noticeId
  noticeTitle.value = row.noticeTitle
  visible.value = true
  nextTick(() => {
    tableRef.value?.setQueryParams({ searchValue: undefined })
    tableRef.value?.reload()
  })
}

/** 关闭弹框 */
function handleClose() {
  tableRef.value?.clearSelection()
  tableRef.value?.setQueryParams({ searchValue: undefined })
}

defineExpose({
  open
})
</script>

<style scoped>
.read-stat {
  font-size: 13px;
  color: #606266;
  line-height: 28px;
}
.read-stat strong {
  color: #409eff;
  font-size: 15px;
  margin: 0 2px;
}
/* 将搜索栏操作区（搜索/重置 + 已读统计）浮动到右侧 */
:deep(.basic-form > .el-form-item:last-of-type) {
  float: right;
}
</style>
