<template>
  <div class="app-container">
    <!-- 页面说明 -->
    <el-alert
      title="系统通知管理"
      type="info"
      :closable="false"
      style="margin-bottom: 16px"
    >
      <div style="line-height: 1.8; font-size: 13px;">
        此页面用于<strong>管理员发布系统通知</strong>。<br/>
        • 支持发送给全部用户、指定用户或指定角色<br/>
        • 发布后用户将实时收到WebSocket推送通知
      </div>
    </el-alert>

    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="通知标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入通知标题"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="通知类型" prop="notificationType">
        <el-select v-model="queryParams.notificationType" placeholder="请选择通知类型" clearable style="width: 120px">
          <el-option label="系统通知" value="system" />
          <el-option label="维护通知" value="maintenance" />
          <el-option label="公告" value="announcement" />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable style="width: 120px">
          <el-option label="普通" value="0" />
          <el-option label="重要" value="1" />
          <el-option label="紧急" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:notification:add']"
        >新增通知</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:notification:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 通知列表 -->
    <el-table v-loading="loading" :data="notificationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="通知标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="通知类型" align="center" prop="notificationType" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.notificationType === 'system'" type="primary" size="small">系统通知</el-tag>
          <el-tag v-else-if="scope.row.notificationType === 'maintenance'" type="warning" size="small">维护通知</el-tag>
          <el-tag v-else-if="scope.row.notificationType === 'announcement'" type="success" size="small">公告</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.priority === '0'" type="info" size="small">普通</el-tag>
          <el-tag v-else-if="scope.row.priority === '1'" type="warning" size="small">重要</el-tag>
          <el-tag v-else-if="scope.row.priority === '2'" type="danger" size="small">紧急</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发送者" align="center" prop="senderName" width="100" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.status === '0'" type="info" size="small">草稿</el-tag>
          <el-tag v-else-if="scope.row.status === '1'" type="success" size="small">已发布</el-tag>
          <el-tag v-else-if="scope.row.status === '2'" type="danger" size="small">已撤回</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="publishTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:notification:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.status === '0'"
            link
            type="primary"
            icon="Promotion"
            @click="handlePublish(scope.row)"
            v-hasPermi="['system:notification:publish']"
          >发布</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:notification:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改通知对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="通知标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入通知标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="通知类型" prop="notificationType">
              <el-select v-model="form.notificationType" placeholder="请选择通知类型" style="width: 100%">
                <el-option label="系统通知" value="system" />
                <el-option label="维护通知" value="maintenance" />
                <el-option label="公告" value="announcement" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%">
                <el-option label="普通" value="0" />
                <el-option label="重要" value="1" />
                <el-option label="紧急" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="目标类型" prop="targetType">
              <el-radio-group v-model="form.targetType">
                <el-radio value="1">全部用户</el-radio>
                <el-radio value="2">指定用户</el-radio>
                <el-radio value="3">指定角色</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.targetType === '2'">
          <el-col :span="24">
            <el-form-item label="目标用户" prop="targetUsers">
              <el-select
                v-model="selectedUsers"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="请选择用户"
                :remote-method="searchUsers"
                :loading="userLoading"
                style="width: 100%"
              >
                <el-option
                  v-for="user in userOptions"
                  :key="user.userId"
                  :label="user.nickName || user.userName"
                  :value="user.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="通知内容" prop="content">
              <el-input
                v-model="form.content"
                type="textarea"
                :rows="6"
                placeholder="请输入通知内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="过期时间">
              <el-date-picker
                v-model="form.expireTime"
                type="datetime"
                placeholder="选择过期时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Notification">
import { 
  listNotification, 
  getNotification, 
  delNotification, 
  addNotification, 
  updateNotification,
  publishNotification 
} from "@/api/system/message"
import { listUser } from "@/api/system/user"

const { proxy } = getCurrentInstance()

const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const notificationList = ref([])
const title = ref("")
const open = ref(false)
const queryFormRef = ref(null)
const formRef = ref(null)

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  title: null,
  notificationType: null,
  priority: null,
  status: null
})

const form = ref({})

const rules = {
  title: [
    { required: true, message: "通知标题不能为空", trigger: "blur" }
  ],
  content: [
    { required: true, message: "通知内容不能为空", trigger: "blur" }
  ],
  notificationType: [
    { required: true, message: "通知类型不能为空", trigger: "change" }
  ],
  priority: [
    { required: true, message: "优先级不能为空", trigger: "change" }
  ],
  targetType: [
    { required: true, message: "目标类型不能为空", trigger: "change" }
  ]
}

const userOptions = ref([])
const selectedUsers = ref([])
const userLoading = ref(false)

/** 查询通知列表 */
function getList() {
  loading.value = true
  listNotification(queryParams.value).then(response => {
    notificationList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    notificationId: null,
    title: null,
    content: null,
    notificationType: "system",
    priority: "0",
    targetType: "1",
    targetUsers: null,
    targetRoles: null,
    expireTime: null
  }
  selectedUsers.value = []
  proxy.resetForm("formRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryFormRef")
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.notificationId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加通知"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const notificationId = row.notificationId || ids.value
  getNotification(notificationId).then(response => {
    form.value = response.data
    if (form.value.targetUsers) {
      selectedUsers.value = JSON.parse(form.value.targetUsers)
    }
    open.value = true
    title.value = "修改通知"
  })
}

/** 提交按钮 */
function submitForm() {
  formRef.value.validate(valid => {
    if (valid) {
      if (form.value.targetType === '2' && selectedUsers.value.length > 0) {
        form.value.targetUsers = JSON.stringify(selectedUsers.value)
      } else {
        form.value.targetUsers = null
      }
      
      if (form.value.notificationId != null) {
        updateNotification(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addNotification(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const notificationIds = row.notificationId || ids.value
  proxy.$modal.confirm('是否确认删除通知编号为"' + notificationIds + '"的数据项？').then(() => {
    return delNotification(notificationIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 发布按钮操作 */
function handlePublish(row) {
  proxy.$modal.confirm('是否确认发布此通知？发布后将立即推送给目标用户。').then(() => {
    return publishNotification(row.notificationId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("发布成功")
  }).catch(() => {})
}

/** 搜索用户 */
function searchUsers(query) {
  if (query !== '') {
    userLoading.value = true
    listUser({
      userName: query,
      pageNum: 1,
      pageSize: 20
    }).then(response => {
      userOptions.value = response.rows || []
      userLoading.value = false
    }).catch(() => {
      userLoading.value = false
    })
  } else {
    userOptions.value = []
  }
}

getList()
</script>
