<template>
  <div class="timetable-management-container">
    <!-- 顶部导航栏 -->
    <el-card class="header-card">
      <div class="header-content">
        <el-tabs v-model="viewMode" type="card" @tab-click="handleTabClick">
          <el-tab-pane label="日历视图" name="calendar"></el-tab-pane>
          <el-tab-pane label="列表视图" name="list"></el-tab-pane>
          <el-tab-pane label="执行历史" name="history"></el-tab-pane>
        </el-tabs>
        <el-button type="primary" @click="addTimetable">新增时间表</el-button>
      </div>
    </el-card>

    <!-- 日历视图 -->
    <div v-if="viewMode === 'calendar'" class="calendar-view">
      <el-calendar v-model="currentDate">
        <template #date-cell="{ data }">
          <div class="date-cell" @click="handleDateClick(data.day)" @contextmenu.prevent="showContextMenu(data.day, $event)">
            <p :class="{'highlight': isToday(data.day), 'event-day': hasEvents(data.day)}">
              {{ data.day.split('-').slice(2).join('-') }}
            </p>
            <div v-if="hasEvents(data.day)" class="events">
              <el-tag
                  v-for="(event, index) in getEvents(data.day).slice(0, 3)"
                  :key="index"
                  :type="getTagType(event.status)"
                  size="small"
                  @click.stop="viewEvent(event)"
                  style="cursor: pointer;"
                  :title="getTooltip(event)"
              >
                {{ event.title }}
              </el-tag>
              <el-tag v-if="getEvents(data.day).length > 3" size="small" type="info">
                +{{ getEvents(data.day).length - 3 }}
              </el-tag>
            </div>
            <el-button
                v-if="!hasEvents(data.day)"
                size="small"
                type="text"
                @click.stop="addTimetableForDay(data.day)"
            >
              + 新增
            </el-button>
          </div>
        </template>
      </el-calendar>

      <!-- 右键菜单 -->
      <div
          v-if="contextMenuVisible"
          class="context-menu"
          :style="{ left: contextMenuX + 'px', top: contextMenuY + 'px' }"
          @click.stop
      >
        <div class="menu-item" @click="handleContextCommand('add')">新增时间表</div>
        <div v-if="selectedDayEvents.length > 0" class="menu-item" @click="handleContextCommand('viewAll')">
          查看所有事件 ({{ selectedDayEvents.length }})
        </div>
      </div>
    </div>

    <!-- 列表视图 -->
    <div v-if="viewMode === 'list'" class="list-view">
      <!-- 搜索栏 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="标题">
          <el-input v-model="searchParams.title" placeholder="请输入标题" clearable />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
              v-model="searchParams.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchParams.status" placeholder="请选择状态" clearable>
            <el-option label="成功" value="success" />
            <el-option label="失败" value="failed" />
            <el-option label="待执行" value="pending" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="timetableList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" align="center" width="80" />
        <el-table-column prop="title" label="标题" align="center" />
        <el-table-column prop="startTime" label="开始时间" align="center" width="180" sortable />
        <el-table-column prop="endTime" label="结束时间" align="center" width="180" sortable />
        <el-table-column prop="devices" label="设备" align="center">
          <template #default="{ row }">
            <el-tag v-for="device in row.devices" :key="device" size="small" style="margin: 0 2px;">
              {{ getDeviceName(device) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click.stop="viewEvent(row)">查看</el-button>
            <el-button size="small" @click.stop="editTimetable(row)">编辑</el-button>
            <el-button size="small" type="danger" @click.stop="deleteTimetable(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-if="total > 0"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.pageSize"
          :current-page="queryParams.pageNumber"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>

    <!-- 执行历史视图 -->
    <div v-if="viewMode === 'history'" class="history-view">
      <el-table :data="executionHistory" border style="width: 100%" v-loading="historyLoading">
        <el-table-column prop="id" label="ID" align="center" width="80" />
        <el-table-column prop="timetableId" label="时间表ID" align="center" width="100" />
        <el-table-column prop="timetableTitle" label="时间表标题" align="center" />
        <el-table-column prop="executionTime" label="执行时间" align="center" width="180" sortable />
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '成功' ? 'success' : 'danger'">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="result" label="结果" align="center" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="100">
          <template #default="{ row }">
            <el-button size="small" @click="viewExecutionDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-if="historyTotal > 0"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="historyTotal"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="historyQueryParams.pageSize"
          :current-page="historyQueryParams.pageNumber"
          @size-change="handleHistorySizeChange"
          @current-change="handleHistoryPageChange"
      />
    </div>

    <!-- 新增/编辑时间表对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :close-on-click-modal="false">
      <el-form ref="timetableFormRef" :model="timetableForm" :rules="timetableRules" label-width="120px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="timetableForm.title" placeholder="请输入标题" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="时间范围" prop="timeRange">
          <el-date-picker
              v-model="timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleTimeRangeChange"
          />
        </el-form-item>
        <el-form-item label="设备" prop="devices">
          <el-select v-model="timetableForm.devices" multiple placeholder="请选择设备" style="width: 100%">
            <el-option label="设备A" value="deviceA" />
            <el-option label="设备B" value="deviceB" />
            <el-option label="设备C" value="deviceC" />
          </el-select>
        </el-form-item>
        <el-form-item label="指令" prop="commands">
          <el-input v-model="timetableForm.commands" type="textarea" :rows="4" placeholder="请输入指令" maxlength="500" show-word-limit />
        </el-form-item>
        <el-form-item label="循环执行">
          <el-switch v-model="timetableForm.isRecurring" />
        </el-form-item>
        <el-form-item v-if="timetableForm.isRecurring" label="循环类型" prop="recurringType">
          <el-radio-group v-model="timetableForm.recurringType">
            <el-radio label="daily">每天</el-radio>
            <el-radio label="weekly">每周</el-radio>
            <el-radio label="monthly">每月</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTimetable" :loading="saveLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看时间表详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="时间表详情" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{ selectedTimetable.id }}</el-descriptions-item>
        <el-descriptions-item label="标题">{{ selectedTimetable.title }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ selectedTimetable.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ selectedTimetable.endTime }}</el-descriptions-item>
        <el-descriptions-item label="设备" :span="2">
          <el-tag v-for="device in selectedTimetable.devices" :key="device" size="small" style="margin: 0 2px;">
            {{ getDeviceName(device) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="指令" :span="2">{{ selectedTimetable.commands }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getTagType(selectedTimetable.status)">{{ getStatusText(selectedTimetable.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ selectedTimetable.createTime || '2025-07-01 08:00:00' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="editFromDetail">编辑</el-button>
      </template>
    </el-dialog>

    <!-- 查看执行历史详情对话框 -->
    <el-dialog v-model="historyDetailDialogVisible" title="执行历史详情" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{ selectedExecution.id }}</el-descriptions-item>
        <el-descriptions-item label="时间表ID">{{ selectedExecution.timetableId }}</el-descriptions-item>
        <el-descriptions-item label="时间表标题">{{ selectedExecution.timetableTitle }}</el-descriptions-item>
        <el-descriptions-item label="执行时间">{{ selectedExecution.executionTime }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="selectedExecution.status === '成功' ? 'success' : 'danger'">{{ selectedExecution.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="耗时">{{ selectedExecution.duration || '120ms' }}</el-descriptions-item>
        <el-descriptions-item label="结果" :span="2">{{ selectedExecution.result }}</el-descriptions-item>
        <el-descriptions-item label="错误信息" :span="2" v-if="selectedExecution.status === '失败'">
          <span style="color: #F56C6C;">{{ selectedExecution.errorMsg || '设备连接超时' }}</span>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="historyDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 查看某天所有事件对话框 -->
    <el-dialog v-model="dayEventsDialogVisible" :title="`${selectedDay} 的所有事件`" width="800px">
      <el-table :data="selectedDayEvents" border style="width: 100%">
        <el-table-column prop="title" label="标题" align="center" />
        <el-table-column prop="startTime" label="开始时间" align="center" width="180" />
        <el-table-column prop="endTime" label="结束时间" align="center" width="180" />
        <el-table-column prop="devices" label="设备" align="center">
          <template #default="{ row }">
            <el-tag v-for="device in row.devices" :key="device" size="small" style="margin: 0 2px;">
              {{ getDeviceName(device) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="viewEvent(row)">查看</el-button>
            <el-button size="small" @click="editTimetable(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="dayEventsDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 视图模式
const viewMode = ref('calendar')
// 当前日期
const currentDate = ref(new Date())
// 时间表列表数据
const timetableList = ref([])
const total = ref(0)
const loading = ref(false)
// 查询参数
const queryParams = ref({
  pageNumber: 1,
  pageSize: 10
})
// 搜索参数
const searchParams = ref({
  title: '',
  dateRange: null,
  status: ''
})
// 执行历史数据
const executionHistory = ref([])
const historyTotal = ref(0)
const historyLoading = ref(false)
// 执行历史查询参数
const historyQueryParams = ref({
  pageNumber: 1,
  pageSize: 10
})
// 控制弹窗显示
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const historyDetailDialogVisible = ref(false)
const dayEventsDialogVisible = ref(false)
const dialogTitle = ref('新增时间表')
const saveLoading = ref(false)
// 表单引用
const timetableFormRef = ref(null)
// 时间范围
const timeRange = ref([])
// 表单数据
const timetableForm = ref({
  id: '',
  title: '',
  startTime: '',
  endTime: '',
  devices: [],
  commands: '',
  isRecurring: false,
  recurringType: 'daily'
})
// 表单验证规则
const timetableRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  timeRange: [
    { required: true, message: '请选择时间范围', trigger: 'change' }
  ],
  devices: [
    { required: true, message: '请选择设备', trigger: 'change' },
    { type: 'array', min: 1, message: '至少选择一个设备', trigger: 'change' }
  ],
  commands: [
    { required: true, message: '请输入指令', trigger: 'blur' },
    { min: 1, max: 500, message: '指令长度在 1 到 500 个字符', trigger: 'blur' }
  ],
  recurringType: [
    { required: true, message: '请选择循环类型', trigger: 'change' }
  ]
}
// 选中的数据
const selectedTimetable = ref({})
const selectedExecution = ref({})
// 模拟时间表数据
const timetableMap = ref({
  '2025-07-01': [
    { id: 'T001', title: '设备A维护', startTime: '2025-07-01 08:00:00', endTime: '2025-07-01 10:00:00', devices: ['deviceA'], commands: '维护指令', status: 'success' },
    { id: 'T002', title: '设备B检查', startTime: '2025-07-01 12:00:00', endTime: '2025-07-01 14:00:00', devices: ['deviceB'], commands: '检查指令', status: 'failed' }
  ],
  '2025-07-02': [
    { id: 'T003', title: '设备C清洗', startTime: '2025-07-02 09:00:00', endTime: '2025-07-02 11:00:00', devices: ['deviceC'], commands: '清洗指令', status: 'success' }
  ],
  '2025-07-15': [
    { id: 'T006', title: '设备A例行检查', startTime: '2025-07-15 09:00:00', endTime: '2025-07-15 10:00:00', devices: ['deviceA'], commands: '检查指令', status: 'pending' },
    { id: 'T007', title: '设备B维护', startTime: '2025-07-15 14:00:00', endTime: '2025-07-15 16:00:00', devices: ['deviceB'], commands: '维护指令', status: 'pending' },
    { id: 'T008', title: '设备C测试', startTime: '2025-07-15 16:30:00', endTime: '2025-07-15 17:30:00', devices: ['deviceC'], commands: '测试指令', status: 'pending' },
    { id: 'T009', title: '全设备检查', startTime: '2025-07-15 18:00:00', endTime: '2025-07-15 20:00:00', devices: ['deviceA', 'deviceB', 'deviceC'], commands: '全面检查', status: 'pending' }
  ]
})
// 模拟执行历史数据
const executionHistoryMap = ref([
  { id: 'H001', timetableId: 'T001', timetableTitle: '设备A维护', executionTime: '2025-07-01 08:00:00', status: '成功', result: '设备A维护完成', duration: '120ms' },
  { id: 'H002', timetableId: 'T002', timetableTitle: '设备B检查', executionTime: '2025-07-01 12:00:00', status: '失败', result: '设备B检查异常', errorMsg: '设备连接超时', duration: '5000ms' },
  { id: 'H003', timetableId: 'T003', timetableTitle: '设备C清洗', executionTime: '2025-07-02 09:00:00', status: '成功', result: '设备C清洗完成', duration: '200ms' },
  { id: 'H004', timetableId: 'T001', timetableTitle: '设备A维护', executionTime: '2025-07-03 10:00:00', status: '成功', result: '设备A测试完成', duration: '150ms' },
  { id: 'H005', timetableId: 'T002', timetableTitle: '设备B检查', executionTime: '2025-07-04 14:00:00', status: '成功', result: '设备B升级完成', duration: '300ms' }
])
// 右键菜单相关变量
const contextMenuVisible = ref(false)
const contextMenuX = ref(0)
const contextMenuY = ref(0)
const selectedDay = ref('')
const selectedDayEvents = ref([])

// 设备名称映射
const deviceNameMap = {
  'deviceA': '设备A',
  'deviceB': '设备B',
  'deviceC': '设备C'
}

// 状态文本映射
const statusTextMap = {
  'success': '成功',
  'failed': '失败',
  'pending': '待执行'
}

// 获取设备名称
const getDeviceName = (deviceCode) => {
  return deviceNameMap[deviceCode] || deviceCode
}

// 获取状态文本
const getStatusText = (status) => {
  return statusTextMap[status] || status
}

// 获取当前日期的时间表
const getEvents = (day) => {
  return timetableMap.value[day] || []
}

// 判断某天是否有事件
const hasEvents = (day) => {
  return timetableMap.value[day] && timetableMap.value[day].length > 0
}

// 判断是否是今天
const isToday = (day) => {
  const today = new Date().toISOString().split('T')[0]
  return day === today
}

// 获取事件标签类型
const getTagType = (status) => {
  switch (status) {
    case 'success':
      return 'success'
    case 'failed':
      return 'danger'
    case 'pending':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取事件提示信息
const getTooltip = (event) => {
  return `标题: ${event.title}\n开始时间: ${event.startTime}\n结束时间: ${event.endTime}\n设备: ${event.devices.map(d => getDeviceName(d)).join(', ')}\n指令: ${event.commands}`
}

// 切换视图模式
const handleTabClick = () => {
  if (viewMode.value === 'list') {
    fetchTimetables()
  } else if (viewMode.value === 'history') {
    fetchExecutionHistory()
  }
}

// 获取时间表列表
const fetchTimetables = async () => {
  loading.value = true
  try {
    // 模拟异步请求
    await new Promise(resolve => setTimeout(resolve, 300))

    let mockData = [
      { id: 'T001', title: '设备A维护', startTime: '2025-07-01 08:00:00', endTime: '2025-07-01 10:00:00', devices: ['deviceA'], commands: '维护指令', status: 'success', createTime: '2025-03-25 10:00:00' },
      { id: 'T002', title: '设备B检查', startTime: '2025-07-01 12:00:00', endTime: '2025-07-01 14:00:00', devices: ['deviceB'], commands: '检查指令', status: 'failed', createTime: '2025-03-25 11:00:00' },
      { id: 'T003', title: '设备C清洗', startTime: '2025-07-02 09:00:00', endTime: '2025-07-02 11:00:00', devices: ['deviceC'], commands: '清洗指令', status: 'success', createTime: '2025-03-26 09:00:00' },
      { id: 'T004', title: '设备A测试', startTime: '2025-07-03 10:00:00', endTime: '2025-07-03 12:00:00', devices: ['deviceA'], commands: '测试指令', status: 'success', createTime: '2025-03-27 14:00:00' },
      { id: 'T005', title: '设备B升级', startTime: '2025-07-04 14:00:00', endTime: '2025-07-04 16:00:00', devices: ['deviceB'], commands: '升级指令', status: 'success', createTime: '2025-03-28 15:00:00' },
      { id: 'T006', title: '设备A例行检查', startTime: '2025-07-15 09:00:00', endTime: '2025-07-15 10:00:00', devices: ['deviceA'], commands: '检查指令', status: 'pending', createTime: '2025-07-01 10:00:00' },
      { id: 'T007', title: '设备B维护', startTime: '2025-07-15 14:00:00', endTime: '2025-07-15 16:00:00', devices: ['deviceB'], commands: '维护指令', status: 'pending', createTime: '2025-07-01 11:00:00' },
      { id: 'T008', title: '设备C测试', startTime: '2025-07-15 16:30:00', endTime: '2025-07-15 17:30:00', devices: ['deviceC'], commands: '测试指令', status: 'pending', createTime: '2025-07-01 12:00:00' },
      { id: 'T009', title: '全设备检查', startTime: '2025-07-15 18:00:00', endTime: '2025-07-15 20:00:00', devices: ['deviceA', 'deviceB', 'deviceC'], commands: '全面检查', status: 'pending', createTime: '2025-07-01 13:00:00' }
    ]

    // 应用搜索过滤
    if (searchParams.value.title) {
      mockData = mockData.filter(item => item.title.includes(searchParams.value.title))
    }
    if (searchParams.value.status) {
      mockData = mockData.filter(item => item.status === searchParams.value.status)
    }
    if (searchParams.value.dateRange && searchParams.value.dateRange.length === 2) {
      const [start, end] = searchParams.value.dateRange
      mockData = mockData.filter(item => {
        return item.startTime >= start && item.endTime <= end
      })
    }

    // 模拟分页
    total.value = mockData.length
    const start = (queryParams.value.pageNumber - 1) * queryParams.value.pageSize
    const end = start + queryParams.value.pageSize
    timetableList.value = mockData.slice(start, end)
  } catch (error) {
    ElMessage.error('获取时间表列表失败')
  } finally {
    loading.value = false
  }
}

// 获取执行历史
const fetchExecutionHistory = async () => {
  historyLoading.value = true
  try {
    // 模拟异步请求
    await new Promise(resolve => setTimeout(resolve, 300))

    // 模拟分页
    const start = (historyQueryParams.value.pageNumber - 1) * historyQueryParams.value.pageSize
    const end = start + historyQueryParams.value.pageSize
    executionHistory.value = executionHistoryMap.value.slice(start, end)
    historyTotal.value = executionHistoryMap.value.length
  } catch (error) {
    ElMessage.error('获取执行历史失败')
  } finally {
    historyLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.value.pageNumber = 1
  fetchTimetables()
}

// 重置搜索
const resetSearch = () => {
  searchParams.value = {
    title: '',
    dateRange: null,
    status: ''
  }
  handleSearch()
}

// 新增时间表
const addTimetable = () => {
  dialogTitle.value = '新增时间表'
  timetableForm.value = {
    id: '',
    title: '',
    startTime: '',
    endTime: '',
    devices: [],
    commands: '',
    isRecurring: false,
    recurringType: 'daily'
  }
  timeRange.value = []
  dialogVisible.value = true
  // 清除表单验证
  nextTick(() => {
    timetableFormRef.value?.clearValidate()
  })
}

// 新增某一天的时间表
const addTimetableForDay = (day) => {
  dialogTitle.value = '新增时间表'
  const startTime = `${day} 08:00:00`
  const endTime = `${day} 10:00:00`
  timetableForm.value = {
    id: '',
    title: '',
    startTime,
    endTime,
    devices: [],
    commands: '',
    isRecurring: false,
    recurringType: 'daily'
  }
  timeRange.value = [startTime, endTime]
  dialogVisible.value = true
  // 清除表单验证
  nextTick(() => {
    timetableFormRef.value?.clearValidate()
  })
}

// 编辑时间表
const editTimetable = (timetable) => {
  dialogTitle.value = '编辑时间表'
  timetableForm.value = { ...timetable }
  timeRange.value = [timetable.startTime, timetable.endTime]
  dialogVisible.value = true
  // 清除表单验证
  nextTick(() => {
    timetableFormRef.value?.clearValidate()
  })
}

// 从详情页编辑
const editFromDetail = () => {
  detailDialogVisible.value = false
  editTimetable(selectedTimetable.value)
}

// 删除时间表
const deleteTimetable = (timetable) => {
  ElMessageBox.confirm(
      `确定要删除时间表"${timetable.title}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      // 模拟删除操作
      await new Promise(resolve => setTimeout(resolve, 300))

      // 从日历数据中删除
      const day = timetable.startTime.split(' ')[0]
      if (timetableMap.value[day]) {
        timetableMap.value[day] = timetableMap.value[day].filter(item => item.id !== timetable.id)
        if (timetableMap.value[day].length === 0) {
          delete timetableMap.value[day]
        }
      }

      ElMessage.success('删除成功')
      fetchTimetables()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 处理时间范围变化
const handleTimeRangeChange = (value) => {
  if (value && value.length === 2) {
    timetableForm.value.startTime = value[0]
    timetableForm.value.endTime = value[1]
  }
}

// 保存时间表
const saveTimetable = async () => {
  try {
    // 表单验证
    const valid = await timetableFormRef.value.validate()
    if (!valid) return

    // 时间验证
    if (new Date(timetableForm.value.startTime) >= new Date(timetableForm.value.endTime)) {
      ElMessage.warning('开始时间必须小于结束时间')
      return
    }

    saveLoading.value = true
    // 模拟保存操作
    await new Promise(resolve => setTimeout(resolve, 500))

    // 生成ID（编辑时保持原ID）
    if (!timetableForm.value.id) {
      timetableForm.value.id = 'T' + Date.now().toString().slice(-3)
    }

    // 添加到日历数据
    const day = timetableForm.value.startTime.split(' ')[0]
    if (!timetableMap.value[day]) {
      timetableMap.value[day] = []
    }

    // 如果是编辑，先删除原数据
    if (dialogTitle.value === '编辑时间表') {
      // 可能日期改变了，需要从原日期删除
      Object.keys(timetableMap.value).forEach(date => {
        timetableMap.value[date] = timetableMap.value[date].filter(item => item.id !== timetableForm.value.id)
        if (timetableMap.value[date].length === 0) {
          delete timetableMap.value[date]
        }
      })
    }

    // 添加新数据
    const newTimetable = {
      ...timetableForm.value,
      status: 'pending',
      createTime: new Date().toISOString().replace('T', ' ').slice(0, 19)
    }

    if (!timetableMap.value[day]) {
      timetableMap.value[day] = []
    }
    timetableMap.value[day].push(newTimetable)

    ElMessage.success(dialogTitle.value === '新增时间表' ? '新增成功' : '编辑成功')
    dialogVisible.value = false

    // 如果在列表视图，刷新列表
    if (viewMode.value === 'list') {
      fetchTimetables()
    }
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    saveLoading.value = false
  }
}

// 查看时间表详情
const viewEvent = (event) => {
  selectedTimetable.value = { ...event }
  detailDialogVisible.value = true
}

// 查看执行历史详情
const viewExecutionDetail = (execution) => {
  selectedExecution.value = { ...execution }
  historyDetailDialogVisible.value = true
}

// 处理日期点击事件
const handleDateClick = (day) => {
  const events = getEvents(day)
  if (events.length === 0) {
    addTimetableForDay(day)
  } else if (events.length === 1) {
    viewEvent(events[0])
  } else {
    // 多个事件时显示列表
    selectedDay.value = day
    selectedDayEvents.value = events
    dayEventsDialogVisible.value = true
  }
}

// 显示右键菜单
const showContextMenu = (day, event) => {
  event.preventDefault()
  contextMenuVisible.value = true
  contextMenuX.value = event.clientX
  contextMenuY.value = event.clientY
  selectedDay.value = day
  selectedDayEvents.value = getEvents(day)

  // 点击其他地方关闭菜单
  document.addEventListener('click', closeContextMenu)
}

// 关闭右键菜单
const closeContextMenu = () => {
  contextMenuVisible.value = false
  document.removeEventListener('click', closeContextMenu)
}

// 处理右键菜单命令
const handleContextCommand = (command) => {
  if (command === 'add') {
    addTimetableForDay(selectedDay.value)
  } else if (command === 'viewAll') {
    dayEventsDialogVisible.value = true
  }
  closeContextMenu()
}

// 分页变化处理
const handlePageChange = (page) => {
  queryParams.value.pageNumber = page
  fetchTimetables()
}

// 每页条数变化处理
const handleSizeChange = (size) => {
  queryParams.value.pageSize = size
  queryParams.value.pageNumber = 1
  fetchTimetables()
}

// 执行历史分页变化处理
const handleHistoryPageChange = (page) => {
  historyQueryParams.value.pageNumber = page
  fetchExecutionHistory()
}

// 执行历史每页条数变化处理
const handleHistorySizeChange = (size) => {
  historyQueryParams.value.pageSize = size
  historyQueryParams.value.pageNumber = 1
  fetchExecutionHistory()
}

// 监听时间范围变化，同步到表单
watch(timeRange, (newVal) => {
  if (newVal && newVal.length === 2) {
    timetableForm.value.startTime = newVal[0]
    timetableForm.value.endTime = newVal[1]
  }
})

// 页面加载时初始化数据
onMounted(() => {
  fetchTimetables()
})

// 组件卸载时清理
onUnmounted(() => {
  document.removeEventListener('click', closeContextMenu)
})
</script>

<style scoped lang="scss">
.timetable-management-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header-card {
  margin-bottom: 20px;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.calendar-view {
  flex: 1;
  overflow: auto;
  position: relative;

  :deep(.el-calendar) {
    --el-calendar-day-height: 100px;

    .el-calendar__body {
      padding: 12px 20px 35px;
    }
  }

  .date-cell {
    height: 100%;
    padding: 8px;
    display: flex;
    flex-direction: column;
    cursor: pointer;
    transition: background-color 0.3s;

    &:hover {
      background-color: #f5f7fa;
    }

    p {
      font-size: 14px;
      margin-bottom: 4px;

      &.highlight {
        font-weight: bold;
        color: #409EFF;
      }

      &.event-day {
        color: #67C23A;
        font-weight: 600;
      }
    }

    .events {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 4px;
      overflow: hidden;

      .el-tag {
        max-width: 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        cursor: pointer;

        &:hover {
          opacity: 0.8;
        }
      }
    }

    .el-button--text {
      padding: 0;
      font-size: 12px;
      margin-top: auto;
    }
  }
}

.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 3000;
  padding: 4px 0;

  .menu-item {
    padding: 8px 16px;
    cursor: pointer;
    font-size: 14px;
    color: #606266;

    &:hover {
      background-color: #f5f7fa;
      color: #409EFF;
    }
  }
}

.list-view, .history-view {
  flex: 1;
  display: flex;
  flex-direction: column;

  .el-table {
    flex: 1;
  }

  .el-pagination {
    margin-top: 20px;
    text-align: right;
  }
}

.dialog-footer {
  text-align: right;
}

// 响应式布局
@media (max-width: 768px) {
  .search-form {
    :deep(.el-form-item) {
      margin-bottom: 10px;
    }
  }

  .calendar-view {
    :deep(.el-calendar) {
      --el-calendar-day-height: 80px;
    }

    .date-cell {
      padding: 4px;

      p {
        font-size: 12px;
      }

      .events {
        .el-tag {
          font-size: 10px;
        }
      }
    }
  }
}
</style>
