<template>
  <div class="frame-body adaption-frame-body summary-share-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="share-list">
        <el-empty v-if="!rows.length && !loading" description="暂无心得分享" />

        <article v-for="item in rows" :key="item.summaryShareId || item.id" class="share-card">
          <div class="share-meta">
            <div class="author-block">
              <el-avatar :size="36">{{ getAvatarText(item.staffName) }}</el-avatar>
              <div>
                <div class="author-row">
                  <span class="author-name">{{ item.staffName || item.author || '-' }}</span>
                  <el-tag v-if="item.isTop === 1" size="small" type="warning">置顶</el-tag>
                </div>
                <div class="author-time">{{ item.createTime || item.createdAt || '-' }}</div>
              </div>
            </div>
            <div class="meta-actions">
              <el-button v-if="item.canChoose" link type="warning" @click="toggleTop(item)">
                {{ item.isTop === 1 ? '取消置顶' : '置顶' }}
              </el-button>
              <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="share-content ql-editor" v-html="item.shareContent || item.content || '-'" />

          <div class="share-footer">
            <span class="like-count">点赞 {{ item.likeCount || item.likes || 0 }}</span>
            <span class="like-users">{{ formatLikeUsers(item.userList) }}</span>
          </div>
        </article>
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="960px" destroy-on-close>
      <el-form label-width="90px">
        <el-form-item label="分享内容">
          <Editor v-model="form.shareContent" :min-height="220" />
        </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 {
  summaryShareAdd,
  summaryShareDelete,
  summaryShareList,
  summaryShareTop,
  summaryShareUnTop,
} 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 dateRange = ref<[string, string] | string[]>([
  moment().subtract(1, 'month').format('YYYY-MM-DD'),
  moment().format('YYYY-MM-DD'),
])

const form = reactive({
  shareContent: '',
})

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

function formatLikeUsers(users: any[]) {
  if (!Array.isArray(users) || !users.length) return '暂无点赞'
  return users.map((item) => item.userName || item.realName || item.name).filter(Boolean).join('、')
}

async function load() {
  loading.value = true
  try {
    const res: any = await summaryShareList({
      pageNo: 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 searchList() {
  load()
}

function reset() {
  dateRange.value = [moment().subtract(1, 'month').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
  load()
}

function openCreate() {
  editingId.value = null
  dialogTitle.value = '新增心得分享'
  form.shareContent = ''
  dialogVisible.value = true
}

function openEdit(row: any) {
  editingId.value = row.summaryShareId || row.id
  dialogTitle.value = '编辑心得分享'
  form.shareContent = row.shareContent || row.content || ''
  dialogVisible.value = true
}

async function submit() {
  if (!form.shareContent.trim() || form.shareContent === '<p></p>') {
    ElMessage.warning('心得内容不能为空')
    return
  }
  submitting.value = true
  try {
    const payload: Record<string, any> = { shareContent: form.shareContent }
    if (editingId.value) payload.summaryShareId = editingId.value
    await summaryShareAdd(payload)
    ElMessage.success(editingId.value ? '编辑成功' : '新增成功')
    dialogVisible.value = false
    load()
  } finally {
    submitting.value = false
  }
}

async function toggleTop(row: any) {
  if (row.isTop === 1) {
    await summaryShareUnTop({ summaryShareId: row.summaryShareId || row.id })
    ElMessage.success('已取消置顶')
  } else {
    await summaryShareTop({ summaryShareId: row.summaryShareId || row.id })
    ElMessage.success('已置顶')
  }
  load()
}

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

load()
</script>

<style scoped lang="scss">
.summary-share-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;
  }

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

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

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

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

  .author-row {
    display: flex;
    align-items: center;
    gap: 8px;
  }

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

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

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

  .share-content {
    margin-top: 16px;
    padding: 0;
    color: #374151;
  }

  .share-footer {
    margin-top: 16px;
    display: flex;
    gap: 16px;
    color: #6b7280;
    font-size: 13px;
  }
}
</style>

