<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.search.title" prefix-icon="Search" style="width: 240px; margin-right: 10px; margin-bottom: 3px" placeholder="请输入公告标题" clearable></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin-right: 10px" @click="reset">重置</el-button>
    </div>
    <div v-if="data.user.role === 'admin'" class="card" style="margin-bottom: 5px">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px;">
      <el-table :data="data.tableData" strip>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="title" label="标题" min-width="150"></el-table-column>
        <el-table-column prop="publisherName" label="发布人" width="120"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="置顶" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.isTop" type="danger">已置顶</el-tag>
            <el-tag v-else type="info">未置顶</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">已发布</el-tag>
            <el-tag v-else type="warning">草稿</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" plain @click="handleView(scope.row)">查看</el-button>
            <el-button type="danger" plain @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="total, prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total"/>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="data.form.id ? '编辑公告' : '新增公告'" v-model="data.formVisible" width="65%" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" label-width="80px" :rules="rules" ref="formRef" style="padding: 20px 30px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="data.form.title" placeholder="请输入公告标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <div class="editor-container">
            <Editor
              v-model="data.form.content"
              :defaultConfig="editorConfig"
              style="height: 300px"
            />
          </div>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="data.form.status">
            <el-radio :label="0">草稿</el-radio>
            <el-radio :label="1">发布</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="置顶">
          <el-switch v-model="data.form.isTop"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog title="公告详情" v-model="data.viewDialogVisible" width="65%">
      <h2 style="text-align: center; margin-bottom: 20px">{{ data.viewForm.title }}</h2>
      <div style="text-align: center; color: #999; margin-bottom: 20px">
        发布人: {{ data.viewForm.publisherName }} | 发布时间: {{ data.viewForm.createTime }}
      </div>
      <div class="content-container" v-html="data.viewForm.content"></div>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import request from '@/utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Editor } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';

const baseApi = 'announcement';

// 富文本编辑器配置
const editorConfig = {
  placeholder: '请输入内容...',
};

// 表单校验规则
const rules = {
  title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }],
};

// 表单引用
const formRef = ref(null);

// 数据定义
const data = reactive({
  user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
  tableData: [],
  total: 0,
  pageNum: 1,  // 当前的页码
  pageSize: 10,  // 每页的个数
  formVisible: false,
  viewDialogVisible: false,
  form: {},
  viewForm: {},
  search: {},
});

// 加载数据
const load = () => {
  data.search.pageNum = data.pageNum;
  data.search.pageSize = data.pageSize;
  request.get(baseApi + '/adminPage', {
    params: data.search
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list || [];
      data.total = res.data?.total;
    } else {
      ElMessage.error(res.msg || '获取数据失败');
    }
  }).catch(error => {
    console.error('加载数据出错', error);
    ElMessage.error('加载数据出错');
  });
};

// 重置搜索条件
const reset = () => {
  data.search = {};
  load();
};

// 新增公告
const handleAdd = () => {
  data.form = {
    id: null,
    title: '',
    content: '',
    isTop: false,
    status: 0,
  };
  data.formVisible = true;
};

// 编辑公告
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.formVisible = true;
};

// 查看公告
const handleView = (row) => {
  data.viewForm = JSON.parse(JSON.stringify(row));
  data.viewDialogVisible = true;
};

// 删除公告
const del = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗?', '删除确认', { type: 'warning' }).then(res => {
    request.delete(baseApi + '/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功');
        load();
      } else {
        ElMessage.error(res.msg || '删除失败');
      }
    }).catch(error => {
      console.error('删除出错', error);
      ElMessage.error('删除出错');
    });
  }).catch(err => {
    console.error(err);
  });
};

// 保存公告
const save = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res;
        if (data.form.id) {
          // 编辑
          res = await request.put(baseApi, data.form);
        } else {
          // 新增
          res = await request.post(baseApi, data.form);
        }
        
        if (res.code === '200') {
          ElMessage.success(data.form.id ? '编辑成功' : '新增成功');
          data.formVisible = false;
          load();
        } else {
          ElMessage.error(res.msg || (data.form.id ? '编辑失败' : '新增失败'));
        }
      } catch (error) {
        console.error(data.form.id ? '编辑出错' : '新增出错', error);
        ElMessage.error(data.form.id ? '编辑出错' : '新增出错');
      }
    }
  });
};

// 页面加载时获取数据
onMounted(() => {
  load();
});
</script>

<style scoped>
.card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
  padding: 20px;
  box-sizing: border-box;
}

:deep(.editor-container) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.content-container {
  padding: 0 20px;
  line-height: 1.6;
}
</style> 