<template>
  <div class="task-detail-page frame-body adaption-frame-body">
    <div class="task-detail-card">
      <div class="task-detail-header">
        <div class="task-detail-header-left">
          <el-button text @click="goBack">返回</el-button>
          <div>
            <div class="task-detail-title">{{ detail.title || detail.name || '任务详情' }}</div>
            <div class="task-detail-subtitle">任务ID: {{ taskIdInput || '-' }}</div>
          </div>
        </div>
        <div class="task-detail-header-right">
          <el-input v-model="taskIdInput" placeholder="任务ID" style="width: 160px" />
          <el-button type="primary" :loading="loading" @click="load">刷新</el-button>
        </div>
      </div>

      <div class="task-detail-content" v-loading="loading">
        <div class="task-detail-main">
          <div class="panel hero-panel">
            <div class="hero-top">
              <div class="hero-status">
                <span class="status-chip">{{ detail.statusLabel || formatStatus(detail.status) }}</span>
                <span class="progress-text">进度 {{ formatPercent(detail.percent || detail.progress) }}</span>
              </div>
              <el-progress :percentage="toNumber(detail.percent || detail.progress)" :stroke-width="14" color="#2d8cf0" />
            </div>
            <div class="hero-grid">
              <div class="hero-item">
                <span class="hero-label">执行人</span>
                <span class="hero-value">{{ detail.leaderName || detail.executeName || detail.ownerName || '-' }}</span>
              </div>
              <div class="hero-item">
                <span class="hero-label">创建人</span>
                <span class="hero-value">{{ detail.createName || detail.fromName || '-' }}</span>
              </div>
              <div class="hero-item">
                <span class="hero-label">开始时间</span>
                <span class="hero-value">{{ detail.startTime || detail.startDate || '-' }}</span>
              </div>
              <div class="hero-item">
                <span class="hero-label">结束时间</span>
                <span class="hero-value">{{ detail.endTime || detail.endDate || '-' }}</span>
              </div>
            </div>
          </div>

          <div class="panel">
            <div class="panel-title">任务说明</div>
            <div class="rich-content" v-html="detail.content || '<p>-</p>'"></div>
          </div>

          <div class="panel">
            <div class="panel-title">参与人</div>
            <div v-if="participantUsers.length" class="user-list">
              <div v-for="(user, idx) in participantUsers" :key="idx" class="user-chip">
                <el-avatar :size="28">{{ getAvatarText(user.staffName || user.realName || user.name) }}</el-avatar>
                <span>{{ user.staffName || user.realName || user.name || '-' }}</span>
              </div>
            </div>
            <el-empty v-else description="暂无参与人" />
          </div>
        </div>

        <div class="task-detail-side">
          <div class="panel">
            <div class="panel-title">基础信息</div>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="任务标题">{{ detail.title || detail.name || '-' }}</el-descriptions-item>
              <el-descriptions-item label="优先级">{{ formatPriority(detail.priorityType) }}</el-descriptions-item>
              <el-descriptions-item label="任务日期">{{ detail.dateName || detail.deadline || '-' }}</el-descriptions-item>
              <el-descriptions-item label="提醒">{{ formatRemind(detail.remindType) }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="panel">
            <div class="panel-title">附件</div>
            <el-empty v-if="!resources.length" description="暂无附件" />
            <div v-else class="resource-list">
              <div v-for="(item, idx) in resources" :key="idx" class="resource-item">
                <div class="resource-name">{{ item.fileName || item.resourceName || '-' }}</div>
                <div class="resource-meta">{{ item.fileSize || item.resourceSize || '-' }} · {{ item.createTime || '-' }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="task-detail-tabs">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="评论" name="comment">
            <div class="comment-editor">
              <Editor v-model="commentContent" :min-height="120" />
              <div class="comment-actions">
                <el-button type="primary" :loading="commentSubmitting" @click="submitComment">发表评论</el-button>
              </div>
            </div>
            <el-empty v-if="!comments.length" description="暂无评论" />
            <div v-else class="comment-list">
              <el-card v-for="(item, idx) in comments" :key="`c-${idx}`" class="comment-item" shadow="never">
                <div class="comment-meta">
                  <div class="comment-author">
                    <el-avatar :size="28">{{ getAvatarText(item.staffName) }}</el-avatar>
                    <span>{{ item.staffName || '匿名' }}</span>
                  </div>
                  <span>{{ item.createTime || '-' }}</span>
                </div>
                <div class="comment-content" v-html="item.content || '-'"></div>
              </el-card>
            </div>
          </el-tab-pane>

          <el-tab-pane label="日志记录" name="log">
            <el-timeline>
              <el-timeline-item v-for="(item, idx) in logs" :key="`l-${idx}`" :timestamp="item.createTime || '-'">
                <div>{{ item.content || '-' }}</div>
              </el-timeline-item>
            </el-timeline>
            <el-empty v-if="!logs.length" description="暂无日志" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Editor from '@/components/Editor/index.vue'
import { taskCommentAdd, taskCommentList, taskGet, taskLogList, taskResourceList } from '@/api/otr/task/core'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const taskIdInput = ref(String(route.query.id || '1'))
const detail = reactive<Record<string, any>>({})
const activeTab = ref('comment')
const logs = ref<any[]>([])
const comments = ref<any[]>([])
const resources = ref<any[]>([])
const commentContent = ref('')
const commentSubmitting = ref(false)

const participantUsers = computed(() => {
  const list = detail.participants || detail.participantList || []
  return Array.isArray(list) ? list : []
})

async function load() {
  loading.value = true
  try {
    const id = taskIdInput.value || '1'
    const [res, logRes, commentRes, resourceRes]: any = await Promise.all([
      taskGet(id),
      taskLogList({ taskId: id, taskDateId: id, page: 1, psize: 20, pageSize: 20 }),
      taskCommentList({ taskId: id, taskDateId: id, page: 1, pageSize: 20 }),
      taskResourceList({ taskId: id, taskDateId: id }),
    ])
    Object.keys(detail).forEach((key) => delete detail[key])
    Object.assign(detail, res?.result || {})
    logs.value = logRes?.result?.records || []
    comments.value = commentRes?.result?.records || []
    resources.value = resourceRes?.result?.records || []
  } finally {
    loading.value = false
  }
}

async function submitComment() {
  if (!commentContent.value.replace(/<[^>]+>/g, '').trim()) {
    ElMessage.warning('请先输入评论内容')
    return
  }
  commentSubmitting.value = true
  try {
    await taskCommentAdd({
      taskId: taskIdInput.value || '1',
      taskDateId: taskIdInput.value || '1',
      content: commentContent.value,
    })
    ElMessage.success('评论已提交')
    commentContent.value = ''
    const commentRes: any = await taskCommentList({ taskId: taskIdInput.value || '1', taskDateId: taskIdInput.value || '1', page: 1, pageSize: 20 })
    comments.value = commentRes?.result?.records || []
  } finally {
    commentSubmitting.value = false
  }
}

function goBack() {
  router.back()
}

function toNumber(value: any) {
  const raw = String(value ?? '0').replace('%', '')
  const num = Number(raw)
  return Number.isNaN(num) ? 0 : Math.max(0, Math.min(100, num))
}

function formatPercent(value: any) {
  return `${toNumber(value)}%`
}

function formatStatus(status: any) {
  switch (Number(status)) {
    case 1:
      return '未开始'
    case 2:
      return '进行中'
    case 3:
    case 4:
      return '已完成'
    case 5:
      return '已逾期'
    default:
      return '-'
  }
}

function formatPriority(value: any) {
  switch (Number(value)) {
    case 1:
      return '重要紧急'
    case 2:
      return '重要不紧急'
    case 3:
      return '不重要紧急'
    case 4:
      return '不重要不紧急'
    default:
      return '-'
  }
}

function formatRemind(value: any) {
  const num = Number(value)
  if (num === -1 || Number.isNaN(num)) return '不提醒'
  if (num === 5) return '开始前5分钟'
  if (num === 30) return '开始前30分钟'
  if (num === 60) return '开始前1小时'
  if (num === 1440) return '开始前1天'
  return `${value}`
}

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

onMounted(load)
</script>

<style scoped lang="scss">
.task-detail-page {
  .task-detail-card {
    background: #fff;
    border-radius: 10px;
    padding: 24px;
  }

  .task-detail-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    padding-bottom: 20px;
    margin-bottom: 20px;
    border-bottom: 1px solid #eef2f6;
  }

  .task-detail-header-left {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .task-detail-header-right {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .task-detail-title {
    font-size: 22px;
    font-weight: 600;
    color: #111827;
  }

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

  .task-detail-content {
    display: grid;
    grid-template-columns: minmax(0, 2fr) minmax(300px, 1fr);
    gap: 20px;
  }

  .panel {
    padding: 20px;
    border: 1px solid #e5e7eb;
    border-radius: 10px;
    background: #fff;
  }

  .hero-panel {
    background: linear-gradient(135deg, #f8fbff 0%, #eef6ff 100%);
  }

  .hero-top {
    margin-bottom: 18px;
  }

  .hero-status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
  }

  .status-chip {
    display: inline-flex;
    align-items: center;
    height: 28px;
    padding: 0 12px;
    color: #2563eb;
    background: rgba(37, 99, 235, 0.1);
    border-radius: 999px;
    font-size: 13px;
    font-weight: 600;
  }

  .progress-text {
    color: #4b5563;
    font-size: 13px;
  }

  .hero-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 14px 18px;
  }

  .hero-item {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .hero-label {
    color: #6b7280;
    font-size: 12px;
  }

  .hero-value {
    color: #111827;
    font-size: 14px;
    font-weight: 500;
  }

  .panel-title {
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: 600;
    color: #111827;
  }

  .rich-content {
    min-height: 160px;
    color: #374151;
    line-height: 1.8;
  }

  .user-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
  }

  .user-chip {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    border-radius: 999px;
    background: #f3f4f6;
    color: #374151;
  }

  .resource-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .resource-item {
    padding: 12px 14px;
    border-radius: 8px;
    background: #f8fafc;
    border: 1px solid #edf2f7;
  }

  .resource-name {
    color: #111827;
    font-weight: 500;
  }

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

  .task-detail-tabs {
    margin-top: 20px;
  }

  .comment-editor {
    margin-bottom: 18px;
  }

  .comment-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
  }

  .comment-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .comment-item {
    border-radius: 10px;
  }

  .comment-meta {
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #6b7280;
    font-size: 12px;
  }

  .comment-author {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: #111827;
    font-size: 13px;
    font-weight: 500;
  }

  .comment-content {
    margin-top: 12px;
    color: #374151;
    line-height: 1.8;
  }

  @media (max-width: 1100px) {
    .task-detail-header {
      flex-direction: column;
      align-items: flex-start;
    }

    .task-detail-header-right {
      width: 100%;
    }

    .task-detail-content {
      grid-template-columns: 1fr;
    }

    .hero-grid {
      grid-template-columns: 1fr;
    }
  }
}
</style>

