<template>
  <div class="page-card">
    <h3>通知公告</h3>
    <div style="margin-bottom: 12px;">
      <el-button type="primary" @click="showCreate = true">发布通知</el-button>
    </div>
    <el-table :data="items" stripe>
      <el-table-column prop="id" label="编号" width="80" />
      <el-table-column prop="title" label="标题" />
      <el-table-column label="对象" width="120">
        <template slot-scope="scope">
          <el-tag :type="targetTag(scope.row.targetRole)">
            {{ targetLabel(scope.row.targetRole) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" />
    </el-table>

    <el-dialog title="发布通知" :visible.sync="showCreate">
      <el-form :model="form" label-width="120px">
        <el-form-item label="标题"><el-input v-model="form.title"/></el-form-item>
        <el-form-item label="内容"><el-input v-model="form.content" type="textarea"/></el-form-item>
        <el-form-item label="通知对象">
          <el-select v-model="form.targetRole">
            <el-option label="全部" value="ALL" />
            <el-option label="护工" value="NURSE" />
            <el-option label="家属" value="FAMILY" />
          </el-select>
        </el-form-item>
        <el-form-item label="指定用户ID"><el-input v-model="form.targetUserId"/></el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="showCreate = false">取消</el-button>
        <el-button type="primary" @click="create">发布</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { noticeCreate, noticeList } from "../../api";

export default {
  data() {
    return {
      items: [],
      showCreate: false,
      form: { title: "", content: "", targetRole: "ALL", targetUserId: "" }
    };
  },
  created() {
    this.load();
  },
  methods: {
    targetLabel(role) {
      if (role === "ALL") return "全部";
      if (role === "NURSE") return "护工";
      if (role === "FAMILY") return "家属";
      return role || "-";
    },
    targetTag(role) {
      if (role === "ALL") return "";
      if (role === "NURSE") return "success";
      if (role === "FAMILY") return "info";
      return "info";
    },
    async load() {
      try {
        const res = await noticeList();
        this.items = res.data.data;
      } catch (e) {
        this.$message.error(e.message || "加载失败");
      }
    },
    async create() {
      try {
        const payload = { ...this.form, targetUserId: this.form.targetUserId || null };
        await noticeCreate(payload);
        this.showCreate = false;
        this.load();
      } catch (e) {
        this.$message.error(e.message || "创建失败");
      }
    }
  }
};
</script>

