<template>
  <div class="timetable-management-container">
    <!-- 顶部导航栏 -->
    <el-card class="header-card">
      <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>
    </el-card>

    <!-- 日历视图 -->
    <div v-if="viewMode === 'calendar'" class="calendar-view">
      <el-calendar v-model="currentDate">
        <template #dateCell="{ 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)"
                  :key="index"
                  :type="getTagType(event.status)"
                  size="small"
                  @click.stop="viewEvent(event)"
                  style="cursor: pointer;"
                  :title="getTooltip(event)"
              >
                {{ event.title }}
              </el-tag>
            </div>
            <el-button
                v-if="!hasEvents(data.day)"
                size="mini"
                type="text"
                @click.stop="addTimetableForDay(data.day)"
            >
              + 新增
            </el-button>
          </div>
        </template>
      </el-calendar>
      <!-- 右键菜单 -->
      <el-dropdown
          v-if="contextMenuVisible"
          trigger="manual"
          :visible="contextMenuVisible"
          @command="handleContextCommand"
          @hide="contextMenuVisible = false"
          :style="{ position: 'absolute', left: contextMenuX + 'px', top: contextMenuY + 'px' }"
      >
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="add">新增时间表</el-dropdown-item>
            <el-dropdown-item v-if="selectedDayEvents.length > 0" command="view">查看事件</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 列表示图 -->
    <div v-if="viewMode === 'list'" class="list-view">
      <el-table :data="timetableList" border style="width: 100%" @row-click="viewEvent">
        <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" />
        <el-table-column prop="endTime" label="结束时间" align="center" width="180" />
        <el-table-column prop="devices" label="设备" align="center" show-overflow-tooltip />
        <el-table-column prop="commands" label="指令" align="center" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="150">
          <template #default="{ row }">
            <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="prev, pager, next"
          :total="total"
          :page-size="queryParams.pageSize"
          :current-page="queryParams.pageNumber"
          @current-change="handlePageChange"
      />
    </div>

    <!-- 执行历史视图 -->
    <div v-if="viewMode === 'history'" class="history-view">
      <el-table :data="executionHistory" border style="width: 100%" @row-click="viewExecutionDetail">
        <el-table-column prop="id" label="ID" align="center" width="80" />
        <el-table-column prop="timetableId" label="时间表ID" align="center" />
        <el-table-column prop="executionTime" label="执行时间" align="center" width="180" />
        <el-table-column prop="status" label="状态" align="center" />
        <el-table-column prop="result" label="结果" align="center" show-overflow-tooltip />
      </el-table>
      <!-- 分页 -->
      <el-pagination
          v-if="historyTotal > 0"
          background
          layout="prev, pager, next"
          :total="historyTotal"
          :page-size="historyQueryParams.pageSize"
          :current-page="historyQueryParams.pageNumber"
          @current-change="handleHistoryPageChange"
      />
    </div>

    <!-- 新增/编辑时间表对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form :model="timetableForm" label-width="120px">
        <el-form-item label="标题">
          <el-input v-model="timetableForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
              v-model="timetableForm.startTime"
              type="datetime"
              placeholder="选择开始时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
              v-model="timetableForm.endTime"
              type="datetime"
              placeholder="选择结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="设备">
          <el-select v-model="timetableForm.devices" multiple placeholder="请选择设备">
            <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="指令">
          <el-input v-model="timetableForm.commands" type="textarea" :rows="4" placeholder="请输入指令" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTimetable">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看时间表详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="时间表详情" width="50%">
      <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="设备">{{ selectedTimetable.devices.join(', ') }}</el-descriptions-item>
        <el-descriptions-item label="指令">{{ selectedTimetable.commands }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 查看执行历史详情对话框 -->
    <el-dialog v-model="historyDetailDialogVisible" title="执行历史详情" width="50%">
      <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.executionTime }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ selectedExecution.status }}</el-descriptions-item>
        <el-descriptions-item label="结果">{{ selectedExecution.result }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

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

// 视图模式（日历视图或列表视图或执行历史）
const viewMode = ref('calendar')
// 当前日期
const currentDate = ref(new Date())
// 时间表列表数据
const timetableList = ref([])
const total = ref(0)
// 查询参数
const queryParams = ref({
  pageNumber: 1,
  pageSize: 10
})
// 执行历史数据
const executionHistory = ref([])
const historyTotal = ref(0)
// 执行历史查询参数
const historyQueryParams = ref({
  pageNumber: 1,
  pageSize: 10
})
// 控制弹窗显示和内容
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const historyDetailDialogVisible = ref(false)
const dialogTitle = ref('新增时间表')
const timetableForm = ref({
  id: '',
  title: '',
  startTime: '',
  endTime: '',
  devices: [],
  commands: ''
})
const selectedTimetable = ref({})
const selectedExecution = ref({})
// 模拟时间表数据
const timetableMap = ref({
  '2025-04-01': [
    { id: 'T001', title: '设备A维护', startTime: '2025-04-01 08:00:00', endTime: '2025-04-01 10:00:00', devices: ['deviceA'], commands: '维护指令', status: 'success' },
    { id: 'T002', title: '设备B检查', startTime: '2025-04-01 12:00:00', endTime: '2025-04-01 14:00:00', devices: ['deviceB'], commands: '检查指令', status: 'failed' }
  ],
  '2025-04-02': [
    { id: 'T003', title: '设备C清洗', startTime: '2025-04-02 09:00:00', endTime: '2025-04-02 11:00:00', devices: ['deviceC'], commands: '清洗指令', status: 'success' }
  ]
})
// 模拟执行历史数据
const executionHistoryMap = ref([
  { id: 'H001', timetableId: 'T001', executionTime: '2025-04-01 08:00:00', status: '成功', result: '设备A维护完成' },
  { id: 'H002', timetableId: 'T002', executionTime: '2025-04-01 12:00:00', status: '失败', result: '设备B检查异常' },
  { id: 'H003', timetableId: 'T003', executionTime: '2025-04-02 09:00:00', status: '成功', result: '设备C清洗完成' },
  { id: 'H004', timetableId: 'T001', executionTime: '2025-04-03 10:00:00', status: '成功', result: '设备A测试完成' },
  { id: 'H005', timetableId: 'T002', executionTime: '2025-04-04 14:00:00', status: '成功', result: '设备B升级完成' }
])
// 右键菜单相关变量
const contextMenuVisible = ref(false)
const contextMenuX = ref(0)
const contextMenuY = ref(0)
const selectedDay = ref('')
const selectedDayEvents = ref([])

// 获取当前日期的时间表
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'
    default:
      return 'info'
  }
}

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

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

