<template>
  <el-card shadow="never" class="info-card recent-card">
    <div class="card-header">
      <span>事件 / 任务</span>
    </div>
    <div class="filter-bar">
      <el-date-picker
        v-model="selectedRange"
        type="datetimerange"
        format="yyyy-MM-dd HH:mm"
        value-format="yyyy-MM-dd HH:mm:ss"
        size="small"
        start-placeholder="开始"
        end-placeholder="结束"
        :clearable="false"
        :editable="false"
        :shortcuts="rangeShortcuts"
        @change="loadTimelineItems"
        class="range-picker"
      />
    </div>
    <div class="recent-timeline-box">
      <el-empty v-if="!hasItems && !loading" description="暂无事件或任务" class="empty-state" />
      <div v-else class="timeline-sections">
        <!-- 重点事件 -->
        <div v-if="groupedImportantEvents.length" class="timeline-section">
          <div class="section-header">
            <span>重点事件</span>
            <el-tag type="danger" size="mini">{{ groupedImportantEvents.length }}</el-tag>
          </div>
          <el-timeline class="recent-timeline">
            <el-timeline-item
              v-for="event in groupedImportantEvents"
              :key="event.id"
              placement="top"
              color="#F56C6C"
            >
              <div class="timeline-item important">
                <div class="title">
                  <span>{{ event.title }}</span>
                  <div class="title-tags">
                    <el-tag type="danger" size="mini">重点</el-tag>
                    <el-tag size="mini" :type="event.statusTag">{{ event.statusLabel }}</el-tag>
                  </div>
                </div>
                <div class="meta">
                  <span>{{ event.time }}</span>
                  <div class="action-buttons">
                    <el-button 
                      type="text" 
                      size="mini"
                      @click.stop="showEventMenu($event, event)"
                    >
                      更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <EventActionMenu
                      v-if="eventMenuVisible && eventMenuEvent && eventMenuEvent.id === event.id"
                      :position="eventMenuPosition"
                      :event="eventMenuEvent"
                      @action="handleEventMenuAction"
                      @close="hideEventMenu"
                    />
                  </div>
                </div>
              </div>
              <!-- Tasks under this event -->
              <div v-if="event.tasks && event.tasks.length > 0" class="event-tasks">
                <div
                  v-for="task in event.tasks"
                  :key="task.id"
                  class="task-item"
                >
                  <div class="task-title">
                    <span>{{ task.title }}</span>
                    <div class="task-tags">
                      <el-tag size="mini" type="info">任务</el-tag>
                      <el-tag size="mini" :type="task.statusTag">{{ task.statusLabel }}</el-tag>
                    </div>
                  </div>
                  <div class="meta">
                    <span>{{ task.time }}</span>
                    <div class="action-buttons">
                      <el-button 
                        type="text" 
                        size="mini"
                        @click.stop="showTaskMenu($event, task)"
                      >
                        更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                      </el-button>
                      <TaskActionMenu
                        v-if="taskMenuVisible && taskMenuTask && taskMenuTask.entityId === task.entityId"
                        :position="taskMenuPosition"
                        :task="taskMenuTask"
                        @action="handleTaskMenuAction"
                        @close="hideTaskMenu"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>

        <!-- 普通事件 -->
        <div v-if="groupedNormalEvents.length" class="timeline-section">
          <div class="section-header">
            <span>普通事件</span>
            <el-tag type="info" size="mini">{{ groupedNormalEvents.length }}</el-tag>
          </div>
          <el-timeline class="recent-timeline">
            <el-timeline-item
              v-for="event in groupedNormalEvents"
              :key="event.id"
              placement="top"
              color="#409EFF"
            >
              <div class="timeline-item">
                <div class="title">
                  <span>{{ event.title }}</span>
                  <el-tag size="mini" :type="event.statusTag">{{ event.statusLabel }}</el-tag>
                </div>
                <div class="meta">
                  <span>{{ event.time }}</span>
                  <div class="action-buttons">
                    <el-button 
                      type="text" 
                      size="mini"
                      @click.stop="showEventMenu($event, event)"
                    >
                      更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <EventActionMenu
                      v-if="eventMenuVisible && eventMenuEvent && eventMenuEvent.id === event.id"
                      :position="eventMenuPosition"
                      :event="eventMenuEvent"
                      @action="handleEventMenuAction"
                      @close="hideEventMenu"
                    />
                  </div>
                </div>
              </div>
              <!-- Tasks under this event -->
              <div v-if="event.tasks && event.tasks.length > 0" class="event-tasks">
                <div
                  v-for="task in event.tasks"
                  :key="task.id"
                  class="task-item"
                >
                  <div class="task-title">
                    <span>{{ task.title }}</span>
                    <div class="task-tags">
                      <el-tag size="mini" type="info">任务</el-tag>
                      <el-tag size="mini" :type="task.statusTag">{{ task.statusLabel }}</el-tag>
                    </div>
                  </div>
                  <div class="meta">
                    <span>{{ task.time }}</span>
                    <div class="action-buttons">
                      <el-button 
                        type="text" 
                        size="mini"
                        @click.stop="showTaskMenu($event, task)"
                      >
                        更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                      </el-button>
                      <TaskActionMenu
                        v-if="taskMenuVisible && taskMenuTask && taskMenuTask.entityId === task.entityId"
                        :position="taskMenuPosition"
                        :task="taskMenuTask"
                        @action="handleTaskMenuAction"
                        @close="hideTaskMenu"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>

        <!-- 独立任务 (tasks without eventId) 暂不使用 -->
        <!-- <div v-if="orphanedTasks.length" class="timeline-section">
          <div class="section-header">
            <span>独立任务</span>
            <el-tag type="warning" size="mini">{{ orphanedTasks.length }}</el-tag>
          </div>
          <el-timeline class="recent-timeline">
            <el-timeline-item
              v-for="task in orphanedTasks"
              :key="task.id"
              placement="top"
              color="#E6A23C"
            >
              <div class="timeline-item">
                <div class="title">
                  <span>{{ task.title }}</span>
                  <div class="task-tags">
                    <el-tag size="mini" type="info">任务</el-tag>
                    <el-tag size="mini" :type="task.statusTag">{{ task.statusLabel }}</el-tag>
                  </div>
                </div>
                <div class="meta">
                  <span>{{ task.time }}</span>
                  <div class="action-buttons">
                    <el-button 
                      type="text" 
                      size="mini"
                      @click.stop="showTaskMenu($event, task)"
                    >
                      更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <TaskActionMenu
                      v-if="taskMenuVisible && taskMenuTask && taskMenuTask.entityId === task.entityId"
                      :position="taskMenuPosition"
                      :task="taskMenuTask"
                      @action="handleTaskMenuAction"
                      @close="hideTaskMenu"
                    />
                  </div>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div> -->
      </div>
    </div>
  </el-card>
