<template>
  <div class="frame-body adaption-frame-body summary-announcement-page">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <div>
            <div class="page-title">内部公告</div>
            <div class="page-subtitle">按旧版公告页方式展示发布内容，保留时间筛选和发布维护能力。</div>
          </div>
          <div class="page-actions">
            <el-button @click="reset">重置</el-button>
            <el-button type="primary" @click="openCreate">发布公告</el-button>
          </div>
        </div>
      </template>

      <el-form :inline="true" @submit.prevent class="toolbar">
        <el-form-item>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            value-format="YYYY-MM-DD"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @change="searchList"
          />
        </el-form-item>
      </el-form>

      <div v-loading="loading" class="announcement-list">
        <el-empty v-if="!rows.length && !loading" description="暂无公告" />

        <article v-for="item in rows" :key="item.bulletinId || item.id" class="announcement-card">
          <div class="announcement-top">
            <div class="publisher-block">
              <el-avatar :size="36">{{ getAvatarText(item.staffName) }}</el-avatar>
              <div>
                <div class="publisher-name">{{ item.staffName || item.publisher || '-' }}</div>
                <div class="publisher-time">发布时间：{{ item.createTime || item.createdAt || '-' }}</div>
              </div>
            </div>
            <div class="meta-actions">
              <el-button v-if="item.canUpdate" link type="primary" @click="openEdit(item)">编辑</el-button>
              <el-button v-if="item.canDelete" link type="danger" @click="remove(item)">删除</el-button>
            </div>
          </div>

          <div class="announcement-headline">
            <h3>{{ item.title || '-' }}</h3>
            <span>截止时间：{{ item.deadlineDate || '-' }}</span>
          </div>

          <div class="announcement-content ql-editor" v-html="item.content || '-'" />

          <div class="announcement-foot">
            <span>通知范围：{{ Number(item.bulletinType) === 1 ? '全体员工' : '指定人员' }}</span>
            <span>已读人数：{{ countRead(item.readVOs) }}</span>
            <span>通知人数：{{ Array.isArray(item.readVOs) ? item.readVOs.length : 0 }}</span>
          </div>
        </article>
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="960px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="截止时间" prop="deadlineDate">
          <el-date-picker v-model="form.deadlineDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择截止时间" />
        </el-form-item>
        <el-form-item label="接收范围" prop="bulletinType">
          <el-radio-group v-model="form.bulletinType">
            <el-radio :value="1">全体员工</el-radio>
            <el-radio :value="2">指定人员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <Editor v-model="form.content" :min-height="240" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref } from 'vue'
import moment from 'moment'
import Editor from '@/components/Editor/index.vue'
import {
  summaryAnnouncementList,
  summaryBulletinAdd,
  summaryBulletinDelete,
  summaryBulletinEdit,
} from '@/api/otr/summary/core'

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('发布公告')
const editingId = ref<string | number | null>(null)
const rows = ref<any[]>([])
const formRef = ref<ElFormInstance>()
const dateRange = ref<[string, string] | string[]>([])

const form = reactive({
  title: '',
  deadlineDate: '',
  bulletinType: 1,
  content: '',
})

const rules = reactive({
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  deadlineDate: [{ required: true, message: '截止时间不能为空', trigger: 'change' }],
  bulletinType: [{ required: true, message: '接收范围不能为空', trigger: 'change' }],
  content: [{ required: true, message: '公告内容不能为空', trigger: 'blur' }],
})

function getAvatarText(name?: string) {
  return name ? name.slice(-1) : '公'
}

function countRead(list: any[]) {
  if (!Array.isArray(list)) return 0
  return list.filter((item) => item?.hasRead).length
}

async function load() {
  loading.value = true
  try {
    const res: any = await summaryAnnouncementList({
      pageIndex: 1,
      pageSize: 20,
      startDate: dateRange.value?.[0] || '',
      endDate: dateRange.value?.[1] || '',
    })
    const result = res?.result || {}
    rows.value = result.records || result.list || []
  } finally {
    loading.value = false
  }
}

function resetForm() {
  form.title = ''
  form.deadlineDate = ''
  form.bulletinType = 1
  form.content = ''
}

function searchList() {
  load()
}

function reset() {
  dateRange.value = []
  load()
}

function openCreate() {
  editingId.value = null
  dialogTitle.value = '发布公告'
  resetForm()
  dialogVisible.value = true
}

function openEdit(row: any) {
  editingId.value = row.bulletinId || row.id
  dialogTitle.value = '编辑公告'
  form.title = row.title || ''
  form.deadlineDate = row.deadlineDate || ''
  form.bulletinType = Number(row.bulletinType || 1)
  form.content = row.content || ''
  dialogVisible.value = true
}

async function submit() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return
  submitting.value = true
  try {
    const payload: Record<string, any> = {
      title: form.title,
      deadlineDate: form.deadlineDate,
      bulletinType: form.bulletinType,
      content: form.content,
      noticeTime: moment().format('YYYY-MM-DD'),
    }
    if (editingId.value) {
      payload.id = editingId.value
      payload.bulletinId = editingId.value
      await summaryBulletinEdit(payload)
      ElMessage.success('编辑成功')
    } else {
      await summaryBulletinAdd(payload)
      ElMessage.success('发布成功')
    }
    dialogVisible.value = false
    load()
  } finally {
    submitting.value = false
  }
}

function remove(row: any) {
  ElMessageBox.confirm('确定删除这条公告吗？', '系统提示', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await summaryBulletinDelete(row.bulletinId || row.id)
      ElMessage.success('删除成功')
      load()
    })
    .catch(() => undefined)
}

load()
</script>

<style scoped lang="scss">
.summary-announcement-page {
  .page-header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 16px;
  }

  .page-title {
    font-size: 18px;
    font-weight: 600;
    color: #111827;
  }

  .page-subtitle {
    margin-top: 4px;
    font-size: 13px;
    color: #6b7280;
  }

  .page-actions {
    display: flex;
    gap: 12px;
  }

  .toolbar {
    margin-bottom: 16px;
  }

  .announcement-list {
    display: grid;
    gap: 16px;
  }

  .announcement-card {
    padding: 22px;
    border: 1px solid #e5e7eb;
    border-radius: 14px;
    background: linear-gradient(180deg, #ffffff 0%, #fafcfe 100%);
  }

  .announcement-top {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 16px;
  }

  .publisher-block {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .publisher-name {
    font-size: 15px;
    font-weight: 600;
    color: #111827;
  }

  .publisher-time {
    margin-top: 4px;
    color: #6b7280;
    font-size: 12px;
  }

  .meta-actions {
    display: flex;
    gap: 8px;
  }

  .announcement-headline {
    margin-top: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
  }

  .announcement-headline h3 {
    margin: 0;
    font-size: 20px;
    color: #111827;
  }

  .announcement-headline span {
    color: #6b7280;
    font-size: 13px;
  }

  .announcement-content {
    margin-top: 18px;
    padding: 0;
    color: #374151;
  }

  .announcement-foot {
    margin-top: 18px;
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    color: #6b7280;
    font-size: 13px;
  }
}
</style>

