<template>
  <div>
    <el-card>
      <div class="search-container" @keyup.enter="donesearchTable">
        <span class="show-text">生产订单:</span>
        <el-input v-model="doneorderNo" placeholder="请输入生产订单" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">销售订单:</span>
        <el-input v-model="donecontractNo" placeholder="请输入销售订单" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">物料编码:</span>
        <el-input v-model="doneproductCode" placeholder="请输入物料编码" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">物料名称:</span>
        <el-input v-model="doneproductName" placeholder="请输入物料名称" clearable style="width: 150px;margin-right: 10px" />
        <br>
        <br>
        <span class="show-text">工序名称:</span>
        <el-input v-model="doneprocessName" placeholder="请输入工序名称" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">计划开始:</span>
        <el-date-picker
          v-model="planStartTime"
          :clearable="false"
          end-placeholder="结束时间"
          format="yyyy-MM-dd"
          popper-class="virtual-cell-time-picker"
          range-separator="-"
          start-placeholder="开始时间"
          style="width: 280px;vertical-align: top"
          type="datetimerange"
          value-format="yyyy-MM-dd" />
        <span class="show-text">计划完成:</span>

        <el-button :disabled="loading" icon="el-icon-search" plain type="primary" @click="donesearchTable()">查询</el-button>
      </div>
      <el-tabs v-model="doneactiveTab" class="custom-tabs">
        <el-tab-pane label="表单" name="form">
          <div style="width: 100%;">
            <el-table
              v-loading="loading"
              :data="donetableData"
              :height="'60vh'"
              border
              element-loading-background="rgba(0, 0, 0, 0.2)"
              element-loading-spinner="el-icon-loading"
              highlight-current-row
              size="mini"
              style="width: 100%;"
              tooltip-effect="dark"
              ref="multipleTable"
              @row-click="handleRowClick"
              @selection-change="handleSelectionChange"
              :row-class-name="donetableRowClassName"
            >
              <el-table-column align="center" type="selection" width="50" />

              <el-table-column align="center" prop="订单号" label="生产订单" width="80" />
              <el-table-column align="center" prop="计划号" label="计划号" width="80" />
              <el-table-column align="center" prop="产品编码" label="物料编码" width="150" />
              <el-table-column align="center" prop="产品名称" label="物料名称" width="150" />
              <el-table-column align="center" prop="计划数量" label="计划数" width="70" />
              <el-table-column align="center" label="要求完工日期" width="100">
                <template slot-scope="scope">
                  {{ formatDate(scope.row.要求完工日期) }}
                </template>
              </el-table-column>
              <el-table-column align="center" prop="标准工时" label="工时" width="80" />
              <el-table-column align="center" prop="工序名称" label="工序名称" width="80" />

              <el-table-column align="center" prop="指派对象" label="指派对象" width="150">
                <template slot-scope="scope">
                  <div class="editable-cell">
                    {{ scope.row.指派对象 }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="指派数量" label="指派数量" width="200">
                <template slot-scope="scope">
                  <div class="editable-cell">
                    {{ scope.row.指派数量 }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="计划开始" width="180">
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.计划开始时间"
                    type="datetime"
                    placeholder="计划开始时间"
                    size="small"
                    style="width: 160px;"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    @change="editstarTask(scope.row)"
                    :clearable="false"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="计划完成" width="180">
                <template slot-scope="scope">
                  {{ formatDateTime(scope.row.计划完成时间) }}
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              :current-page="donepageCurrent"
              :page-sizes="[10, 20, 30, 40, 100]"
              :page-size="donepageSize"
              :total="donetotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="donehandleSizeChanges"
              @current-change="donehandleCurrentChanges"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane label="日程" name="doneschedule">
          <div class="schedule-container">
            <div class="calendar-header">
              <el-button-group>
                <el-button size="small" :type="currentView === 'dayGridMonth' ? 'primary' : ''" @click="changeView('dayGridMonth')">月</el-button>
                <el-button size="small" :type="currentView === 'timeGridWeek' ? 'primary' : ''" @click="changeView('timeGridWeek')">周</el-button>
                <el-button size="small" :type="currentView === 'timeGridDay' ? 'primary' : ''" @click="changeView('timeGridDay')">日</el-button>
              </el-button-group>
              <div style="flex: 1"></div>
              <el-button size="small" @click="goToday()">今天</el-button>
            </div>
            <div class="calendar-wrapper">
              <FullCalendar ref="donefullCalendar" :options="donecalendarOptions" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'

export default {
  components: { FullCalendar },
  data() {
    // 设置默认时间为今天
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const todayStr = today.toISOString().split('T')[0]
    const tomorrow = new Date(today)
    tomorrow.setDate(tomorrow.getDate() + 2)
    const tomorrowStr = tomorrow.toISOString().split('T')[0]
    
    return {
      doneactiveTab: 'form',
      donecontractNo: '',
      doneorderNo: '',
      doneproductCode: '',
      doneproductName: '',
      doneprocessName: '',
      doneproductionStatus: '已完成',
      Doing: [],
      Doingoptions: [],
      station: '全部',
      planStartTime: [todayStr, tomorrowStr], // 默认今天
      loading: false,
      donetableData: [],
      multipleSelection: [],
      selectedRow: null,
      currentView: 'timeGridWeek', // 当前视图状态

      donetotal: 0,
      donepageCurrent: 1,
      donepageSize: 20,

      donecalendarOptions: {
        plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin],
        initialView: 'timeGridWeek', // 默认周视图
        locale: 'zh-cn',
        headerToolbar: false, // 禁用默认header，使用自定义
        editable: true,
        droppable: true,
        selectable: true,
        events: [],
        eventDrop: this.handleEventDrop.bind(this),
        eventClick: this.handleEventClick.bind(this),
        eventResize: this.handleEventResize.bind(this),
        eventDragStart: this.handleEventDragStart.bind(this),
        eventDragStop: this.handleEventDragStop.bind(this),
        
        // 高度自适应配置
        height: 'auto',
        contentHeight: 'auto',
        
        // 时间槽配置
        slotMinTime: '00:00:00',
        slotMaxTime: '24:00:00',
        allDaySlot: false,
        weekends: true,
        nowIndicator: true,
        
        // 时间间隔配置 - 确保每小时高度自适应
        slotDuration: '01:00:00',
        slotLabelInterval: '01:00:00',
        slotLabelFormat: {
          hour: '2-digit',
          minute: '2-digit',
          hour12: false
        },
        
        // 日期头部格式
        dayHeaderFormat: { 
          weekday: 'short', 
          day: 'numeric', 
          month: 'short', 
          omitCommas: true 
        },
        eventTimeFormat: { 
          hour: '2-digit', 
          minute: '2-digit', 
          hour12: false 
        },
        
        // 视图配置
        dayMaxEventRows: false,
        dayMaxEvents: false,
        
        // 周/日视图关键配置 - 实现纵向排列
        expandRows: true,
        slotEventOverlap: false,
        eventDisplay: 'block',
        
        // 拖拽配置
        eventStartEditable: true,
        eventDurationEditable: true,
        eventResizableFromStart: true,
        
        // 事件显示配置
        eventMinHeight: 20,
        
        // 窗口响应
        handleWindowResize: true,
        
        // 业务时间配置
        businessHours: {
          daysOfWeek: [0, 1, 2, 3, 4, 5, 6, 7],
          startTime: '00:00',
          endTime: '24:00',
        }
      },
      currentTime: "",
      isDragging: false,
      draggedEventId: null,
      
      // 新增：用于跟踪事件状态
      eventUpdateQueue: [],
      isUpdatingEvents: false,
    }
  },
  computed: {
    donecalendarEvents() {
      return this.donetableData
        .filter(item => item.计划开始时间)
        .map(item => {
          const isPriority = item.优先级 === '是' || item.加急状态 === '加急'
          const durationHours = parseFloat(item.标准工时) || 1
          const startTime = this.formatDateForCalendar(item.计划开始时间)
          
          if (!startTime) {
            console.warn('Invalid start time for calendar event:', item.计划开始时间)
            return null
          }

          const endTime = this.calculateEndTime(startTime, durationHours)

          return {
            id: `${item.订单号}-${item.订单行号}-${item.拆分内码}`,
            title: `${item.订单号} | ${item.产品名称} | ${item.指派对象}`,
            start: startTime,
            end: endTime,
            extendedProps: {
              订单号: item.订单号,
              订单行号: item.订单行号,
              拆分内码: item.拆分内码,
              指派对象: item.指派对象,
              计划数量: item.计划数量,
              标准工时: item.标准工时,
              优先级: item.优先级,
              计划开始时间: item.计划开始时间,
              计划完成时间: item.计划完成时间
            },
            backgroundColor: isPriority ? '#f56c6c' : '#409EFF',
            borderColor: isPriority ? '#f56c6c' : '#409EFF',
            textColor: '#fff',
            classNames: isPriority ? ['priority-event'] : ['normal-event'],
            editable: true,
            durationEditable: true,
            display: 'block',
            startEditable: true,
          }
        })
        .filter(event => event !== null)
    }
  },
  watch: {
    doneactiveTab(newVal) {
      if (newVal === 'doneschedule') {
        this.$nextTick(() => {
          setTimeout(() => {
            this.loadCalendarEvents()
          }, 100)
        })
      }
    },
    donetableData: {
      handler() {
        if (this.doneactiveTab === 'doneschedule') {
          this.$nextTick(() => {
            this.loadCalendarEvents()
          })
        }
      },
      deep: true
    }
  },
  created() {
    this.donesearchTable()
    this.getCurrentTime();
    setInterval(this.getCurrentTime, 1000);
  },
  mounted() {
    window.addEventListener('resize', this.handleWindowResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleWindowResize)
  },
  methods: {
    handleWindowResize() {
      const calendarApi = this.$refs.donefullCalendar?.getApi()
      if (calendarApi) {
        setTimeout(() => {
          calendarApi.updateSize()
        }, 100)
      }
    },

    getCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      this.currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    formatDate(date) {
      if (!date) return ''
      return date.split(' ').length > 1 ? date.split(' ')[0] : date
    },

    formatDateTime(dateTime) {
      if (!dateTime) return ''
      return dateTime
    },

    formatDateForCalendar(dateTime) {
      if (!dateTime) return null
      
      try {
        let dateStr = dateTime
        
        if (dateStr.includes('/')) {
          const [datePart, timePart = '0:00:00'] = dateStr.split(' ')
          const dateParts = datePart.split('/')
          const timeParts = timePart.split(':')
          
          const year = dateParts[0]
          const month = String(dateParts[1]).padStart(2, '0')
          const day = String(dateParts[2]).padStart(2, '0')
          const hour = timeParts.length > 0 ? String(timeParts[0]).padStart(2, '0') : '00'
          const minute = timeParts.length > 1 ? String(timeParts[1]).padStart(2, '0') : '00'
          const second = timeParts.length > 2 ? String(timeParts[2]).padStart(2, '0') : '00'
          
          dateStr = `${year}-${month}-${day} ${hour}:${minute}:${second}`
        }
        
        if (dateStr.includes(' ')) {
          const [datePart, timePart] = dateStr.split(' ')
          const [year, month, day] = datePart.split('-')
          const [hour, minute, second] = timePart.split(':')
          
          const dateObj = new Date(year, month - 1, day, hour, minute, second)
          
          if (isNaN(dateObj.getTime())) {
            console.error('Invalid date after conversion:', dateStr)
            return null
          }
          
          return dateObj.toISOString()
        }
        
        const dateOnlyMatch = dateStr.match(/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})$/)
        if (dateOnlyMatch) {
          const year = dateOnlyMatch[1]
          const month = String(dateOnlyMatch[2]).padStart(2, '0')
          const day = String(dateOnlyMatch[3]).padStart(2, '0')
          const dateObj = new Date(year, month - 1, day, 9, 0, 0)
          
          if (isNaN(dateObj.getTime())) {
            console.error('Invalid date only:', dateStr)
            return null
          }
          
          return dateObj.toISOString()
        }
        
        console.error('Unrecognized date format:', dateTime)
        return null
      } catch (error) {
        console.error('Error parsing date:', dateTime, error)
        return null
      }
    },

    calculateEndTime(startTime, durationHours) {
      if (!startTime) return null
      
      const startDate = new Date(startTime)
      if (isNaN(startDate.getTime())) {
        console.error('Invalid start time for end calculation:', startTime)
        return null
      }
      
      const endDate = new Date(startDate.getTime() + (durationHours * 60 * 60 * 1000))
      return endDate.toISOString()
    },

    donehandleSizeChanges(val) {
      this.donepageCurrent = 1
      this.donepageSize = val
      this.donesearchTable()
    },

    donehandleCurrentChanges(val) {
      this.donepageCurrent = val
      this.donesearchTable()
    },

    donesearchTable() {
      this.loading = true
      this.donetableData = []
      const param = []

      if (this.Doing.length > 0 && this.station == '') {
        this.station = this.Doing.join(",")
      } else if (this.station != '' && this.station != '全部') {
        this.station = this.Doing.join(",")
      } else {
        this.station = '全部'
      }

      param.push(['订单号', this.doneorderNo || 0])
      param.push(['物料类型', '自制件'])
      param.push(['合同号', this.donecontractNo])
      param.push(['产品编码', this.doneproductCode])
      param.push(['产品名称', this.doneproductName])
      param.push(['工序名称', this.doneprocessName])
      param.push(['计划开始1', this.planStartTime[0] || ''])
      param.push(['计划开始2', this.planStartTime[1] || ''])
      param.push(['排产状态', this.doneproductionStatus])
      param.push(['指派对象', this.station])

      const Data = this.CreateData('11', 'MES_OrderPlanned_Queryzp', param, this.donepageSize, this.donepageCurrent)
      this.ExecDatabase(Data).then(response => {
        this.loading = false
        if (response.data.rows.length !== 0) {
          this.donetotal = response.data.total
          this.donetableData = response.data.rows.map(item => {
            if (item.计划开始时间 && !item.计划开始时间.includes(':')) {
              item.计划开始时间 = item.计划开始时间 + ' 09:00:00'
            }
            return item
          })
          
          if (this.doneactiveTab === 'doneschedule') {
            this.$nextTick(() => {
              this.loadCalendarEvents()
            })
          }
        }
      }).catch(() => {
        this.loading = false
      })
    },

    loadCalendarEvents() {
      // 防止重复加载
      if (this.isUpdatingEvents) return;
      
      const calendarApi = this.$refs.donefullCalendar?.getApi()
      if (calendarApi) {
        // 标记开始更新
        this.isUpdatingEvents = true;
        
        try {
          // 获取当前所有事件ID
          const existingEvents = calendarApi.getEvents();
          const existingEventIds = new Set(existingEvents.map(e => e.id));
          
          // 计算需要添加的事件
          const newEvents = this.donecalendarEvents.filter(event => 
            event && !existingEventIds.has(event.id)
          );
          
          // 计算需要删除的事件（在数据中不存在的事件）
          const currentEventIds = new Set(this.donecalendarEvents.filter(e => e).map(e => e.id));
          const eventsToRemove = existingEvents.filter(event => 
            !currentEventIds.has(event.id)
          );
          
          // 执行删除
          eventsToRemove.forEach(event => event.remove());
          
          // 执行添加
          newEvents.forEach(event => {
            try {
              calendarApi.addEvent(event);
            } catch (error) {
              console.warn('Error adding event:', error, event);
            }
          });
          
          // 更新现有事件的属性（如果时间有变化）
          this.donecalendarEvents.forEach(event => {
            if (!event) return;
            
            const existingEvent = calendarApi.getEventById(event.id);
            if (existingEvent) {
              // 检查事件时间是否发生了变化
              const existingStart = existingEvent.start?.toISOString();
              const existingEnd = existingEvent.end?.toISOString();
              const newStart = event.start;
              const newEnd = event.end;
              
              if (existingStart !== newStart || existingEnd !== newEnd) {
                try {
                  existingEvent.setDates(newStart, newEnd);
                } catch (error) {
                  console.warn('Error updating event dates:', error, event);
                }
              }
            }
          });
          
          // 更新日历大小
          setTimeout(() => {
            calendarApi.updateSize();
          }, 50);
          
        } catch (error) {
          console.error('Error loading calendar events:', error);
        } finally {
          // 标记更新完成
          setTimeout(() => {
            this.isUpdatingEvents = false;
          }, 100);
        }
      }
    },

    editstarTask(row) {
      if (!row.计划开始时间) {
        this.$message.error('计划开始时间不能为空')
        return
      }

      const params = []
      params.push(["editstr", `[计划开始时间] = '${row.计划开始时间}'`])
      params.push(["订单号", row.订单号])
      params.push(["订单行号", row.订单行号])
      params.push(["订单拆分内码", row.拆分内码])
      
      const Data = this.CreateData('12', 'MES_OrderPlanned_EditTaskPlanned', params)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result !== '1') {
          this.$message.error('修改失败')
          return
        }
        this.$message.success('修改成功')
        // 更新对应的事件
        this.updateSingleCalendarEvent(row);
      })
    },

    updateSingleCalendarEvent(row) {
      if (this.doneactiveTab === 'doneschedule') {
        const calendarApi = this.$refs.donefullCalendar?.getApi()
        if (calendarApi) {
          const eventId = `${row.订单号}-${row.订单行号}-${row.拆分内码}`
          const event = calendarApi.getEventById(eventId)
          
          if (event) {
            const newStart = this.formatDateForCalendar(row.计划开始时间)
            const newEnd = this.calculateEndTime(row.计划开始时间, row.标准工时)
            
            if (newStart && newEnd) {
              try {
                event.setDates(newStart, newEnd)
              } catch (error) {
                console.error('Error updating event:', error)
                // 如果更新失败，重新加载所有事件
                this.loadCalendarEvents()
              }
            }
          } else {
            // 如果事件不存在，重新加载所有事件
            this.loadCalendarEvents()
          }
        }
      }
    },

    // 切换视图
    changeView(viewName) {
      this.currentView = viewName
      const calendarApi = this.$refs.donefullCalendar?.getApi()
      if (calendarApi) {
        calendarApi.changeView(viewName)
        // 视图切换后重新渲染事件
        setTimeout(() => {
          this.loadCalendarEvents()
          calendarApi.updateSize()
        }, 100)
      }
    },

    // 回到今天
    goToday() {
      const calendarApi = this.$refs.donefullCalendar?.getApi()
      if (calendarApi) {
        calendarApi.today()
        setTimeout(() => {
          calendarApi.updateSize()
        }, 100)
      }
    },

    // 事件拖拽开始
    handleEventDragStart(info) {
      this.isDragging = true
      this.draggedEventId = info.event.id
      info.event.setProp('borderColor', '#ff9800')
    },

    // 事件拖拽结束
    handleEventDragStop(info) {
      this.isDragging = false
      const isPriority = info.event.extendedProps.优先级 === '是' || info.event.extendedProps.加急状态 === '加急'
      info.event.setProp('borderColor', isPriority ? '#f56c6c' : '#409EFF')
      this.draggedEventId = null
    },

    // 修复拖拽重复问题
    async handleEventDrop(info) {
      const event = info.event
      const { 订单号, 订单行号, 拆分内码, 标准工时 } = event.extendedProps
      
      // 获取新的开始时间
      const newStartDate = event.start
      if (!newStartDate) return
      
      // 格式化为 yyyy-MM-dd HH:mm:ss
      const newStartTime = this.formatDateForDisplay(newStartDate)
      
      // 查找对应的数据行
      const row = this.donetableData.find(item => 
        item.订单号 === 订单号 && 
        item.订单行号 === 订单行号 && 
        item.拆分内码 === 拆分内码
      )
      
      if (row) {
        const oldTime = row.计划开始时间
        
        try {
          // 直接更新后端，不先更新本地数据
          await this.updateTaskTime(订单号, 订单行号, 拆分内码, newStartTime)
          
          // 更新本地数据
          row.计划开始时间 = newStartTime
          
          // 只更新当前事件，避免重新加载导致重复
          const calendarApi = this.$refs.donefullCalendar?.getApi()
          if (calendarApi) {
            // 确保事件位置正确
            const newStart = this.formatDateForCalendar(newStartTime)
            const newEnd = this.calculateEndTime(newStartTime, 标准工时)
            
            if (newStart && newEnd) {
              try {
                event.setDates(newStart, newEnd)
              } catch (error) {
                console.error('Error setting event dates:', error)
              }
            }
          }
          
          this.$message.success('拖拽修改成功')
          
        } catch (error) {
          // 失败后恢复事件到原位置
          row.计划开始时间 = oldTime
          const oldStart = this.formatDateForCalendar(oldTime)
          const oldEnd = this.calculateEndTime(oldTime, 标准工时)
          
          if (oldStart && oldEnd) {
            event.setDates(oldStart, oldEnd)
          }
          
          this.$message.error('拖拽修改失败')
        }
      }
    },

    // 更新任务时间
    updateTaskTime(订单号, 订单行号, 拆分内码, newStartTime) {
      return new Promise((resolve, reject) => {
        const params = []
        params.push(["editstr", `[计划开始时间] = '${newStartTime}'`])
        params.push(["订单号", 订单号])
        params.push(["订单行号", 订单行号])
        params.push(["订单拆分内码", 拆分内码])
        
        const Data = this.CreateData('12', 'MES_OrderPlanned_EditTaskPlanned', params)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result !== '1') {
            reject(new Error('修改失败'))
            return
          }
          resolve()
        }).catch(reject)
      })
    },

    // 事件调整大小回调
    async handleEventResize(info) {
      const event = info.event
      const { 订单号, 订单行号, 拆分内码 } = event.extendedProps
      
      // 获取新的结束时间
      const newEndDate = event.end
      if (!newEndDate) return
      
      // 计算新的工时（小时）
      const startDate = event.start
      if (!startDate) return
      
      const durationMs = newEndDate.getTime() - startDate.getTime()
      const newDurationHours = Math.round(durationMs / (1000 * 60 * 60) * 10) / 10
      
      // 查找对应的数据行
      const row = this.donetableData.find(item => 
        item.订单号 === 订单号 && 
        item.订单行号 === 订单行号 && 
        item.拆分内码 === 拆分内码
      )
      
      if (row) {
        const oldDuration = row.标准工时
        
        try {
          await this.updateTaskDuration(订单号, 订单行号, 拆分内码, newDurationHours)
          
          // 更新本地数据
          row.标准工时 = newDurationHours.toString()
          
          this.$message.success('工时调整成功')
          
        } catch (error) {
          // 失败后恢复
          row.标准工时 = oldDuration
          
          // 恢复事件大小
          const oldEnd = new Date(startDate.getTime() + (oldDuration * 60 * 60 * 1000))
          event.setDates(startDate, oldEnd)
          
          this.$message.error('工时调整失败')
        }
      }
    },

    updateTaskDuration(订单号, 订单行号, 拆分内码, duration) {
      return new Promise((resolve, reject) => {
        const params = []
        params.push(["editstr", `[标准工时] = '${duration}'`])
        params.push(["订单号", 订单号])
        params.push(["订单行号", 订单行号])
        params.push(["订单拆分内码", 拆分内码])
        
        const Data = this.CreateData('12', 'MES_OrderPlanned_EditTaskPlanned', params)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result !== '1') {
            reject(new Error('修改工时失败'))
            return
          }
          resolve()
        }).catch(reject)
      })
    },

    formatDateForDisplay(date) {
      if (!date) return ''
      const d = new Date(date)
      if (isNaN(d.getTime())) return ''
      
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hours = String(d.getHours()).padStart(2, '0')
      const minutes = String(d.getMinutes()).padStart(2, '0')
      const seconds = String(d.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    // 点击事件查看详情
    handleEventClick(info) {
      const event = info.event
      const taskInfo = event.extendedProps
      
      this.$alert(`
        <div style="text-align: left;">
          <p><strong>订单号:</strong> ${taskInfo.订单号}</p>
          <p><strong>指派对象:</strong> ${taskInfo.指派对象}</p>
          <p><strong>计划数量:</strong> ${taskInfo.计划数量}</p>
          <p><strong>标准工时:</strong> ${taskInfo.标准工时}小时</p>
          <p><strong>开始时间:</strong> ${this.formatDateTimeDisplay(event.start)}</p>
          <p><strong>结束时间:</strong> ${this.formatDateTimeDisplay(event.end)}</p>
        </div>
      `, '任务详情', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '关闭',
        callback: () => { }
      })
    },

    formatDateTimeDisplay(date) {
      if (!date) return ''
      const d = new Date(date)
      if (isNaN(d.getTime())) return ''
      
      return d.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-')
    },

    handleRowClick(row) {
      this.selectedRow = row
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    donetableRowClassName({ row }) {
      const isUrgent = row.优先级 === '是' || row.加急状态 === '加急';
      if (isUrgent) {
        return 'priority-row';
      }
      return '';
    }
  }
}
</script>