// 获取时间表列表
const fetchTimetables = () => {
  // 模拟异步请求
  setTimeout(() => {
    const mockData = [
      { id: 'T001', title: '设备A维护', startTime: '2025-04-01 08:00:00', endTime: '2025-04-01 10:00:00', devices: ['deviceA'], commands: '维护指令', status: 'success' },
      { id: 'T002', title: '设备B检查', startTime: '2025-04-01 12:00:00', endTime: '2025-04-01 14:00:00', devices: ['deviceB'], commands: '检查指令', status: 'failed' },
      { id: 'T003', title: '设备C清洗', startTime: '2025-04-02 09:00:00', endTime: '2025-04-02 11:00:00', devices: ['deviceC'], commands: '清洗指令', status: 'success' },
      { id: 'T004', title: '设备A测试', startTime: '2025-04-03 10:00:00', endTime: '2025-04-03 12:00:00', devices: ['deviceA'], commands: '测试指令', status: 'success' },
      { id: 'T005', title: '设备B升级', startTime: '2025-04-04 14:00:00', endTime: '2025-04-04 16:00:00', devices: ['deviceB'], commands: '升级指令', status: 'success' }
    ]
    // 模拟分页
    const start = (queryParams.value.pageNumber - 1) * queryParams.value.pageSize
    const end = start + queryParams.value.pageSize
    timetableList.value = mockData.slice(start, end)
    total.value = mockData.length
  }, 300)
}

// 获取执行历史
const fetchExecutionHistory = () => {
  // 模拟异步请求
  setTimeout(() => {
    // 模拟分页
    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
  }, 300)
}

// 新增时间表
const addTimetable = () => {
  dialogTitle.value = '新增时间表'
  timetableForm.value = {
    id: '',
    title: '',
    startTime: '',
    endTime: '',
    devices: [],
    commands: ''
  }
  dialogVisible.value = true
}

// 新增某一天的时间表
const addTimetableForDay = (day) => {
  dialogTitle.value = '新增时间表'
  timetableForm.value = {
    id: '',
    title: '',
    startTime: `${day} 08:00:00`,
    endTime: `${day} 10:00:00`,
    devices: [],
    commands: ''
  }
  dialogVisible.value = true
}

// 编辑时间表
const editTimetable = (timetable) => {
  dialogTitle.value = '编辑时间表'
  timetableForm.value = { ...timetable }
  dialogVisible.value = true
}

// 删除时间表
const deleteTimetable = (timetable) => {
  ElMessage.confirm('确定要删除该时间表吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除操作
    setTimeout(() => {
      ElMessage.success('时间表删除成功')
      fetchTimetables()
    }, 300)
  }).catch(() => {})
}

// 保存时间表
const saveTimetable = () => {
  if (!timetableForm.value.title || !timetableForm.value.startTime || !timetableForm.value.endTime || timetableForm.value.devices.length === 0 || !timetableForm.value.commands) {
    ElMessage.warning('请填写完整的时间表信息')
    return
  }
  // 模拟保存操作
  setTimeout(() => {
    ElMessage.success('时间表保存成功')
    dialogVisible.value = false
    fetchTimetables()
  }, 300)
}

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

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

// 处理日期点击事件
const handleDateClick = (day) => {
  if (!hasEvents(day)) {
    addTimetableForDay(day)
  }
}

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

// 处理右键菜单命令
const handleContextCommand = (command) => {
  if (command === 'add') {
    addTimetableForDay(selectedDay.value)
  } else if (command === 'view') {
    if (selectedDayEvents.value.length > 0) {
      viewEvent(selectedDayEvents.value[0]) // 默认查看第一个事件
    }
  }
}

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

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

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

<style scoped lang="scss">
.timetable-management-container {
  padding: 20px;
}
.header-card {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.calendar-view {
  .el-calendar {
    --el-calendar-day-height: 80px;
  }
  .date-cell {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    p {
      font-size: 14px;
    }
    .highlight {
      font-weight: bold;
      color: #409EFF;
    }
    .event-day {
      color: #67C23A;
    }
    .events {
      margin-top: 5px;
      display: flex;
      flex-wrap: wrap;
      gap: 5px;
      .el-tag {
        max-width: 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
    .el-button--text {
      padding: 0;
      font-size: 12px;
    }
  }
}
.list-view, .history-view {
  .el-table {
    margin-bottom: 20px;
  }
  .el-pagination {
    text-align: right;
  }
}
.dialog-footer {
  text-align: right;
}
</style>
