<template>
  <a-modal :visible="visible" title="工单详情" width="900px" :footer="false" @cancel="handleCancel" @update:visible="handleVisibleChange">
    <a-spin :loading="loading" style="width: 100%">
      <div v-if="ticketDetail" class="ticket-detail">
        <!-- 工单基本信息 -->
        <a-descriptions title="基本信息" :column="2" bordered>
          <a-descriptions-item label="工单编号">
            {{ ticketDetail.ticket_no }}
          </a-descriptions-item>
          <a-descriptions-item label="工单状态">
            <a-tag :color="getStatusColor(ticketDetail.status)">
              {{ getStatusText(ticketDetail.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="工单标题" :span="2">
            {{ ticketDetail.title }}
          </a-descriptions-item>
          <a-descriptions-item label="工单类型">
            <a-tag color="blue">
              {{ getTypeText(ticketDetail.type) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="优先级">
            <a-tag :color="getPriorityColor(ticketDetail.priority)">
              {{ getPriorityText(ticketDetail.priority) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="创建人">
            {{ ticketDetail.creator_name }}
          </a-descriptions-item>
          <a-descriptions-item label="处理人">
            {{ ticketDetail.assignee_name || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="分类">
            {{ ticketDetail.category_name || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formatDateTime(ticketDetail.created_at) }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ formatDateTime(ticketDetail.updated_at) }}
          </a-descriptions-item>
          <a-descriptions-item label="Incident ID">
            {{ ticketDetail.incident_id || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="资源 UID">
            {{ ticketDetail.resource_uid || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="资源分类">
            {{ ticketDetail.resource_category || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="业务系统 ID">
            {{ ticketDetail.business_system_id || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="知识条目 ID">
            {{ ticketDetail.knowledge_id || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="SLA 状态">
            <a-tag :color="ticketDetail.sla_violated ? 'red' : 'green'">
              {{ ticketDetail.sla_violated ? '已违规' : '正常' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="响应截止">
            <span :class="{ overdue: isDeadlineBreached(ticketDetail.response_deadline, ticketDetail.accepted_at) }">
              {{ formatDateTime(ticketDetail.response_deadline) }}
            </span>
          </a-descriptions-item>
          <a-descriptions-item label="解决截止">
            <span :class="{ overdue: isDeadlineBreached(ticketDetail.resolve_deadline, ticketDetail.resolved_at) }">
              {{ formatDateTime(ticketDetail.resolve_deadline) }}
            </span>
          </a-descriptions-item>
        </a-descriptions>

        <!-- 工单描述 -->
        <div class="section">
          <h3>工单描述</h3>
          <div class="description">
            {{ ticketDetail.description || '暂无描述' }}
          </div>
        </div>

        <!-- 关联知识 -->
        <div class="section">
          <h3>关联知识</h3>
          <a-table row-key="id" :data="knowledgeRelations" :pagination="false" size="small">
            <template #columns>
              <a-table-column title="类型" data-index="knowledge_type" :width="90" />
              <a-table-column title="标题" data-index="knowledge_title" />
              <a-table-column title="关系" data-index="relation_type" :width="110" />
              <a-table-column title="来源" data-index="source" :width="100" />
              <a-table-column title="分数" data-index="score" :width="80" />
            </template>
          </a-table>
        </div>

        <!-- 评论列表 -->
        <div class="section">
          <h3>评论列表</h3>
          <div class="comments">
            <a-empty v-if="!comments || comments.length === 0" description="暂无评论" />
            <div v-else class="comment-list">
              <div v-for="comment in comments" :key="comment.id" class="comment-item">
                <div class="comment-header">
                  <span class="comment-operator">{{ comment.operator_name }}</span>
                  <span class="comment-time">{{ formatDateTime(comment.created_at) }}</span>
                </div>
                <div class="comment-content">{{ comment.content }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 添加评论 -->
        <div class="section">
          <h3>添加评论</h3>
          <a-textarea
            v-model="commentContent"
            placeholder="请输入评论内容"
            :auto-size="{ minRows: 3, maxRows: 5 }"
            :max-length="500"
            show-word-limit
          />
          <div class="comment-actions">
            <a-button type="primary" :loading="submitting" @click="handleSubmitComment">提交评论</a-button>
          </div>
        </div>

        <!-- 操作日志 -->
        <div class="section">
          <h3>操作日志</h3>
          <a-timeline>
            <a-timeline-item v-for="log in logs" :key="log.id">
              <template #dot>
                <a-badge :status="getLogStatus(log.action)" />
              </template>
              <div class="log-content">
                <div class="log-header">
                  <span class="log-action">{{ getActionText(log.action) }}</span>
                  <span class="log-operator">{{ log.operator_name }}</span>
                  <span class="log-time">{{ formatDateTime(log.created_at) }}</span>
                </div>
                <div class="log-detail">{{ log.content }}</div>
              </div>
            </a-timeline-item>
            <a-timeline-item v-if="!logs || logs.length === 0">暂无操作日志</a-timeline-item>
          </a-timeline>
        </div>
      </div>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { fetchFeedbackTicketDetail, commentFeedbackTicket, fetchFeedbackTicketLogs } from '@/api/ops/feedbackTicket'
import { fetchTicketKnowledge, type IncidentKnowledgeRelation } from '@/api/kb/knowledge'

interface Props {
  visible: boolean
  ticketId: number
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 状态管理
const loading = ref(false)
const submitting = ref(false)
const ticketDetail = ref<any>(null)
const comments = ref<any[]>([])
const logs = ref<any[]>([])
const knowledgeRelations = ref<IncidentKnowledgeRelation[]>([])
const commentContent = ref('')

// 监听对话框显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal && props.ticketId) {
      fetchTicketDetail()
      fetchTicketLogs()
      fetchKnowledgeRelations()
    } else {
      // 关闭时清空数据
      ticketDetail.value = null
      comments.value = []
      logs.value = []
      knowledgeRelations.value = []
      commentContent.value = ''
    }
  }
)

// 获取工单详情
const fetchTicketDetail = async () => {
  loading.value = true
  try {
    const res = await fetchFeedbackTicketDetail(props.ticketId)
    if (res.code === 0) {
      ticketDetail.value = res.details
    } else {
      Message.error(res.message || '获取工单详情失败')
    }
  } catch (error) {
    Message.error('获取工单详情失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const fetchKnowledgeRelations = async () => {
  try {
    const res: any = await fetchTicketKnowledge(props.ticketId)
    knowledgeRelations.value = res.details || []
  } catch (error) {
    console.error('获取关联知识失败', error)
  }
}

// 获取操作日志
const fetchTicketLogs = async () => {
  try {
    const res = await fetchFeedbackTicketLogs(props.ticketId)
    if (res.code === 0) {
      logs.value = res.details || []
      // 提取评论
      comments.value = logs.value.filter((log: any) => log.action === 'comment')
    }
  } catch (error) {
    console.error('获取操作日志失败', error)
  }
}

// 提交评论
const handleSubmitComment = async () => {
  if (!commentContent.value.trim()) {
    Message.warning('请输入评论内容')
    return
  }

  submitting.value = true
  try {
    const res = await commentFeedbackTicket(props.ticketId, {
      content: commentContent.value,
    })
    if (res.code === 0) {
      Message.success('评论成功')
      commentContent.value = ''
      // 刷新日志和评论
      await fetchTicketLogs()
    } else {
      Message.error(res.message || '评论失败')
    }
  } catch (error) {
    Message.error('评论失败')
    console.error(error)
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const handleCancel = () => {
  emit('update:visible', false)
  emit('refresh')
}

// 处理对话框可见性变化
const handleVisibleChange = (visible: boolean) => {
  emit('update:visible', visible)
}

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    pending: 'blue',
    accepted: 'green',
    processing: 'cyan',
    suspended: 'orange',
    resolved: 'purple',
    closed: 'gray',
    cancelled: 'red',
  }
  return colorMap[status] || 'gray'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待接单',
    accepted: '已接单',
    processing: '处理中',
    suspended: '已挂起',
    resolved: '已解决',
    closed: '已关闭',
    cancelled: '已撤回',
  }
  return textMap[status] || status
}

// 获取优先级颜色
const getPriorityColor = (priority: string) => {
  const colorMap: Record<string, string> = {
    low: 'gray',
    medium: 'blue',
    high: 'orange',
    critical: 'red',
    urgent: 'red',
  }
  return colorMap[priority] || 'gray'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const textMap: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高',
    critical: '紧急',
    urgent: '紧急',
  }
  return textMap[priority] || priority
}

// 获取类型文本
const getTypeText = (type: string) => {
  const textMap: Record<string, string> = {
    incident: '故障',
    request: '请求',
    change: '变更',
    problem: '问题',
    consultation: '咨询',
    question: '问题',
    other: '其他',
  }
  return textMap[type] || type
}

// 获取操作文本
const getActionText = (action: string) => {
  const textMap: Record<string, string> = {
    create: '创建',
    accept: '接单',
    transfer: '转交',
    suspend: '挂起',
    resume: '重启',
    resolve: '解决',
    close: '关闭',
    cancel: '撤回',
    comment: '评论',
    update: '更新',
  }
  return textMap[action] || action
}

// 获取日志状态
const getLogStatus = (action: string) => {
  const statusMap: Record<string, string> = {
    create: 'processing',
    accept: 'success',
    transfer: 'warning',
    suspend: 'warning',
    resume: 'processing',
    resolve: 'success',
    close: 'default',
    cancel: 'error',
    comment: 'default',
    update: 'processing',
  }
  return statusMap[action] || 'default'
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

const isDeadlineBreached = (deadline?: string, finishedAt?: string) => {
  if (!deadline) return false
  const deadlineMs = new Date(deadline).getTime()
  if (Number.isNaN(deadlineMs)) return false
  const compareMs = finishedAt ? new Date(finishedAt).getTime() : Date.now()
  return compareMs > deadlineMs
}
</script>

<script lang="ts">
export default {
  name: 'TicketDetailDialog',
}
</script>

<style scoped lang="less">
.ticket-detail {
  overflow-y: auto;
}

.section {
  margin-top: 24px;

  h3 {
    margin-bottom: 12px;
    font-size: 16px;
    font-weight: 600;
  }
}

.description {
  padding: 12px;
  background-color: var(--color-fill-2);
  border-radius: 4px;
  line-height: 1.6;
}

.comment-list {
  .comment-item {
    padding: 12px;
    margin-bottom: 12px;
    background-color: var(--color-fill-2);
    border-radius: 4px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .comment-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 12px;
    color: var(--color-text-3);

    .comment-operator {
      font-weight: 600;
    }
  }

  .comment-content {
    line-height: 1.6;
  }
}

.comment-actions {
  margin-top: 12px;
  text-align: right;
}

.log-content {
  .log-header {
    display: flex;
    gap: 12px;
    margin-bottom: 4px;
    font-size: 12px;
    color: var(--color-text-3);

    .log-action {
      font-weight: 600;
    }
  }

  .log-detail {
    color: var(--color-text-2);
  }
}

.overdue {
  color: rgb(var(--red-6));
  font-weight: 600;
}
</style>