<style scoped>
.priority-row {
  background-color: #f56c6c !important;
  color: #000000 !important;
}

::v-deep .priority-row td {
  background-color: #f56c6c !important;
  color: #000000 !important;
  border: #f56c6c;
}

.show-text {
  margin-right: 5px;
  line-height: 32px;
}

.show-head {
  margin-right: 5px;
  line-height: 32px;
  font-size: 15px;
}

.custom-tabs {
  margin-top: 20px;
}

.schedule-container {
  min-height: 70vh;
  display: flex;
  flex-direction: column;
}

.calendar-wrapper {
  flex: 1;
  min-height: 600px;
  position: relative;
}

.calendar-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 0 10px;
  background: #f5f7fa;
  border-radius: 4px;
  padding: 10px;
}

.calendar-header .el-button-group {
  margin-right: 10px;
}

.calendar-header .el-button {
  min-width: 60px;
}

/* 日历自适应高度的关键样式 */
.schedule-container ::v-deep .fc {
  font-size: 13px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

/* 周/日视图时间槽高度自适应 - 关键修改 */
.schedule-container ::v-deep .fc-timegrid-slot {
  height: auto !important;
  min-height: 30px !important; /* 设置最小高度 */
  max-height: 80px !important; /* 设置最大高度 */
}

.schedule-container ::v-deep .fc-timegrid-slot-lane {
  height: 100% !important;
}

/* 实现纵向排列 - 关键修改 */
.schedule-container ::v-deep .fc-timegrid-col-events {
  position: relative !important;
}

.schedule-container ::v-deep .fc-timegrid-event-harness {
  position: relative !important;
  margin: 2px 0 !important; /* 纵向间距 */
}

.schedule-container ::v-deep .fc-timegrid-event {
  position: relative !important;
  margin: 0 !important;
  width: 100% !important;
}

/* 确保事件像月视图一样纵向排列 */
.schedule-container ::v-deep .fc-timegrid-col {
  position: relative;
}

.schedule-container ::v-deep .fc-timegrid-col-frame {
  position: relative;
  height: auto !important;
}

/* 时间轴样式 */
.schedule-container ::v-deep .fc-timegrid-axis {
  width: 60px !important;
  min-width: 60px !important;
}

/* 事件样式优化 */
.schedule-container ::v-deep .fc-event {
  font-size: 12px;
  padding: 3px 5px;
  margin: 1px 0; /* 纵向间距 */
  min-height: 24px;
  line-height: 1.4;
  border-radius: 3px;
  cursor: move;
  border-left-width: 4px !important;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  transition: all 0.2s ease;
  overflow: hidden;
}

.schedule-container ::v-deep .fc-event:hover {
  box-shadow: 0 2px 6px rgba(0,0,0,0.15);
  transform: translateY(-1px);
}

.schedule-container ::v-deep .fc-event-title {
  font-size: 11px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
}

/* 拖拽样式 */
.schedule-container ::v-deep .fc-event-dragging {
  opacity: 0.8;
  box-shadow: 0 4px 12px rgba(0,0,0,0.2) !important;
  z-index: 9999 !important;
}

/* 移除更多链接 */
.schedule-container ::v-deep .fc-daygrid-more-link {
  display: none;
}

::v-deep .el-table__fixed {
  height: auto !important;
  bottom: 12px !important;
}

/* 优先级事件样式 */
.schedule-container ::v-deep .priority-event {
  border-left-color: #ff0000 !important;
  background: linear-gradient(135deg, #f56c6c 0%, #ff8c8c 100%) !important;
}

/* 普通事件样式 */
.schedule-container ::v-deep .normal-event {
  border-left-color: #409EFF !important;
  background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%) !important;
}

/* 月视图事件样式优化 */
.schedule-container ::v-deep .fc-daygrid-event {
  font-size: 11px;
  padding: 2px 4px;
  margin: 1px 0;
  min-height: 20px !important;
}

/* 确保容器自适应 */
.schedule-container ::v-deep .fc-view-harness {
  flex: 1;
  min-height: 500px;
}

.schedule-container ::v-deep .fc-view-harness-active {
  height: 100% !important;
}

/* 列标题样式 */
.schedule-container ::v-deep .fc-col-header-cell {
  padding: 8px 4px !important;
}

.schedule-container ::v-deep .fc-col-header-cell-cushion {
  font-size: 13px;
  font-weight: 500;
}

/* 滚动条样式 */
.schedule-container ::v-deep .fc-scroller::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.schedule-container ::v-deep .fc-scroller::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.schedule-container ::v-deep .fc-scroller::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.schedule-container ::v-deep .fc-scroller::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式调整 */
@media (max-height: 800px) {
  .schedule-container {
    min-height: 60vh;
  }
  
  .calendar-wrapper {
    min-height: 450px;
  }
  
  .schedule-container ::v-deep .fc-timegrid-slot {
    min-height: 40px !important;
    max-height: 60px !important;
  }
  
  .schedule-container ::v-deep .fc-event {
    font-size: 11px;
    padding: 2px 4px;
    min-height: 20px;
  }
}

/* 小屏幕适配 */
@media (max-width: 768px) {
  .schedule-container ::v-deep .fc-timegrid-axis {
    width: 50px !important;
    min-width: 50px !important;
  }
  
  .schedule-container ::v-deep .fc-event-title {
    font-size: 10px;
  }
}
</style>