<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </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>

    
    <br>

    <div v-loading="loading">
      <div v-if="topList && topList.length" class="ann-list">
        <div class="ann-list-title">置顶公告</div>
        <div class="ann-item" v-for="a in topList" :key="'top-'+a.id">
          <div class="ann-left">
            <span class="ann-icon"></span>
            <span class="ann-title" @click="openDetail(a)">{{ a.title }}</span>
          </div>
          <div class="ann-date">{{ formatDate(a.createTime) }}</div>
        </div>
      </div>
      <div v-if="announcementList && announcementList.length" class="ann-list" style="margin-top: 12px;">
        <div class="ann-list-title">公告列表</div>
        <div class="ann-item" v-for="a in announcementList" :key="a.id">
          <div class="ann-left">
            <span class="ann-icon"></span>
            <span class="ann-title" @click="openDetail(a)">{{ a.title }}</span>
          </div>
          <div class="ann-date">{{ formatDate(   a.createTime) }}</div>
        </div>
      </div>
      <el-empty v-else description="暂无公告" />
    </div>

    <el-dialog v-model="detailOpen" title="公告详情" width="700px" append-to-body>
      <div class="ann-detail">
        <div class="ann-detail-title">{{ detailData.title }}</div>
        <div class="ann-detail-meta">发布时间：{{ formatDate(detailData.updateTime || detailData.createTime) }}</div>
        <div class="ann-detail-content" v-html="detailData.content"></div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen=false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <br>
    <div class="pagination-wrapper">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="queryParams.pageSize"
          layout=", prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    
  </div>
</template>

<script setup name="Announcement">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { listTouristAnnouncements, getAnnouncement, delAnnouncement, addAnnouncement, updateAnnouncement } from "@/api/announcement";

const { proxy } = getCurrentInstance();

const announcementList = ref([]);
const topList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");

const isAdd = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    content: null,
    isTop: null,
    status: null,
    creator: null,
    updater: null
  },
  rules: {
    title: [
      { required: true, message: "标题不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "内容不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询公告列表 */
function getList() {
  loading.value = true;
  const { pageNum, pageSize, title } = queryParams.value
  listTouristAnnouncements({ pageNum, pageSize, title }).then(response => {
    const data = response.data || response
    topList.value = data.topList || []
    announcementList.value = data.list || []
    total.value = Number(data.total || 0)
  }).finally(() => { loading.value = false })
}

// 改变每页条数大小
function handleSizeChange(val) {
  queryParams.value.pageSize = val;
  getList();
}

// 换页
function handleCurrentChange(val) {
  queryParams.value.pageNum = val;
  getList();
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    content: null,
    isTop: null,
    status: null,
    createTime: null,
    creator: null,
    updateTime: null,
    updater: null
  };
  const announcementRef = proxy.$refs["announcementRef"]
  if (announcementRef) {
    announcementRef.resetFields();
  }
}

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

/** 重置按钮操作 */
function resetQuery() {
  const queryRef = proxy.$refs["queryRef"]
  if (queryRef) {
    queryRef.resetFields();
  }
  handleQuery();
}


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

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getAnnouncement(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改公告";
    isAdd.value = false;
  });
}

function formatDate(val) {
  if (!val) return ''
  const d = new Date(val)
  if (isNaN(d.getTime())) return ''
  const y = d.getFullYear()
  const M = String(d.getMonth() + 1).padStart(2, '0')
  const D = String(d.getDate()).padStart(2, '0')
  return `${y}.${M}.${D}`
}

const detailOpen = ref(false)
const detailData = ref({})

function openDetail(a) {
  const id = a && a.id
  if (!id) return
  getAnnouncement(id).then(response => {
    detailData.value = response.data || {}
    detailOpen.value = true
  })
}

/** 表单提交按钮 */
function submitForm() {
  proxy.$refs["announcementRef"].validate(valid => {
    if (valid) {
      if (isAdd.value) {  // 添加
        addAnnouncement(form.value).then(response => {
          proxy.$message({
            message: response.msg,
            type: 'success'
          })
          open.value = false;
          getList();
        });
      } else {  // 更新
        updateAnnouncement(form.value).then(response => {
          proxy.$message({
            message: response.msg,
            type: 'success'
          })
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$confirm('是否确认删除公告编号为"' + row.id + '"的数据项？').then(function() {
    return delAnnouncement(row.id);
  }).then(response => {
    getList();
    proxy.$message({
      message: response.msg,
      type: 'success'
    })
  }).catch(() => {});
}

/** 导出按钮操作 */
// function handleExport() {
//   proxy.download('system/announcement/export', {
//     ...queryParams.value
//   }, `announcement_${new Date().getTime()}.xlsx`)
// }

getList();
</script>

<style scoped>
.app-container {
  width: 80%;
  margin: 24px auto 40px;
}

.mb8 { margin-bottom: 8px; }

:deep(.el-form) {
  display: flex;
  justify-content: center;
}

.pagination-wrapper { display: flex; justify-content: center; }

:deep(.el-row.mb8) { justify-content: center; }

.ann-list { background: #fff; border: 1px solid #e7dfcf; border-radius: 12px; padding: 8px 16px; }
.ann-list-title { font-weight: 700; color: #2c1f1f; margin: 8px 0; }
.ann-item { display: flex; align-items: center; justify-content: space-between; padding: 12px 6px; border-bottom: 1px dashed #e7dfcf; }
.ann-item:last-child { border-bottom: none; }
.ann-left { display: flex; align-items: center; gap: 8px; }
.ann-icon { width: 10px; height: 10px; border: 1px solid #c9a36a; border-radius: 2px; background: #f9f6f1; display: inline-block; }
.ann-title { color: #2c1f1f; }
.ann-title:hover { color: #8a2b2b; }
.ann-title { cursor: pointer; }
.ann-date { color: #8a2b2b; font-size: 12px; }

.ann-detail-title { font-size: 20px; font-weight: 700; color: #2c1f1f; }
.ann-detail-meta { color: #909399; font-size: 12px; margin: 6px 0 12px; }
.ann-detail-content :deep(p) { margin: 8px 0; line-height: 1.8; }
.ann-detail-content { color: #606266; }
.ann-detail-content>>>img {
  width: 100%;
}
</style>
