<template>
  <el-dialog title="发布系统通知" v-model="visible" width="800px" append-to-body @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="通知标题" prop="title">
        <el-select
          v-model="form.title"
          filterable
          allow-create
          default-first-option
          placeholder="选择或输入通知标题"
          style="width: 100%"
        >
          <el-option label="系统维护通知" value="系统维护通知" />
          <el-option label="版本更新通知" value="版本更新通知" />
          <el-option label="重要公告" value="重要公告" />
          <el-option label="安全提醒" value="安全提醒" />
          <el-option label="活动通知" value="活动通知" />
          <el-option label="节假日通知" value="节假日通知" />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-radio-group v-model="form.priority">
          <el-radio value="0">普通</el-radio>
          <el-radio value="1">重要</el-radio>
          <el-radio value="2">紧急</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="接收者" prop="receiverIds">
        <div class="receiver-selector">
          <div class="selector-actions">
            <el-button icon="User" @click="openSelectUserDialog">
              选择接收者
            </el-button>
            <el-button icon="CircleCheck" @click="selectAllUsers">
              全选
            </el-button>
            <el-button v-if="form.receiverIds && form.receiverIds.length > 0" icon="Delete" @click="clearReceivers">
              清空
            </el-button>
          </div>
          <div class="selected-users">
            <el-tag
              v-for="userId in form.receiverIds"
              :key="userId"
              closable
              @close="removeReceiver(userId)"
              style="margin: 4px;"
            >
              {{ getUserName(userId) }}
            </el-tag>
            <div v-if="!form.receiverIds || form.receiverIds.length === 0" class="empty-tip">
              未选择接收者
            </div>
          </div>
          <div class="receiver-count">
            <el-tag size="small" type="success">已选择 {{ form.receiverIds ? form.receiverIds.length : 0 }} 人</el-tag>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="消息内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="8"
          placeholder="请输入消息内容"
          maxlength="2000"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </div>
    </template>
    
    <!-- 选择用户对话框 -->
    <select-user-dialog ref="selectUserDialogRef" @confirm="handleUserSelected" />
  </el-dialog>
</template>

<script setup name="SendMessageDialog">
import { addNotification } from "@/api/system/message"
import { listUser } from "@/api/system/user"
import SelectUserDialog from "./SelectUserDialog.vue"

const { proxy } = getCurrentInstance()
const emit = defineEmits(['success'])

const visible = ref(false)
const submitLoading = ref(false)
const userList = ref([])
const formRef = ref(null)
const selectUserDialogRef = ref(null)

const form = ref({
  title: null,
  content: null,
  messageType: '2',
  priority: '0',
  receiverIds: [],
  receiverNames: []
})

const rules = {
  title: [
    { required: true, message: "消息标题不能为空", trigger: "blur" }
  ],
  content: [
    { required: true, message: "消息内容不能为空", trigger: "blur" }
  ],
  receiverIds: [
    { required: true, message: "请至少选择一个接收者", trigger: "change" }
  ]
}

/** 打开对话框 */
function open() {
  visible.value = true
  getUserList()
}

/** 获取用户列表 */
function getUserList() {
  listUser({ pageNum: 1, pageSize: 1000 }).then(response => {
    userList.value = response.rows || []
  })
}

/** 打开选择用户对话框 */
function openSelectUserDialog() {
  selectUserDialogRef.value.open(form.value.receiverIds)
}

/** 处理用户选择 */
function handleUserSelected(users) {
  form.value.receiverIds = users.map(u => u.userId)
  form.value.receiverNames = users.map(u => u.userName)
  proxy.$modal.msgSuccess(`已选择 ${users.length} 人`)
}

/** 全选用户 */
function selectAllUsers() {
  form.value.receiverIds = userList.value.map(u => u.userId)
  form.value.receiverNames = userList.value.map(u => u.userName)
  proxy.$modal.msgSuccess(`已选择全部 ${userList.value.length} 人`)
}

/** 清空接收者 */
function clearReceivers() {
  form.value.receiverIds = []
  form.value.receiverNames = []
}

/** 移除单个接收者 */
function removeReceiver(userId) {
  const index = form.value.receiverIds.indexOf(userId)
  if (index > -1) {
    form.value.receiverIds.splice(index, 1)
    form.value.receiverNames.splice(index, 1)
  }
}

/** 获取用户名称 */
function getUserName(userId) {
  const user = userList.value.find(u => u.userId === userId)
  return user ? user.nickName : userId
}

/** 提交按钮 */
function submitForm() {
  formRef.value.validate(valid => {
    if (valid) {
      submitLoading.value = true
      // 构建发送数据，将 receiverIds 转换为后端需要的格式
      const submitData = {
        title: form.value.title,
        content: form.value.content,
        priority: form.value.priority,
        targetType: '2', // 2=指定用户
        targetUsers: JSON.stringify(form.value.receiverIds)
      }
      addNotification(submitData).then(response => {
        proxy.$modal.msgSuccess("发送成功")
        visible.value = false
        emit('success')
      }).finally(() => {
        submitLoading.value = false
      })
    }
  })
}

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

/** 关闭对话框 */
function handleClose() {
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    title: null,
    content: null,
    messageType: '2',
    priority: '0',
    receiverIds: [],
    receiverNames: []
  }
  proxy.resetForm("formRef")
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.receiver-selector {
  .selector-actions {
    margin-bottom: 12px;
    display: flex;
    gap: 8px;
  }
  
  .selected-users {
    min-height: 80px;
    max-height: 200px;
    overflow-y: auto;
    padding: 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background: #f5f7fa;
    
    .empty-tip {
      color: #909399;
      font-size: 13px;
      text-align: center;
      padding: 20px 0;
    }
  }
  
  .receiver-count {
    margin-top: 8px;
  }
}
</style>
