<template>
  <!-- 搜索工作栏 -->
  <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="0">
    <el-form-item>
      <el-select
        v-model="queryParams.messageType"
        placeholder="消息类型"
        clearable
        filterable
        @change="handleQuery"
      >
        <el-option
          v-for="item in typeOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-select
        v-model="queryParams.readStatus"
        placeholder="状态"
        clearable
        filterable
        @change="handleQuery"
      >
        <el-option label="已读" :value="true" />
        <el-option label="未读" :value="false" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button :disabled="selectedIds.length == 0" @click="handleUpdateList">
        标记已读
      </el-button>
      <el-button @click="handleUpdateAll"> 全部已读 </el-button>
    </el-form-item>
  </el-form>

  <el-text class="mb-10px" type="danger">tips: 双击展示消息详情</el-text>

  <!-- 列表 -->
  <el-table
    ref="tableRef"
    v-loading="loading"
    :data="list"
    row-key="id"
    @selection-change="handleSelectionChange"
    @row-dblclick="handleDetail"
  >
    <el-table-column type="selection" :selectable="selectable" reserve-selection width="60px" />
    <el-table-column label="类型" align="left" prop="messageType" width="200px" />
    <el-table-column label="标题" align="left" prop="title" />
    <el-table-column
      label="时间"
      align="left"
      prop="createTime"
      width="180"
      :formatter="dateFormatter"
    />
    <el-table-column label="状态" align="left" width="100px">
      <template #default="{ row }">
        <el-tag :type="row.readStatus ? 'success' : 'info'">
          {{ row.readStatus ? '已读' : '未读' }}
        </el-tag>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <Pagination
    :total="total"
    v-model:page="queryParams.pageNo"
    v-model:limit="queryParams.pageSize"
    @pagination="getList"
  />
</template>
<script lang="ts" setup name="NotifyMessage">
import { dateFormatter } from '@/utils/formatTime'
import * as NotifyMessageApi from '@/api/system/notify/message'
import { useUserStore } from '@/store/modules/user'
import { getGeneralSysDictData } from '@/api/system/dict/dict.data'

const router = useRouter()

const userStore = useUserStore()
const message = useMessage() // 消息

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<any[]>([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 20,
  messageType: undefined,
  readStatus: undefined
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await NotifyMessageApi.getNotifyMessagePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 某一行，是否允许选中 */
const selectable = (row: any) => {
  return !row.readStatus
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

function handleDetail(row: any) {
  if (!row.readStatus) {
    handleReadOne(row.id)
  }

  const url = router.resolve({
    path: '/nm-detail',
    query: { id: row.id }
  })
  window.open(url.href, '_blank')
}

const tableRef = ref() // 表格的 Ref
const selectedIds = ref<number[]>([]) // 表格的选中 ID 数组

/** 标记全部站内信已读 **/
const handleUpdateAll = async () => {
  await NotifyMessageApi.updateAllNotifyMessageRead({
    roleId: userStore.getUser?.currentRole
  })
  message.success('全部已读成功！')
  tableRef.value.clearSelection()
  await getList()
}

/** 标记一些站内信已读 **/
const handleUpdateList = async () => {
  if (selectedIds.value.length === 0) {
    return
  }
  await NotifyMessageApi.updateNotifyMessageRead({
    ids: selectedIds.value,
    roleId: userStore.getUser?.currentRole
  })
  message.success('批量已读成功！')
  tableRef.value.clearSelection()
  await getList()
}

/** 标记一条站内信已读 */
const handleReadOne = async (id: number) => {
  await NotifyMessageApi.updateNotifyMessageRead({
    ids: [id],
    roleId: userStore.getUser?.currentRole
  })
  await getList()
}

/** 当表格选择项发生变化时会触发该事件  */
const handleSelectionChange = (array: NotifyMessageApi.NotifyMessageVO[]) => {
  selectedIds.value = []
  if (!array) {
    return
  }
  array.forEach((row) => selectedIds.value.push(row.id))
}

const typeOptions = ref<any[]>([])

function getOptions() {
  getGeneralSysDictData('message_type').then((data) => {
    typeOptions.value = data
  })
}

/** 初始化 **/
onMounted(() => {
  getOptions()
  getList()
})
</script>