</template>

<script>
import { listDispatchTasks, publishDispatchTask, markDispatchTaskInProgress, closeDispatchTask, abortDispatchTask, removeDispatchTasks } from '@/api/emergency/dispatchTask'
import { listEvents, pinEvent, unpinEvent } from '@/api/emergency/event'
import { formatDateTime, getTodayDateRange } from '@/views/duty/alert/utils/dateHelpers'
import TaskActionMenu from './TaskActionMenu.vue'
import EventActionMenu from './EventActionMenu.vue'

export default {
  name: 'DispatchTimelineCard',
  components: {
    TaskActionMenu,
    EventActionMenu
  },
  props: {
    highlightMarkerId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      events: [],
      tasks: [],
      selectedRange: [],
      highlightedItemId: null,
      taskMenuVisible: false,
      taskMenuPosition: { left: 0, top: 0 },
      taskMenuTask: null,
      eventMenuVisible: false,
      eventMenuPosition: { left: 0, top: 0 },
      eventMenuEvent: null,
      rangeShortcuts: [
        {
          text: '今天',
          onClick: (picker) => {
            const { startOfDay, endOfDay } = getTodayDateRange()
            picker.$emit('pick', [startOfDay, endOfDay])
          }
        },
        {
          text: '最近24小时',
          onClick: (picker) => {
            const end = new Date()
            const start = new Date(end.getTime() - 24 * 3600 * 1000)
            picker.$emit('pick', [start, end])
          }
        }
      ]
    }
  },
  computed: {
    // Group tasks by eventId
    tasksByEventId() {
      const map = new Map()
      this.tasks.forEach(task => {
        if (task.eventId) {
          const eventId = task.eventId
          if (!map.has(eventId)) {
            map.set(eventId, [])
          }
          map.get(eventId).push(task)
        }
      })
      // Sort tasks within each event by time
      map.forEach((tasks, eventId) => {
        tasks.sort((a, b) => new Date(b.rawTime).getTime() - new Date(a.rawTime).getTime())
      })
      return map
    },
    // Events with their tasks attached
    groupedImportantEvents() {
      return this.events
        .filter(event => event.importantFlag === 1)
        .map(event => ({
          ...event,
          tasks: this.tasksByEventId.get(event.entityId) || []
        }))
        .sort((a, b) => new Date(b.rawTime).getTime() - new Date(a.rawTime).getTime())
    },
    groupedNormalEvents() {
      return this.events
        .filter(event => event.importantFlag !== 1)
        .map(event => ({
          ...event,
          tasks: this.tasksByEventId.get(event.entityId) || []
        }))
        .sort((a, b) => new Date(b.rawTime).getTime() - new Date(a.rawTime).getTime())
    },
    // Tasks without eventId (orphaned)
    orphanedTasks() {
      return this.tasks
        .filter(task => !task.eventId)
        .sort((a, b) => new Date(b.rawTime).getTime() - new Date(a.rawTime).getTime())
    },
    hasItems() {
      return this.groupedImportantEvents.length > 0 || 
             this.groupedNormalEvents.length > 0 || 
             this.orphanedTasks.length > 0
    },
    // For backward compatibility with syncHighlightedItem
    timelineItems() {
      return [...this.events, ...this.tasks]
    }
  },
  watch: {
    highlightMarkerId: {
      immediate: true,
      handler(newVal) {
        this.syncHighlightedItem(newVal)
      }
    }
  },
  mounted() {
    const { startOfDay, endOfDay } = getTodayDateRange()
    this.selectedRange = [startOfDay, endOfDay]
    this.loadTimelineItems()
  },
  methods: {
    reload() {
      this.loadTimelineItems()
    },
    async loadTimelineItems() {
      this.loading = true
      try {
        const [start, end] = this.selectedRange || []
        const startTime = start ? new Date(start) : getTodayDateRange().startOfDay
        const endTime = end ? new Date(end) : getTodayDateRange().endOfDay
        const [events, tasks] = await Promise.all([
          this.fetchEvents(startTime, endTime),
          this.fetchTasks()
        ])
        this.events = events
        this.tasks = tasks
        this.syncHighlightedItem(this.highlightMarkerId)
      } catch (error) {
        console.error('加载事件/任务时间线失败:', error)
        this.events = []
        this.tasks = []
      } finally {
        this.loading = false
      }
    },
    async fetchEvents(startOfDay, endOfDay) {
      // Fetch events within the selected date range
      const rangeRes = await listEvents({
        pageNum: 1,
        pageSize: 50,
        beginOccurredAt: formatDateTime(startOfDay),
        endOccurredAt: formatDateTime(endOfDay),
        excludeStatuses: ['completed', 'archived'] // 排除已完成和归档的事件
      })
      
      // Fetch all active events (not completed/archived) that occurred before the range start
      const activeRes = await listEvents({
        pageNum: 1,
        pageSize: 50,
        endOccurredAt: formatDateTime(startOfDay), // Only events that occurred before start of range
        excludeStatuses: ['completed', 'archived'] // 排除已完成和归档的事件
      }).catch(() => ({ code: 200, rows: [] }))
      
      // Collect all events from range query
      const rangeEvents = rangeRes && rangeRes.code === 200 && Array.isArray(rangeRes.rows) 
        ? rangeRes.rows 
        : []
      
      // Collect all active events (already filtered by backend to occur before startOfDay)
      const activeEvents = activeRes && activeRes.code === 200 && Array.isArray(activeRes.rows)
        ? activeRes.rows
        : []
      
      // Merge and deduplicate by event ID
      const allEventsMap = new Map()
      
      // Add range events
      rangeEvents.forEach(event => {
        allEventsMap.set(event.id, event)
      })
      
      // Add active events (will overwrite if duplicate, but that's fine)
      activeEvents.forEach(event => {
        allEventsMap.set(event.id, event)
      })
      
      // Convert to array and map to timeline items
      return Array.from(allEventsMap.values()).map((event) => {
        const rawTime = event.occurredAt || event.updateTime || event.createTime
        return {
          id: `event-${event.id}`,
          type: 'event',
          title: event.title || event.eventNo || '未命名事件',
          summary: event.summary || '暂无摘要',
          time: formatDateTime(rawTime),
          rawTime,
          related: event.eventNo ? `事件 ${event.eventNo}` : null,
          statusLabel: this.getEventStatusLabel(event.status),
          statusTag: this.getEventStatusTag(event.status),
          entityId: event.id,
          markerId: `event-${event.id}`,
          importantFlag: event.importantFlag,
          // Preserve original fields for copyEventInfo
          eventNo: event.eventNo,
          status: event.status,
          location: event.location,
          address: event.address,
          occurredAt: event.occurredAt,
          createTime: event.createTime
        }
      })
    },
    async fetchTasks() {
      const res = await listDispatchTasks({
        pageNum: 1,
        pageSize: 50
      })
      if (res && res.code === 200 && Array.isArray(res.rows)) {
        return res.rows.map((task) => {
          const rawTime = task.updateTime || task.createTime
          return {
            id: `task-${task.id}`,
            type: 'task',
            title: task.name || task.taskNo || '未命名任务',
            summary: task.description || '暂无描述',
            time: formatDateTime(rawTime),
            rawTime,
            related: task.eventId ? `事件 ${task.eventId}` : null,
            status: task.status,
            statusLabel: this.getTaskStatusLabel(task.status),
            statusTag: this.getTaskStatusTag(task.status),
            entityId: task.id,
            markerId: task.eventId ? `event-${task.eventId}` : null,
            eventId: task.eventId
          }
        })
      }
      return []
    },
    getEventStatusLabel(status) {
      switch (status) {
        case 'draft':
          return '草稿'
        case 'pending':
          return '待处理'
        case 'processing':
          return '处理中'
        case 'completed':
          return '已完成'
        default:
          return '未知'
      }
    },
    getEventStatusTag(status) {
      switch (status) {
        case 'draft':
          return 'info'
        case 'pending':
          return 'warning'
        case 'processing':
          return 'success'
        case 'completed':
          return 'default'
        default:
          return 'info'
      }
    },
    getTaskStatusLabel(status) {
      switch (status) {
        case 'draft':
          return '草稿'
        case 'published':
          return '已下达'
        case 'in_progress':
          return '执行中'
        case 'closed':
          return '已关闭'
        case 'cancelled':
          return '已取消'
        default:
          return '未知'
      }
    },
    getTaskStatusTag(status) {
      switch (status) {
        case 'draft':
          return 'info'
        case 'published':
          return 'warning'
        case 'in_progress':
          return 'success'
        case 'closed':
          return 'default'
        case 'cancelled':
          return 'danger'
        default:
          return 'info'
      }
    },
    viewItem(item) {
      this.highlightedItemId = item.id
      this.$emit('view-item', item)
    },
    locateItem(item) {
      // Center and zoom to the marker without toggling highlight
      this.highlightedItemId = item.id
      this.$emit('view-item', item)
    },
    openDetail(item) {
      if (item.type === 'task') {
        // Emit task-detail event for tasks
        this.$emit('view-task-detail', item)
      } else {
        // Emit view-detail event for events
        this.$emit('view-detail', item)
      }
    },
    clearHighlight(item) {
      this.highlightedItemId = null
      this.$emit('clear-highlight', item)
    },
    syncHighlightedItem(markerId) {
      if (!markerId) {
        this.highlightedItemId = null
        return
      }
      const matched = this.timelineItems.find(
        (item) => item.markerId === markerId || item.id === markerId
      )
      this.highlightedItemId = matched ? matched.id : null
    },
    async handleTaskAction(action, task) {
      if (!task || !task.entityId) {
        this.$message.error('任务信息不完整')
        return
      }

      try {
        let res
        switch (action) {
          case 'publish':
            res = await publishDispatchTask(task.entityId)
            if (res && res.code === 200) {
              this.$message.success('任务发布成功')
              this.reload()
              this.$emit('task-status-changed', { taskId: task.entityId, status: 'published' })
            } else {
              this.$message.error(res.msg || '发布失败')
            }
            break
          case 'start':
            res = await markDispatchTaskInProgress(task.entityId)
            if (res && res.code === 200) {
              this.$message.success('任务已开始执行')
              this.reload()
              this.$emit('task-status-changed', { taskId: task.entityId, status: 'in_progress' })
            } else {
              this.$message.error(res.msg || '操作失败')
            }
            break
          case 'close':
            this.$prompt('请输入关闭备注', '关闭任务', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputType: 'textarea',
              inputPlaceholder: '请输入关闭原因或备注'
            }).then(async ({ value }) => {
              res = await closeDispatchTask(task.entityId, { remark: value || '' })
              if (res && res.code === 200) {
                this.$message.success('任务已关闭')
                this.reload()
                this.$emit('task-status-changed', { taskId: task.entityId, status: 'closed' })
              } else {
                this.$message.error(res.msg || '关闭失败')
              }
            }).catch(() => {
              // User cancelled
            })
            break
          case 'delete':
            this.$confirm('确定要删除此任务吗？删除后无法恢复。', '删除任务', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async () => {
              res = await removeDispatchTasks([task.entityId])
              if (res && res.code === 200) {
                this.$message.success('任务已删除')
                this.reload()
                this.$emit('task-status-changed', { taskId: task.entityId, status: 'deleted' })
              } else {
                this.$message.error(res.msg || '删除失败')
              }
            }).catch(() => {
              // User cancelled
            })
            break
          case 'abort':
            this.$prompt('请输入取消原因', '取消任务', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputType: 'textarea',
              inputPlaceholder: '请输入取消原因'
            }).then(async ({ value }) => {
              res = await abortDispatchTask(task.entityId, { reason: value || '' })
              if (res && res.code === 200) {
                this.$message.success('任务已取消')
                this.reload()
                this.$emit('task-status-changed', { taskId: task.entityId, status: 'cancelled' })
              } else {
                this.$message.error(res.msg || '取消失败')
              }
            }).catch(() => {
              // User cancelled
            })
            break
          case 'detail':
            this.openDetail(task)
            break
          default:
            this.$message.warning('未知操作')
        }
      } catch (error) {
        console.error('任务操作失败:', error)
        this.$message.error('操作失败，请稍后重试')
      }
    },
    showTaskMenu(event, task) {
      // Hide any existing menu first
      if (this.taskMenuVisible) {
        this.hideTaskMenu()
      }
      
      const rect = event.currentTarget.getBoundingClientRect()
      this.taskMenuPosition = {
        left: rect.left,
        top: rect.bottom + 4
      }
      this.taskMenuTask = task
      this.taskMenuVisible = true
      
      // Delay adding the outside click listener to avoid immediate closure
      this.$nextTick(() => {
        setTimeout(() => {
          document.addEventListener('click', this.handleOutsideClick, true)
        }, 0)
      })
    },
    hideTaskMenu() {
      this.taskMenuVisible = false
      this.taskMenuTask = null
      document.removeEventListener('click', this.handleOutsideClick, true)
    },
    handleOutsideClick(event) {
      // Don't close if clicking on the button or menu itself
      const button = event.target.closest('.action-buttons')
      const menu = event.target.closest('.task-action-menu')
      
      if (!this.$el.contains(event.target) && !button && !menu) {
        this.hideTaskMenu()
      }
    },
    handleTaskMenuAction(command) {
      if (this.taskMenuTask) {
        this.handleTaskAction(command, this.taskMenuTask)
      }
      this.hideTaskMenu()
    },
    showEventMenu(domEvent, eventData) {
      // Prevent event propagation
      domEvent.stopPropagation()
      
      // Hide any existing menu first
      if (this.eventMenuVisible) {
        this.hideEventMenu()
      }
      
      // Save button reference before async operations
      const buttonElement = domEvent.currentTarget
      const rect = buttonElement.getBoundingClientRect()
      
      // 传递按钮的右下角坐标，菜单会将其右下角对齐到此位置
      this.eventMenuPosition = {
        left: rect.right,
        top: rect.bottom
      }
      this.eventMenuEvent = eventData
      this.eventMenuVisible = true
      
      // Delay adding the outside click listener to avoid immediate closure
      this.$nextTick(() => {
        setTimeout(() => {
          document.addEventListener('click', this.handleEventOutsideClick, true)
        }, 100)
      })
    },
    hideEventMenu() {
      this.eventMenuVisible = false
      this.eventMenuEvent = null
      document.removeEventListener('click', this.handleEventOutsideClick, true)
    },
    handleEventOutsideClick(event) {
      // Don't close if clicking on the button or menu itself
      const button = event.target.closest('.action-buttons')
      const menu = event.target.closest('.event-action-menu')
      
      if (!this.$el.contains(event.target) && !button && !menu) {
        this.hideEventMenu()
      }
    },
    handleEventMenuAction(action) {
      if (!this.eventMenuEvent) {
        this.hideEventMenu()
        return
      }
      
      const event = this.eventMenuEvent
      
      switch (action) {
        case 'view':
          this.openDetail(event)
          break
        case 'locate':
          this.locateItem(event)
          break
        case 'createTask':
          this.$emit('create-task', event)
          break
        case 'pin':
          this.toggleEventPin(event)
          break
        case 'copyInfo':
          this.copyEventInfo(event)
          break
        default:
          this.$message.warning('未知操作')
      }
      
      this.hideEventMenu()
    },
    async toggleEventPin(event) {
      try {
        const api = event.importantFlag === 1 ? unpinEvent : pinEvent
        const res = await api(event.entityId)
        if (res && res.code === 200) {
          event.importantFlag = event.importantFlag === 1 ? 0 : 1
          const message = event.importantFlag === 1 ? '已标记为重点事件' : '已取消重点事件'
          this.$message.success(message)
          this.reload()
          this.$emit('event-pin-changed', {
            id: event.entityId,
            important: event.importantFlag === 1
          })
        } else {
          this.$message.error(res.msg || '操作失败')
        }
      } catch (error) {
        console.error('标记事件失败:', error)
        this.$message.error('操作失败，请稍后重试')
      }
    },
    copyEventInfo(event) {
      const infoSegments = [
        `事件编号：${event.eventNo || event.entityId || '未知'}`,
        `标题：${event.title || event.eventNo || '未命名事件'}`,
        `状态：${this.getEventStatusLabel(event.status)}`,
        `地点：${event.location || event.address || '未知'}`,
        `发生时间：${event.occurredAt ? formatDateTime(event.occurredAt) : (event.createTime ? formatDateTime(event.createTime) : '未知')}`
      ]
      const text = infoSegments.join('\n')
      this.copyToClipboard(text)
        .then(() => {
          this.$message.success('事件关键信息已复制')
        })
        .catch(() => {
          this.$message.error('复制失败，请手动复制')
        })
    },
    copyToClipboard(text) {
      if (navigator.clipboard && navigator.clipboard.writeText) {
        return navigator.clipboard.writeText(text).catch(() => {
          return this.legacyCopy(text)
        })
      } else {
        return Promise.resolve(this.legacyCopy(text))
      }
    },
    legacyCopy(text) {
      return new Promise((resolve, reject) => {
        const textarea = document.createElement('textarea')
        textarea.value = text
        textarea.style.position = 'fixed'
        textarea.style.opacity = '0'
        document.body.appendChild(textarea)
        textarea.select()
        try {
          const success = document.execCommand('copy')
          document.body.removeChild(textarea)
          if (success) {
            resolve()
          } else {
            reject(new Error('Copy command failed'))
          }
        } catch (err) {
          document.body.removeChild(textarea)
          reject(err)
        }
      })
    },
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleOutsideClick, true)
    document.removeEventListener('click', this.handleEventOutsideClick, true)
  }
}
</script>

