<template>
  <div class="announcement-page">
    <div class="announcement-container">
      <!-- 搜索区域 -->
      <div class="search-card">
        <el-form :model="queryParams" :inline="true">
          <el-form-item label="公告标题">
            <el-input v-model="queryParams.announcementTitle" placeholder="请输入公告标题" clearable style="width: 240px" />
          </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>
      </div>

      <!-- 表格区域 -->
      <div class="table-card">
        <div class="table-header">
          <span class="table-title">平台公告信息列表</span>
          <div class="table-actions">
            <el-button type="primary" icon="Plus" @click="handleAdd">新增公告</el-button>
            <el-button icon="Refresh" circle size="small" @click="getList" />
          </div>
        </div>

        <el-table v-loading="loading" :data="announcementList" border>
          <el-table-column label="编号" align="center" prop="announcementNo" width="100" />
          <el-table-column label="封面图片" align="center" width="100">
            <template #default="scope">
              <el-image
                v-if="scope.row.coverImageUrl"
                :src="scope.row.coverImageUrl"
                :preview-src-list="[scope.row.coverImageUrl]"
                fit="contain"
                style="width: 60px; height: 60px"
                preview-teleported
              />
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="标题" align="center" prop="announcementTitle" min-width="300" show-overflow-tooltip />
          <el-table-column label="是否显示" align="center" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.isShow === 1 ? 'primary' : 'info'" effect="plain" size="small">
                {{ scope.row.isShow === 1 ? '显示' : '隐藏' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="发布时间" align="center" prop="createTime" width="180" />
          <el-table-column label="查看" align="center" prop="viewCount" width="80" />
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <el-link type="primary" @click="handleEdit(scope.row)">编辑</el-link>
              <el-link type="danger" @click="handleDelete(scope.row)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="total"
          @pagination="handlePagination"
        />
      </div>
    </div>

    <!-- 新增/编辑侧边栏 -->
    <el-drawer v-model="dialog.visible" :title="dialog.title" size="1000px" direction="rtl" append-to-body :destroy-on-close="true">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公告编号" prop="announcementNo">
              <el-input v-model="form.announcementNo" placeholder="请输入公告编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否显示" prop="isShow">
              <el-switch v-model="form.isShow" :active-value="1" :inactive-value="0" active-text="显示" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="公告标题" prop="announcementTitle">
          <el-input v-model="form.announcementTitle" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImage">
          <upload-image v-model="form.coverImage" :limit="1" />
        </el-form-item>
        <el-form-item label="公告内容" prop="announcementContent">
          <editor v-model="form.announcementContent" :min-height="200" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 认</el-button>
        <el-button @click="dialog.visible = false">取 消</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="OperationAnnouncement" lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import type { FormInstance } from 'element-plus';
import { listAnnouncement, getAnnouncement, addAnnouncement, updateAnnouncement, delAnnouncement } from '@/api/system/announcement';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 查询参数
const queryParams = reactive({
  announcementTitle: '',
  platformCode: 'opm',
  pageNum: 1,
  pageSize: 10
});

// 列表数据
const announcementList = ref<any[]>([]);
const loading = ref(false);
const total = ref(0);

// 对话框
const dialog = reactive({
  visible: false,
  title: ''
});

// 表单
const formRef = ref<FormInstance>();
const initForm = {
  id: undefined as number | undefined,
  announcementNo: '',
  announcementTitle: '',
  announcementContent: '',
  coverImage: '',
  isShow: 1,
  platformCode: 'opm'
};
const form = ref({ ...initForm });

const rules = {
  announcementTitle: [{ required: true, message: '请输入公告标题', trigger: 'blur' }]
};

// 查询列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await listAnnouncement(queryParams);
    announcementList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('加载列表失败', error);
    proxy?.$modal.msgError('加载列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 分页
const handlePagination = (paging: { page: number; limit: number }) => {
  queryParams.pageNum = paging.page;
  queryParams.pageSize = paging.limit;
  getList();
};

// 重置
const resetQuery = () => {
  queryParams.announcementTitle = '';
  handleQuery();
};

// 新增
const handleAdd = () => {
  form.value = { ...initForm };
  formRef.value?.resetFields();
  dialog.title = '新增公告';
  dialog.visible = true;
};

// 编辑
const handleEdit = async (row: any) => {
  try {
    const res = await getAnnouncement(row.id);
    form.value = {
      id: res.data.id,
      announcementNo: res.data.announcementNo || '',
      announcementTitle: res.data.announcementTitle || '',
      announcementContent: res.data.announcementContent || '',
      coverImage: res.data.coverImage || '',
      isShow: res.data.isShow ?? 1,
      platformCode: 'opm'
    };
    formRef.value?.resetFields();
    dialog.title = '编辑公告';
    dialog.visible = true;
  } catch (error) {
    console.error('获取详情失败', error);
    proxy?.$modal.msgError('获取详情失败');
  }
};

// 删除
const handleDelete = (row: any) => {
  proxy?.$modal.confirm(`是否确认删除公告"${row.announcementTitle}"？`).then(async () => {
    try {
      await delAnnouncement(row.id);
      proxy?.$modal.msgSuccess('删除成功');
      getList();
    } catch (error) {
      console.error('删除失败', error);
      proxy?.$modal.msgError('删除失败');
    }
  });
};

// 提交表单
const submitForm = async () => {
  const valid = await formRef.value?.validate();
  if (!valid) return;

  try {
    if (form.value.id) {
      await updateAnnouncement(form.value);
      proxy?.$modal.msgSuccess('修改成功');
    } else {
      await addAnnouncement(form.value);
      proxy?.$modal.msgSuccess('添加成功');
    }
    dialog.visible = false;
    getList();
  } catch (error) {
    console.error('保存失败', error);
    proxy?.$modal.msgError('保存失败');
  }
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.announcement-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px;
}

.announcement-container {
  max-width: 1200px;
  margin: 0 auto;
}

.search-card {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 12px;
}

.table-card {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

:deep(.el-link) {
  margin: 0 8px;
}
</style>