<style lang="scss" scoped>
.info-card.recent-card {
  min-height: calc(100vh - 545px)
  // height: 100%;
  // display: flex;
  // flex-direction: column;
  // overflow: hidden;
  
  // ::v-deep .el-card__body {
  //   flex: 1;
  //   display: flex;
  //   flex-direction: column;
  //   overflow: hidden;
  //   min-height: 0;
  // }
}

.recent-timeline-box {
  // flex: 1;
  margin-top: 16px;
  box-sizing: border-box;
  // overflow-y: auto;
  overflow-x: hidden;
  min-height: 0;
}

.empty-state {
  margin-top: 32px;
}

::v-deep .el-timeline-item {
  padding-right: 16px;
}

.timeline-item {
  padding: 12px 0;
  border-bottom: 1px solid #f0f2f5;
}

.timeline-item:last-of-type {
  border-bottom: none;
}

.timeline-item .title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  margin-bottom: 6px;
}

.timeline-item .meta {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #909399;
  gap: 12px;
}

.timeline-item .meta .el-button {
  padding: 0;
}

.action-buttons {
  margin-left: auto;
  display: flex;
  gap: 8px;
  position: relative;
}

.timeline-sections {
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 0;
}

.timeline-section {
  border: 1px solid #ebeef5;
  border-radius: 6px;
  padding: 12px;
  background: #fff;
  min-height: 0;
}

.recent-timeline {
  max-height: none;
  padding-left: 0;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  margin-bottom: 8px;
}

.timeline-item.important .title {
  color: #d9001b;
}

.title-tags {
  display: flex;
  gap: 6px;
}


.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
  font-size: 14px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.clear-highlight-btn {
  padding: 0;
}

.filter-bar {
  margin-top: 8px;
  padding: 8px 0;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.range-picker {
  width: 100%;
}

.event-tasks {
  // margin-top: 8px;
  // margin-left: 24px;
  margin: 0 0 0 8px;
  // padding-left: 16px;
  padding-left: 0;
  border-left: 2px solid #e4e7ed;
}

.task-item {
  padding: 8px 0;
  margin-bottom: 8px;
  background: #f8f9fa;
  border-radius: 4px;
  padding: 8px 12px;
}

.task-item:last-child {
  margin-bottom: 0;
}

.task-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  font-size: 13px;
  margin-bottom: 4px;
  color: #606266;
}

.task-tags {
  display: flex;
  gap: 6px;
}

.task-item .meta {
  display: flex;
  align-items: center;
  font-size: 11px;
  color: #909399;
  gap: 12px;
}

.task-item .meta .el-button {
  padding: 0;
  font-size: 11px;
}
</style>