<template>
  <div class="workstation-plan-page">
    <el-card>
      <div class="search-container" @keyup.enter="donesearchTable">
        <span class="show-head">工位排产</span>
        <span class="show-text">生产订单:</span>
        <el-input v-model="doneorderNo" placeholder="请输入生产订单" clearable style="width: 150px;margin-right: 10px"  clear/>
        <span class="show-text">销售订单:</span>
        <el-input v-model="donecontractNo" placeholder="请输入销售订单" clearable style="width: 150px;margin-right: 10px" clear/>
        <span class="show-text">物料编码:</span>
        <el-input v-model="doneproductCode" placeholder="请输入物料编码" clearable style="width: 150px;margin-right: 10px" clear/>
        <span class="show-text">物料名称:</span>
        <el-input v-model="doneproductName" placeholder="请输入物料名称" clearable style="width: 150px;margin-right: 10px" clear/>
        <span class="show-text">工序名称:</span>
        <el-input v-model="doneprocessName" placeholder="请输入工序名称" clearable style="width: 150px;margin-right: 10px" clear/>
        <br>
        <br>
        <span class="show-text">要求完工日期:</span>
        <el-date-picker
          v-model="completionTime"
          
          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-date-picker
          v-model="planStartTime"
          
          placeholder="计划开始时间"
          style="width: 150px;vertical-align: top"
          type="date"
          value-format="yyyy-MM-dd" />
        <span class="show-text">计划完成:</span>
        <el-date-picker
          v-model="planendTime"
          
          placeholder="计划完成时间"
          style="width: 150px;vertical-align: top"
          type="date"
          value-format="yyyy-MM-dd" />
        <el-button :disabled="loading" icon="el-icon-search" plain type="primary" @click="donesearchTable()">查询</el-button>
      </div>

      <el-checkbox-group v-model="Doing" class="station-checks" @change="Doingform">
        <el-checkbox v-for="item in Doingoptions" :key="item.工位号" :label="item.指南工位号" :value="item.工位号" />
      </el-checkbox-group>

      <el-tabs v-model="doneactiveTab" class="custom-tabs">
        <el-tab-pane label="工位排产" name="form">
          <div v-loading="loading" class="station-board" element-loading-background="rgba(255, 255, 255, 0.65)">
            <el-empty v-if="workstationGroups.length === 0" description="暂无排产任务" />
            <div v-else class="station-table-wrap">
              <table class="station-table">
                <thead>
                  <tr>
                    <th class="col-tree">工位 / 日期</th>
                    <!-- <th class="col-num">排产数量</th> -->
                    <th class="col-hours">标准工时</th>
                    <th class="col-settlement-hours">结算工时</th>
                    <th class="col-settlement-piece">结算单件工时</th>
                    <th class="col-order">生产订单</th>
                    <th class="col-plan">计划号</th>
                    <th class="col-contract">销售订单</th>
                    <th class="col-code">物料编码</th>
                    <th class="col-name">物料名称</th>
                    <th class="col-plan-num">计划数</th>
                    <th class="col-date">要求完工日期</th>
                    <th class="col-process">工序名称</th>
                    <th class="col-station">指派对象</th>
                    <th class="col-date">计划开始</th>
                    <th class="col-date">计划完成</th>
                    <th class="col-date">最晚开始</th>
                    <th class="col-personnel">二次派工</th>
                    <th class="col-priority">优先级</th>
                    <th class="col-text">未完成说明</th>
                    <th class="col-text">派工特殊备注</th>
                    <th class="col-group">外协分组</th>
                    <th class="col-text">占用情况</th>
                    <th class="col-user">最后编辑人</th>
                    <th class="col-time">最后编辑时间</th>
                    <th class="col-actions">操作</th>
                  </tr>
                </thead>
                <tbody>
                  <template v-for="stationGroup in workstationGroups">
                    <tr
                      :key="`station-${stationGroup.station}`"
                      class="summary-row station-row"
                      @click="toggleStation(stationGroup.station)">
                      <td class="tree-cell">
                        <i :class="isStationExpanded(stationGroup.station) ? 'el-icon-arrow-down' : 'el-icon-arrow-right'" class="group-arrow"></i>
                        <span>{{ stationGroup.station }}</span>
                      </td>
                      <!-- <td>{{ stationGroup.totalQuantity }}</td> -->
                      <td>{{ stationGroup.totalHours }}</td>
                      <td>{{ stationGroup.totalSettlementHours }}</td>
                      <td></td>
                      <td colspan="21"></td>
                    </tr>
                    <template v-for="dateGroup in stationGroup.dates">
                      <tr
                        v-show="isStationExpanded(stationGroup.station)"
                        :key="`date-${stationGroup.station}-${dateGroup.date}`"
                        class="summary-row date-row"
                        @click="toggleDate(stationGroup.station, dateGroup.date)">
                        <td class="tree-cell">
                          <i :class="isDateExpanded(stationGroup.station, dateGroup.date) ? 'el-icon-arrow-down' : 'el-icon-arrow-right'" class="group-arrow date-arrow"></i>
                          <span>{{ dateGroup.date }}</span>
                        </td>
                        <!-- <td>{{ dateGroup.totalQuantity }}</td> -->
                        <td>{{ dateGroup.totalHours }}</td>
                        <td>{{ dateGroup.totalSettlementHours }}</td>
                        <td></td>
                        <td colspan="21"></td>
                      </tr>
                      <tr
                        v-show="isStationExpanded(stationGroup.station) && isDateExpanded(stationGroup.station, dateGroup.date)"
                        v-for="task in dateGroup.tasks"
                        :key="`task-${task.订单号}-${task.订单行号}-${task.拆分内码}`"
                        class="task-row"
                        :class="{ 'is-priority': task.优先级 === '是' || task.加急状态 === '加急' }"
                        @click="handleRowClick(task)">
                        <td></td>
                        <!-- <td class="number-cell">{{ task.指派数量 || task.计划数量 }}</td> -->
                        <td class="number-cell">{{ calcStandardHours(task) }}</td>
                        <td class="number-cell">{{ calcSettlementHours(task) }}</td>
                        <td class="number-cell" @click.stop>
                          <el-button
                            type="text"
                            size="mini"
                            class="work-hour-button"
                            @click="openWorkHourDialog(task)">
                            {{ hasValue(task.结算单件工时) ? formatNumber(task.结算单件工时) : '选择' }}
                          </el-button>
                        </td>
                        <td>{{ task.订单号 }}</td>
                        <td>{{ task.计划号 }}</td>
                        <td>{{ task.合同号 }}</td>
                        <td>{{ task.产品编码 }}</td>
                        <td class="name-cell">
                          <span>{{ task.产品名称 }}</span>
                          <el-tag v-if="task.优先级 === '是' || task.加急状态 === '加急'" type="danger" size="mini">加急</el-tag>
                        </td>
                        <td class="number-cell">{{ task.计划数量 }}</td>
                        <td>{{ formatDate(task.要求完工日期) }}</td>
                        <td>{{ task.工序名称 }}</td>
                        <td @click.stop>
                          <el-select
                            v-model="task.指派对象"
                            filterable
                            size="mini"
                            class="compact-select"
                            placeholder="请选择"
                            @focus="handleRowClick(task)"
                            @change="editdomTask">
                            <el-option
                              v-for="item in stationOptions"
                              :key="item.code"
                              :label="item.label"
                              :value="item.value" />
                          </el-select>
                        </td>
                        <td @click.stop>
                          <el-date-picker
                            v-model="task.计划开始时间"
                            type="date"
                            size="mini"
                            class="compact-date"
                            value-format="yyyy-MM-dd"
                            @focus="handleRowClick(task)"
                            @change="editstarTask" />
                        </td>
                        <td @click.stop>
                          <el-date-picker
                            v-model="task.计划完成时间"
                            type="date"
                            size="mini"
                            class="compact-date"
                            value-format="yyyy-MM-dd"
                            @focus="handleRowClick(task)"
                            @change="editendTask" />
                        </td>
                        <td @click.stop>
                          <el-date-picker
                            v-model="task.最晚开始时间"
                            type="date"
                            size="mini"
                            class="compact-date"
                            value-format="yyyy-MM-dd"
                            @focus="handleRowClick(task)"
                            @change="editlateTask" />
                        </td>
                        <td @click.stop>
                          <el-select
                            v-model="task.二次派工"
                            filterable
                            multiple
                            collapse-tags
                            size="mini"
                            class="compact-personnel"
                            placeholder="请选择"
                            @change="doneeditpersonnel(task)">
                            <el-option
                              v-for="item in personnelOptions"
                              :key="item.code"
                              :label="item.label"
                              :value="item.value" />
                          </el-select>
                        </td>
                        <td class="tag-cell">
                          <el-tag :type="task.优先级 === '是' ? 'warning' : 'info'" size="mini">{{ task.优先级 }}</el-tag>
                        </td>
                        <td>{{ task.未完成说明 }}</td>
                        <td>{{ task.派工特殊说明 }}</td>
                        <td @click.stop>
                          <el-input
                            v-model="task.外协分组"
                            size="mini"
                            class="compact-group"
                            placeholder="外协分组"
                            @focus="handleRowClick(task)"
                            @change="savegroup" />
                        </td>
                        <td>{{ task.占用情况 }}</td>
                        <td>{{ task.最后编辑人 }}</td>
                        <td>{{ task.最后编辑时间 }}</td>
                        <td class="action-cell" @click.stop>
                          <el-button type="text" size="mini" @click="getitemdata(task.订单号)">原料</el-button>
                          <el-button type="text" size="mini" @click="editRemark(task)">编辑</el-button>
                        </td>
                      </tr>
                    </template>
                  </template>
                </tbody>
              </table>
            </div>
          </div>
        </el-tab-pane>

        <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" />

        <el-tab-pane label="日程" name="doneschedule">
          <div class="schedule-container">
            <FullCalendar ref="donefullCalendar" :options="donecalendarOptions" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 编辑备注弹窗 -->
    <el-dialog
      :visible.sync="remarkDialogVisible"
      title="编辑备注信息"
      width="600px"
      center>
      <el-form
        ref="remarkForm"
        :model="remarkForm"
        label-width="140px"
        size="mini">
        <el-form-item label="优先级">
          <el-select v-model="remarkForm.优先级" placeholder="请选择优先级" style="width: 100%">
            <el-option label="是" value="是"/>
            <el-option label="否" value="否"/>
          </el-select>
        </el-form-item>
        <el-form-item label="未完成说明">
          <el-input
            v-model="remarkForm.未完成说明"
            :rows="2"
            type="textarea"
            placeholder="请输入未完成说明"/>
        </el-form-item>
        <el-form-item label="派工特殊备注">
          <el-input
            v-model="remarkForm.派工特殊说明"
            :rows="3"
            type="textarea"
            placeholder="请输入派工特殊备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="remarkDialogVisible = false">取 消</el-button>
        <el-button
          :loading="remarkSubmitLoading"
          type="primary"
          @click="submitRemark">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogcasual" title="原料信息" center style="min-height: 300px;" width="1400px">
        <el-card style="height: 550px">
          <el-table
            :data="itemdata"
            :height="'55vh'"
            border
            size="mini"
            style="margin-top: 20px; width: 95%;"
            >
            <el-table-column align="center" label="序号" type="index" width="50"  />
            <el-table-column align="center" prop="子件编码" label="物料编码" width="220" />
            <el-table-column align="center" prop="子件名称" label="物料名称" width="190" />
            <el-table-column align="center" prop="基本数量" label="基本数量" width="100" />
            <el-table-column align="center" prop="待出数量" label="待出数量" width="100" />
            <el-table-column align="center" prop="拣配数量" label="拣配数量" width="100" />
            <el-table-column align="center" prop="计划数量" label="计划数量" width="100" />
            <el-table-column align="center" prop="存货量" label="存货量" width="80" />
            <el-table-column align="center" prop="材质" label="材质" width="80" />
          </el-table>
        </el-card>
    </el-dialog>
    <el-dialog :visible.sync="dialogcasual2" title="历史工时" center style="min-height: 300px;" width="1400px">
        <el-card style="height: 550px">
          <el-table
            v-loading="workHourLoading"
            :data="workHourData"
            :height="'55vh'"
            border
            size="mini"
            style="margin-top: 20px; width: 95%;">
            <el-table-column label="选择" width="120" align="center" fixed>
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="mini"
                  :disabled="!canSelectHistoryHour(scope.row.settlementReportPieceHours)"
                  @click="selectSettlementPieceHour(scope.row, 'report')">报工</el-button>
                <el-button
                  type="text"
                  size="mini"
                  :disabled="!canSelectHistoryHour(scope.row.settlementAuxiliaryPieceHours)"
                  @click="selectSettlementPieceHour(scope.row, 'auxiliary')">辅助</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="taskDescription" label="任务描述" min-width="380" show-overflow-tooltip>
              <template slot-scope="scope">
                <span :class="{ 'bold-text': scope.row.level === 1 }">{{ scope.row.taskDescription || '' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="settlementReportPieceHours" label="结算报工单件工时" width="140" align="center">
              <template slot-scope="scope">
                {{ formatHistoryPieceHours(scope.row.settlementReportPieceHours) }}
              </template>
            </el-table-column>
            <el-table-column prop="settlementAuxiliaryPieceHours" label="结算辅助单件工时" width="140" align="center">
              <template slot-scope="scope">
                {{ formatHistoryPieceHours(scope.row.settlementAuxiliaryPieceHours) }}
              </template>
            </el-table-column>
            <el-table-column prop="station" label="工位" width="110" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.station || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="productionOrderNo" label="生产订单号" width="130" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.productionOrderNo || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="operatorNames" label="操作人" width="180" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.operatorNames || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="reportWorkHours" label="报工工时" width="100" align="center">
              <template slot-scope="scope">
                <span :class="{ 'bold-text': scope.row.level <= 2 }">{{ scope.row.reportWorkHours || '' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="auxiliaryWorkHours" label="辅助工时" width="100" align="center">
              <template slot-scope="scope">
                <span :class="{ 'bold-text': scope.row.level <= 2 }">{{ scope.row.auxiliaryWorkHours || '' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="reportFinishQty" label="报工完成数" width="110" align="center">
              <template slot-scope="scope">
                <span :class="{ 'bold-text': scope.row.level <= 2 }">{{ scope.row.reportFinishQty || '' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="auxiliaryFinishQty" label="辅助完成数" width="110" align="center">
              <template slot-scope="scope">
                <span :class="{ 'bold-text': scope.row.level <= 2 }">{{ scope.row.auxiliaryFinishQty || '' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="totalWorkHours" label="合计工时" width="100" align="center">
              <template slot-scope="scope">
                <span :class="{ 'bold-text': scope.row.level <= 2 }">{{ scope.row.totalWorkHours || '' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="clampingTime" label="装夹时间" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.clampingTime || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="programTime" label="调程时间" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.programTime || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="recordCount" label="记录数" width="90" align="center">
              <template slot-scope="scope">
                <span :class="{ 'bold-text': scope.row.level <= 2 }">{{ scope.row.recordCount || '' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
    </el-dialog>
    
  </div>
</template>


<script>
// 这三个组件用于绘制日历
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from '@fullcalendar/interaction'
import { patchB1 } from '@/api/b1s';
import { postB1 } from '@/api/b1s';
export default {
  components: { FullCalendar },
  data() {
    return {
      dialogcasual:false,
      activeTab: 'form',
      doneactiveTab: 'form',
      orderNo: '',
      contractNo: '',
      productCode: '',
      productName: '',
      processName: '',
      nature: '',
      productionStatus: '未完成',
      donecontractNo: '',
      doneorderNo: '',
      doneproductCode: '',
      doneproductName: '',
      doneprocessName: '',
      donenature: '',
      doneproductionStatus: '已完成',
      Doing:[],
      Doingoptions:[],
      station:'全部',
      completids:[],
      completionTime: [],
      planStartTime: '',
      planendTime: '',
      loading: false,
      tableData: [],
      donetableData: [],
      expandedStations: {},
      expandedDates: {},

      multipleSelection: [],
      dialogVisible: false,
      submitLoading: false,
      currentRow: {},
      stationOptions: [],
      
      selectedRow: null,
      editnumber:0,
      groupnumber:0,
      submitstatus:0,
      formData: {
        指派对象: '',
        指派对象编号: '',
        指派数量: 0,
        计划开始时间: '',
        计划完成时间: '',
        最晚开始时间: '',
        派工特殊说明: ''
      },
      remarkDialogVisible: false,
      remarkSubmitLoading: false,
      remarkForm: {
        优先级: '',
        未完成说明: '',
        派工特殊说明: ''
      
      
      },

      personnelOptions: [],
      personnel:[],

      // 分页
      total: 0, // 分页总数
      pageCurrent: 1, // 分页当前页
      pageSize: 100, // 分页每页显示条数

      donetotal: 0, // 分页总数
      donepageCurrent: 1, // 分页当前页
      donepageSize: 100, // 分页每页显示条数
      // FullCalendar 配置选项
      calendarOptions: {
        plugins: [dayGridPlugin, interactionPlugin], // 加载日视图和交互插件
        initialView: 'dayGridMonth',
        locale: 'zh-cn',
        headerToolbar: {
          left: 'prev,next today',
          center: 'title',
          right: 'today'
        },
        editable: true, // 允许通过拖拽或调整大小来修改事件
        droppable: true,
        events: [],
        eventDrop: this.handleEventDrop, // 拖拽完成后回调
        eventResize: this.handleEventResize, // 调整大小完成后回调
        eventClick:this.handleEventClick,
        height: 'auto', // 设置高度为auto，使其自适应内容
        dayMaxEvents: true // 限制每天显示的事件数量
      },
      donecalendarOptions: {
        plugins: [dayGridPlugin, interactionPlugin], // 加载日视图和交互插件
        initialView: 'dayGridMonth',
        locale: 'zh-cn',
        headerToolbar: {
          left: 'prev,next today',
          center: 'title',
          right: 'today'
        },
        editable: true, // 允许通过拖拽或调整大小来修改事件
        droppable: true,
        events: [],
        eventDrop: this.handleEventDrop, // 拖拽完成后回调
        eventResize: this.handleEventResize, // 调整大小完成后回调
        eventClick:this.handleEventClick,
        height: 'auto', // 设置高度为auto，使其自适应内容
        dayMaxEvents: true, // 限制每天显示的事件数量
        eventDidMount: (info) => {
          info.el.style.minHeight = '40px'
          info.el.style.height = '40px'
          info.el.style.lineHeight = '40px'
        }
      },
      currentTime: "",
      itemdata:[],
      dialogcasual2:false,
      workHourData:[],
      workHourLoading:false,
      workHourCurrentRow:null
    }
  },
  computed: {
    workstationGroups() {
      const rows = Array.isArray(this.donetableData) ? this.donetableData : []
      const stationMap = new Map()
      const getTime = value => {
        if (!value || value === '未排日期') return Number.MAX_SAFE_INTEGER
        const normalized = String(value).split(' ')[0].replace(/\//g, '-')
        const time = new Date(normalized).getTime()
        return Number.isNaN(time) ? Number.MAX_SAFE_INTEGER : time
      }

      rows.forEach(task => {
        const station = task.指派对象 || '未指派'
        const planDate = this.formatDate(task.计划开始时间) || '未排日期'
        const hours = Number(task.标准工时) || 0
        const settlementPieceHours = Number(task.结算单件工时)
        const hasSettlementHours = this.hasValue(task.结算单件工时) && !Number.isNaN(settlementPieceHours)

        if (!stationMap.has(station)) {
          stationMap.set(station, {
            station,
            totalCount: 0,
            totalQuantity: 0,
            totalHours: 0,
            totalSettlementHours: 0,
            settlementHoursCount: 0,
            dateMap: new Map()
          })
        }

        const stationGroup = stationMap.get(station)
        const quantity = Number(task.指派数量 || task.计划数量) || 0
        stationGroup.totalCount += 1
        stationGroup.totalQuantity += quantity
        stationGroup.totalHours += hours*quantity
        if (hasSettlementHours) {
          stationGroup.totalSettlementHours += settlementPieceHours * quantity
          stationGroup.settlementHoursCount += 1
        }

        if (!stationGroup.dateMap.has(planDate)) {
          stationGroup.dateMap.set(planDate, {
            date: planDate,
            totalQuantity: 0,
            totalHours: 0,
            totalSettlementHours: 0,
            settlementHoursCount: 0,
            tasks: []
          })
        }

        const dateGroup = stationGroup.dateMap.get(planDate)
        dateGroup.totalQuantity += quantity
        dateGroup.totalHours += hours*quantity
        if (hasSettlementHours) {
          dateGroup.totalSettlementHours += settlementPieceHours * quantity
          dateGroup.settlementHoursCount += 1
        }
        dateGroup.tasks.push(task)
      })

      return Array.from(stationMap.values()).map(stationGroup => {
        const dates = Array.from(stationGroup.dateMap.values())
          .sort((a, b) => getTime(a.date) - getTime(b.date))
          .map(dateGroup => ({
            ...dateGroup,
            totalQuantity: dateGroup.totalQuantity,
            totalHours: Number(dateGroup.totalHours.toFixed(2)),
            totalSettlementHours: dateGroup.settlementHoursCount > 0 ? Number(dateGroup.totalSettlementHours.toFixed(2)) : '',
            tasks: dateGroup.tasks.sort((a, b) => getTime(a.计划开始时间) - getTime(b.计划开始时间))
          }))

        return {
          station: stationGroup.station,
          totalCount: stationGroup.totalCount,
          totalQuantity: stationGroup.totalQuantity,
          totalHours: Number(stationGroup.totalHours.toFixed(2)),
          totalSettlementHours: stationGroup.settlementHoursCount > 0 ? Number(stationGroup.totalSettlementHours.toFixed(2)) : '',
          dates
        }
      })
    },
    calendarEvents() {
      return this.tableData.map(item => {
        const isPriority = item.优先级 === '是'

        return {
          id: `${item.订单号}-${item.订单行号}-${item.拆分内码}`,
          title: `${item.订单号} | ${item.产品名称} | ${item.指派对象} | ${item.计划数量}`,
          start: this.formatDateForCalendar(this.formatDate2(item.计划开始时间)),
          end: this.formatDateForCalendar(this.formatDate2(item.计划完成时间), true),
          extendedProps: {
            订单号: item.订单号,
            订单行号: item.订单行号,
            拆分内码: item.拆分内码,
            指派对象: item.指派对象,
            计划数量: item.计划数量,
            优先级: item.优先级
          },
          backgroundColor: isPriority ? '#f56c6c' : '#409EFF', // 优先级高为红色，普通为蓝色
          borderColor: isPriority ? '#f56c6c' : '#409EFF',
          textColor: isPriority ? '#fff' : '#fff', // 白色文字
          classNames: isPriority ? ['priority-event'] : ['normal-event'],
          
        }
      })
    },
    donecalendarEvents() {
      return this.donetableData.map(item => {
        const isPriority = item.优先级 === '是'

        return {
          id: `${item.订单号}-${item.订单行号}-${item.拆分内码}`,
          title: `${item.订单号} | ${item.产品名称} | ${item.产品编码} | ${item.指派对象} | ${item.计划数量} | ${item.完成数量} `,
          start: this.formatDateForCalendar(this.formatDate2(item.计划开始时间)),
          end: this.formatDateForCalendar(this.formatDate2(item.计划完成时间), true),
          extendedProps: {
            订单号: item.订单号,
            订单行号: item.订单行号,
            拆分内码: item.拆分内码,
            指派对象: item.指派对象,
            计划数量: item.计划数量,
            优先级: item.优先级,
            产品编码:item.产品编码
          },
          backgroundColor: isPriority ? '#f56c6c' : '#409EFF', // 优先级高为红色，普通为蓝色
          borderColor: isPriority ? '#f56c6c' : '#409EFF',
          textColor: isPriority ? '#fff' : '#fff', // 白色文字
          classNames: isPriority ? ['priority-event'] : ['normal-event']
        }
      })
    }
  },
  watch: {
    activeTab(newVal) {
      if (newVal === 'schedule') {
        this.$nextTick(() => {
          // 判断日历的HTML Dom 是否存在
          const calendarApi = this.$refs.fullCalendar && this.$refs.fullCalendar.getApi()
          if (calendarApi) {
            // 重新绘制日历界面 避免出现未渲染问题
            calendarApi.updateSize()
          }
          this.calendarOptions.events = this.calendarEvents
        })
      }
      
    },
    doneactiveTab(newVal) {
      if (newVal === 'doneschedule') {
        this.$nextTick(() => {
          // 判断日历的HTML Dom 是否存在
          const calendarApi = this.$refs.donefullCalendar && this.$refs.donefullCalendar.getApi()
          if (calendarApi) {
            // 重新绘制日历界面 避免出现未渲染问题
            calendarApi.updateSize()
          }
          this.donecalendarOptions.events = this.donecalendarEvents
        })
      }
    },
    tableData: {
      handler() {
        if (this.activeTab === 'schedule') {
          this.calendarOptions.events = this.calendarEvents
          this.$nextTick(() => {
            const calendarApi = this.$refs.fullCalendar && this.$refs.fullCalendar.getApi()
            if (calendarApi) {
              calendarApi.refetchEvents()
            }
          })
        }
        
      },
      deep: true
    },
    donetableData: {
      handler() {
        
        if (this.doneactiveTab === 'doneschedule') {
          this.donecalendarOptions.events = this.donecalendarEvents
          this.$nextTick(() => {
            const calendarApi = this.$refs.donefullCalendar && this.$refs.donefullCalendar.getApi()
            if (calendarApi) {
              calendarApi.refetchEvents()
            }
          })
        }
      },
      deep: true
    }
  },
  created() {
    var now = new Date()
    var start = new Date(Date.UTC(now.getFullYear() - 1, now.getMonth(), now.getDate(), 0, 0, 0)).toISOString().replace('T', ' ').replace('.000Z', '')
    var end = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)).toISOString().replace('T', ' ').replace('.000Z', '')
    // this.completionTime = [start, end]
    this.getDoing()
    this.getStationList()
    this.getcompletids()
    this.getpersonnelList()
    this.getCurrentTime();
    setInterval(this.getCurrentTime, 1000);
  },
  methods: {
    stationDateKey(station, date) {
      return `${station}__${date}`
    },
    isStationExpanded(station) {
      return this.expandedStations[station] !== false
    },
    isDateExpanded(station, date) {
      return this.expandedDates[this.stationDateKey(station, date)] !== false
    },
    toggleStation(station) {
      this.$set(this.expandedStations, station, !this.isStationExpanded(station))
    },
    toggleDate(station, date) {
      const key = this.stationDateKey(station, date)
      this.$set(this.expandedDates, key, !this.isDateExpanded(station, date))
    },
    hasValue(value) {
      return value !== null && value !== undefined && value !== ''
    },
    formatNumber(value) {
      if (!this.hasValue(value)) return ''
      const number = Number(value)
      if (Number.isNaN(number)) return value
      return Number(number.toFixed(2))
    },
    getTaskQuantity(task) {
      return Number(task.指派数量 || task.计划数量) || 0
    },
    calcStandardHours(task) {
      const hours = Number(task.标准工时) || 0
      return Number((hours * this.getTaskQuantity(task)).toFixed(2))
    },
    calcSettlementHours(task) {
      if (!this.hasValue(task.结算单件工时)) return ''
      const pieceHours = Number(task.结算单件工时)
      if (Number.isNaN(pieceHours)) return ''
      return Number((pieceHours * this.getTaskQuantity(task)).toFixed(2))
    },
    formatHistoryPieceHours(value) {
      if (!this.canSelectHistoryHour(value)) return ''
      return Number((Number(value) * 60).toFixed(2))
    },
    canSelectHistoryHour(value) {
      if (!this.hasValue(value)) return false
      const number = Number(value)
      return !Number.isNaN(number) && number > 0
    },
    openWorkHourDialog(row) {
      this.handleRowClick(row)
      this.workHourCurrentRow = row
      this.dialogcasual2 = true
      this.workHourLoading = true
      this.workHourData = []

      const param = []
      param.push(["产品编码", row.产品编码])
      param.push(["合同号", ''])
      param.push(["订单号", ''])
      param.push(["工位", ''])
      param.push(["开始日期", ''])
      param.push(["结束日期", ''])
      param.push(["数据条数", 100])
      const Data = this.CreateData('11', '生产管理_结算工时_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data && Array.isArray(response.data)) {
          response.data.forEach(element => {
            if (element.Level == 2) {
              this.workHourData.push(element)
            }
          })
        }
      }).catch(() => {
        this.$message.error('历史工时查询失败')
      }).finally(() => {
        this.workHourLoading = false
      })
    },
    selectSettlementPieceHour(historyRow, type) {
      const rawValue = type === 'auxiliary'
        ? historyRow.settlementAuxiliaryPieceHours
        : historyRow.settlementReportPieceHours
      const pieceHours = this.formatHistoryPieceHours(rawValue)

      if (!this.hasValue(pieceHours)) {
        this.$message.error('历史工时为空，无法选择')
        return
      }

      this.saveSettlementPieceHour(this.workHourCurrentRow, pieceHours)
    },
    saveSettlementPieceHour(row, pieceHours) {
      if (!row) {
        this.$message.error('请选择任务')
        return
      }

      const number = Number(pieceHours)
      if (Number.isNaN(number)) {
        this.$message.error('结算单件工时格式错误')
        return
      }

      const params = []
      params.push(["editstr", `[结算单件工时] = ${number}`])
      params.push(["订单号", row.订单号])
      params.push(["订单行号", row.订单行号])
      params.push(["订单拆分内码", row.拆分内码])
      const Data = this.CreateData('12', 'MES_OrderPlanned_EditTaskPlanned', params)
      this.ExecDatabase(Data).then(response => {
        const result = response.data && response.data[0]
        if (!result || result.result !== '1') {
          this.$message.error('保存失败')
          return
        }
        this.$set(row, '结算单件工时', number)
        this.dialogcasual2 = false
        this.$message.success('保存成功')
      }).catch(() => {
        this.$message.error('保存失败')
      })
    },
    //you
    getitemdata(item){
      var param = []
      this.dialogcasual  = true
      this.itemdata = []
      param.push(["订单编号",item])
      var Data = this.CreateData('11', '工艺管理_获取物料原料信息',param)
      this.ExecDatabase(Data).then(response => {
        response.data.forEach(element => {
          if(element.U_MoType  == '机加件'){
            this.itemdata.push({
              '子件编码':element.子件编码,
              '子件名称':element.子件名称,
              '计划数量':element.计划数量,
              '材质':element.材质,
              '基本数量':element.基本数量,
              '存货量':element.存货量,
              '待出数量':element.待出数量,
              '拣配数量':element.拣配数量,
              
            })
          }
        })
      })
    },
    getCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
      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}`;
    },
    getcompletids(){
      const Data = this.CreateData('11', '计划排产_生产订单_已排产订单查询'); // 确保这个接口返回包含订单号的数据
      this.ExecDatabase(Data).then(response => {
        if (response.data && Array.isArray(response.data)) {
          this.completids = response.data.map(item => item.订单编号); // 提取所有订单号
          this.doneupdateTableDataOrder(); // 数据更新后重新排序
        }
      })
    },
    updateTableDataOrder() {
      this.$nextTick(() => {
         this.tableData.sort((a, b) => {
            if (!a || !b) return 0;
            
            // 只取日期部分 YYYY-MM-DD
            const aDate = a.计划开始时间 ? a.计划开始时间.split(' ')[0] : '';
            const bDate = b.计划开始时间 ? b.计划开始时间.split(' ')[0] : '';
            
            // 或者用 toDateString()
            // const aDate = a.计划开始时间 ? new Date(a.计划开始时间).toDateString() : '';
            // const bDate = b.计划开始时间 ? new Date(b.计划开始时间).toDateString() : '';
            
            return aDate.localeCompare(bDate);
          });
      });
    },
    doneupdateTableDataOrder() {
      this.$nextTick(() => {
         this.donetableData.sort((a, b) => {
            if (!a || !b) return 0;
            
            // 只取日期部分 YYYY-MM-DD
            const aDate = a.计划开始时间 ? a.计划开始时间.split(' ')[0] : '';
            const bDate = b.计划开始时间 ? b.计划开始时间.split(' ')[0] : '';
            
            // 或者用 toDateString()
            // const aDate = a.计划开始时间 ? new Date(a.计划开始时间).toDateString() : '';
            // const bDate = b.计划开始时间 ? new Date(b.计划开始时间).toDateString() : '';
            
            return aDate.localeCompare(bDate);
          });
      });
    },
    tableRowClassName({ row, rowIndex }) {
      const isUrgent = row.优先级 === '是' || row.加急状态 === '加急' ;
      const isSpecial = this.completids.includes(row.订单号);
      if (isUrgent) {
        return 'priority-row';
      }else if (isSpecial) {
        return 'special-row'; // 新增橙色类
      }
      return '';
    },
    donetableRowClassName({ row, rowIndex }) {
      const isUrgent = row.优先级 === '是' || row.加急状态 === '加急' ;
      if (isUrgent) {
        return 'priority-row';
      }
      return '';
    },
    handleEventClick(info) {
      // 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> ${this.formatDate(event.startStr)}</p>
          <p><strong>结束时间:</strong> ${this.formatDate(event.endStr)}</p>
        </div>
      `, '任务详情', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '关闭',
        callback: () => {}
      })
    },
    getDoing(){
      var Data = this.CreateData('11', 'MES_登录_工位与名称_查询')
      this.ExecDatabase(Data).then(response => {
          this.loading = false
          if (response.data.length !== 0) {
              this.Doingoptions= response.data
              // response.data.forEach(item => {
              //   this.Doing.push(item.指南工位号)
              // });
              this.searchTable()
              this.donesearchTable()
          }
      })
    },
    Doingform(value){
      this.station = ''
    },
    formatDate(date) {
      if (!date) return ''
      return date.split(' ').length > 1 ? date.split(' ')[0] : date
    },
    formatDate2(input) {
      const parts = input.split(' ')[0].split('/'); // 取日期部分并按 / 分割
      const [year, month, day] = parts;
      return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
    },
    handleSizeChanges(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchTable()
    },
    handleCurrentChanges(val) {
      this.pageCurrent = val
      this.searchTable()
    },
    donehandleSizeChanges(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.donesearchTable()
    },
    donehandleCurrentChanges(val) {
      this.pageCurrent = val
      this.donesearchTable()
    },
    searchTable() {
      this.loading = true
      this.tableData = []
      var 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.orderNo || 0])
      param.push(['物料类型', '自制件'])
      param.push(['合同号', this.contractNo])
      param.push(['产品编码', this.productCode])
      param.push(['产品名称', this.productName])
      param.push(['工序名称', this.processName])
      // param.push(['性质', this.nature])
      param.push(['要求完工日期1', this.completionTime[0]])
      param.push(['要求完工日期2', this.completionTime[1]])
      param.push(['计划开始', this.planStartTime])
      param.push(['计划完成', this.planendTime])
      param.push(['排产状态', this.productionStatus])
      param.push(['指派对象', this.station])
      var Data = this.CreateData('11', '机加已排产_获取任务列表', param,this.pageSize, this.pageCurrent)
      this.ExecDatabase(Data).then(response => {
        
        this.loading = false
        if (response.data.rows.length !== 0) {
          this.total = response.data.total
          this.tableData = response.data.rows
          this.fninsertidx()
          .map(item => ({
              ...item,
              editingNum: false,
              editingStatus: false,
              editingTarget: false
          }))
          this.updateTableDataOrder();
        }
      }).catch(() => {
        this.loading = false
      })
      
    },
    fninsertidx(){
      this.tableData.forEach(item => {
        if(item.二次派工){
          item.二次派工 = item.二次派工.split(",").map(Number)
        }
        if(item.最晚开始时间 =='1900/1/1 0:00:00'){
          item.最晚开始时间 = ''
        }
      });
    },
    donesearchTable() {
      this.loading = true
      this.donetableData = []
      var 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.completionTime[0]])
      param.push(['要求完工日期2', this.completionTime[1]])
      param.push(['计划开始', this.planStartTime])
      param.push(['计划完成', this.planendTime])
      param.push(['排产状态', this.doneproductionStatus])
      param.push(['指派对象', this.station])
      var Data = this.CreateData('11', '机加已排产_获取任务列表', param,this.pageSize, this.pageCurrent)
      this.ExecDatabase(Data).then(response => {
        
        this.loading = false
        // const priorityLevel = {
        //   '是': 1,
        //   '否': 0,
        //   // 如果还有其他值，比如 '紧急'、'重要'，可以加
        // };
        if (response.data.rows.length !== 0) {
          this.donetotal = response.data.total
          this.donetableData = response.data.rows
          this.donefninsertidx()
          .map(item => ({
            ...item,
            editingNum: false,
            editingStatus: false,
            editingTarget: false
          }))
          this.doneupdateTableDataOrder();
        }
      }).catch(() => {
        this.loading = false
      })
    },
    donefninsertidx(){
      this.donetableData.forEach(item => {
        if(item.二次派工){
          item.二次派工 = item.二次派工.split(",").map(Number)
        }
        if(item.最晚开始时间 =='1900/1/1 0:00:00'){
          item.最晚开始时间 = ''
        }
      });
    },
    getStationList() {
      const params = []
      const Data = this.CreateData('11', 'Prog_MES_LoadStations', params)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0) {
          this.stationOptions = response.data.map(item => ({
            label: item.OPName,
            value: item.OPName,
            code: item.VisCode
          }))
        }
      })
    },
    getpersonnelList() {
      const params = []
      const Data = this.CreateData('11', '系统管理_人员管理_所有有效人员查询', params)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0) {
          this.personnelOptions = response.data.map(item => ({
            label: item.人员姓名,
            value: item.人员编号,
            code: item.人员编号
          }))
        }
      })
    },
    handleStationChange(value) {
      const selected = this.stationOptions.find(item => item.value === value)
      this.formData.指派对象编号 = selected ? selected.code : ''
    },
    workPlan(row) {
      this.currentRow = row
      this.getStationList()
      this.dialogVisible = true
      this.formData = {
        指派对象: row.指派对象,
        指派对象编号: row.指派对象编号,
        指派数量: row.计划数量,
        计划开始时间: row.计划开始时间,
        计划完成时间: row.计划完成时间,
        最晚开始时间: row.最晚开始时间,
        派工特殊说明: row.派工特殊说明
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    editstarTask(date){
      var editstr = "[计划开始时间] = '"+ date+"'"
      var params =  [];
      var row = this.selectedRow 
      params.push(["editstr",editstr])
      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('修改成功')
      })
    },
    editendTask(date){
      var editstr = "[计划完成时间] = '"+ date+"'"
      var params =  [];
      var row = this.selectedRow 
      params.push(["editstr",editstr])
      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('修改成功')
      })
    },
    editlateTask(date){
      var editstr = "[最晚开始时间] = '"+ date+"'"
      var params =  [];
      var row = this.selectedRow 
      params.push(["editstr",editstr])
      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('修改成功')
      })
    },
    editdomTask(date){
      var editstr = "[指派对象] = '"+ date+"'"
      var params =  [];
      var row = this.selectedRow 
      params.push(["editstr",editstr])
      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.cancelAllEditing();
        this.$message.success('修改成功')
      })
    },
    editpersonnel(row){
      var params =  [];
      params.push(["TaskAID",row.taskaid])
      params.push(["personnel",row.二次派工])
      const Data = this.CreateData('12', '计划排产_二次派工', params)
      this.ExecDatabase(Data).then(response => {
        this.$message.success('修改成功')
      })
    },
    doneeditpersonnel(row){
      var params =  [];
      params.push(["TaskAID",row.taskaid])
      params.push(["personnel",row.二次派工])
      const Data = this.CreateData('12', '计划排产_二次派工', params)
      this.ExecDatabase(Data).then(response => {
        this.$message.success('修改成功')
      })
    },
    AllworkPlan() {
      const multipleSelectionrow = this.multipleSelection;
      // 1. 校验：至少选择两个任务
      if (multipleSelectionrow.length < 2) {
        return this.$message.error('请选择多个任务');
      }
      const firstpo = multipleSelectionrow[0];

      // 2. 检查第一行是否有指派数量（若无则可设默认值）
      if (!firstpo.指派数量) {
        firstpo.指派数量 = multipleSelectionrow[0].计划数量;
        // return this.$message.error('请填写第一行的指派数量');
      }
      // 3. 检查第一行关键字段
      if (!firstpo.指派对象 || !firstpo.计划开始时间) {
        return this.$message.error('请填写第一道工序的指派对象和计划开始时间');
      }
      // 4. 遍历所有选中行，按顺序处理
      for (let i = 0; i < multipleSelectionrow.length; i++) {
        const item = multipleSelectionrow[i];
        // 检查是否属于同一订单
        if (item.订单号 !== firstpo.订单号) {
          return this.$message.error('请选择同一订单任务');
        }
        // === 统一赋值：指派对象 和 指派数量（用第一行的值）===
        if (i === 0) {
          // 第一行：必须有值（已校验）
          if (!item.指派对象) {
            item.指派对象 = firstpo.指派对象;
          }
        } else {
          const prevItem = multipleSelectionrow[i - 1];
          if (!item.指派对象) {
            item.指派对象 = prevItem.指派对象;
          }
        }
        if(!item.指派数量){
          item.指派数量 = item.计划数量;
        }
        // === 处理 计划开始时间：为空则继承上一行 ===
        if (i === 0) {
          // 第一行：必须有值（已校验）
          if (!item.计划开始时间) {
            item.计划开始时间 = new Date(firstpo.计划开始时间);
          }
        } else {
          const prevItem = multipleSelectionrow[i - 1];
          if (!item.计划开始时间) {
            item.计划开始时间 = new Date(prevItem.计划开始时间);
          }
          if (!item.计划完成时间) {
            item.计划完成时间 = new Date(prevItem.计划完成时间);
        }
        }
        // === 处理 计划完成时间：为空则等于当前行的 计划开始时间 ===
        
      }
      // 5. 更新状态
      this.submitstatus = 1;
      this.multipleSelection = multipleSelectionrow;
    },
    // clickadjust(){
    //   var row = this.selectedRow
    //   const params = []
    //   params.push(['TaskAID', row.taskaid])
    //   params.push(['订单号', row.订单号])
    //   params.push(['订单行号', row.订单行号])
    //   params.push(['订单拆分内码', row.拆分内码])
    //   params.push(['派工特殊说明', row.派工特殊说明])
    //   params.push(['派工操作人', this.$store.state.user.name])
    //   const Data = this.CreateData('12', '计划排产_派工', params)
    //   this.ExecDatabase(Data).then(response => {
    //     if (response.data[0].result !== '1') {
    //       this.$message.error('派工失败')
    //       return
    //     }
    //     this.$message.success('派工成功')
        
    //   })

    // },
    editsum(){
      var row = this.selectedRow
      const params = []
      if(this.editnumber >= 1 & this.editnumber <=row.计划数量 ){
        params.push(['订单号', row.订单号])
        params.push(['订单行号', row.订单行号])
        params.push(['订单拆分内码', row.拆分内码])
        params.push(['指派对象编号', row.指派对象编号])
        params.push(['指派对象', row.指派对象])
        params.push(['指派数量', this.editnumber ])
        params.push(['派工特殊说明', row.派工特殊说明])
        params.push(['计划开始时间', row.计划开始时间])
        params.push(['计划完成时间', row.计划完成时间])
        params.push(['最晚开始时间', row.最晚开始时间])
        params.push(['派工操作人', this.$store.state.user.name])
      }else{
        return this.$message.error('指派数量输入错误')
      }
      const Data = this.CreateData('12', 'MES_OrderPlanned_SingleTaskPlanned', params)
      this.ExecDatabase(Data).then(response => {
        this.submitLoading = false
        if (response.data[0].result !== '1') {
          this.$message.error('派工失败')
          return
        }
        this.$message.success('派工成功')
        this.dialogVisible = false
        this.searchTable()
        this.donesearchTable()
      }).catch(() => {
        this.submitLoading = false
      })
    },
    submitForm() {
      this.submitLoading = true
      this.multipleSelection.forEach(item => {
        const params = []
        params.push(['订单号', item.订单号])
        params.push(['订单行号', item.订单行号])
        params.push(['订单拆分内码', item.拆分内码])
        params.push(['指派对象编号', item.指派对象编号])
        params.push(['指派对象', item.指派对象])
        params.push(['指派数量', item.指派数量])
        params.push(['派工特殊说明', item.派工特殊说明])
        params.push(['计划开始时间', item.计划开始时间])
        params.push(['计划完成时间', item.计划完成时间])
        params.push(['最晚开始时间', item.最晚开始时间])
        params.push(['派工操作人', this.$store.state.user.name])

        const Data = this.CreateData('12', 'MES_OrderPlanned_SingleTaskPlanned', params)
        this.ExecDatabase(Data).then(response => {
          this.submitLoading = false
          if (response.data[0].result !== '1') {
            this.$message.error('派工失败')
            return
          }
          this.$message.success('派工成功')
          
        }).catch(() => {
          this.submitLoading = false
        })
      });
      this.dialogVisible = false
      this.searchTable()
      this.donesearchTable()
      this.submitstatus = 0
      this.multipleSelection = []
    },
    startEditingNum(row) {
      this.cancelAllEditing();
      this.$set(row, 'editingNum', true);
    },
    startEditingTarget(row) {
      this.cancelAllEditing();
      this.$set(row, 'editingTarget', true);
    },
    saveNum(num) {
      this.editnumber = num
      
    },
    savegroup(num) {
      var row = this.selectedRow 
      const params = []
      params.push(['TaskAID', row.taskaid])
      params.push(['外协分组', num])
      const Data = this.CreateData('12', '计划排产_外协分组', params)
      this.ExecDatabase(Data).then(response => {
        this.$message.success('保存成功')
        // this.searchTable()
        // this.donesearchTable()
      }).catch(() => {
        this.submitLoading = false
      })
    },
    handleRowClick(row) {
      this.selectedRow = row

    },
    // 取消所有编辑
    cancelAllEditing() {
      this.tableData.forEach(row => {
        this.$set(row, 'editingNum', false);
        this.$set(row, 'editingStatus', false);
        this.$set(row, 'editingTarget', false);
      });
    },
    workPlanOver() {
      const multipleSelectionrow = this.multipleSelection;

      if (multipleSelectionrow.length < 1) {
        return this.$message.error('请选择任务');
      }

      // 使用 for...of，可以正常使用 return 跳出整个函数
      for (const item of multipleSelectionrow) {
        if (!item.指派对象) {
          this.$message.error('请选择' + item.订单号 + '的指派对象');
          return; // ✅ 成功截停整个函数
        }

        if (!item.指派数量) {
          item.指派数量 = item.计划数量;
        }

        if (!item.计划开始时间) {
          this.$message.error('请选择' + item.订单号 + '的计划开始时间');
          return; // ✅ 截停
        }

        if (!item.计划完成时间) {
          this.$message.error('请选择' + item.订单号 + '的计划完成时间');
          return; // ✅ 截停
        }
      }

      // 所有校验通过，继续执行
      const params = [];
      params.push(['任务列表', JSON.stringify(multipleSelectionrow)]);
      params.push(['派工操作人', this.$store.state.user.name]);
      const result = {};

      multipleSelectionrow.forEach(element => {
        const orderNo = element.订单号;
        const startTime = element.计划开始时间;   // "2025-10-01 00:00:00"
        const finishTime = element.计划完成时间; // "2025-10-10 00:00:00"

        // 如果该订单号还未在 result 中，初始化
        if (!result[orderNo]) {
          result[orderNo] = {
            最早开始: null,
            最晚完成: null
          };
        }

        // 更新 最早开始时间（取最小值）
        if (result[orderNo].最早开始 === null || startTime < result[orderNo].最早开始) {
          result[orderNo].最早开始 = startTime;
        }

        // 更新 最晚完成时间（取最大值）
        if (result[orderNo].最晚完成 === null || finishTime > result[orderNo].最晚完成) {
          result[orderNo].最晚完成 = finishTime;
        }
      });

      // 输出结果
      const resultArray = Object.keys(result).map(orderNo => ({
        订单号: orderNo,
        最早开始: result[orderNo].最早开始,
        最晚完成: result[orderNo].最晚完成
      }));
      resultArray.forEach(element => {
        patchB1("/ProductionOrders("+element.订单号+")",{
          "AbsoluteEntry": element.订单号,
          "U_MODueDate": element.最晚完成,
          "U_MOStartDate": element.最早开始,
        })
      })
      
      const Data = this.CreateData('11', 'MES_OrderPlanned_Finish', params);
      this.ExecDatabase(Data).then(response => {
        this.$message.success('排产完成');
        this.multipleSelection = [];
        this.searchTable();
        this.donesearchTable();
      });
    },
    editRemark(row) {
      this.currentRow = row
      this.remarkDialogVisible = true
      this.remarkForm = {
        优先级: row.优先级 || '',
        未完成说明: row.未完成说明 || '',
        派工特殊说明: row.派工特殊说明 || ''
      }
    },
    
    submitRemark() {
      this.remarkSubmitLoading = true
      const params = []
      params.push(['订单号', this.currentRow.订单号])
      params.push(['订单行号', this.currentRow.订单行号])
      params.push(['订单拆分内码', this.currentRow.拆分内码])
      params.push(['优先级', this.remarkForm.优先级])
      params.push(['未完成说明', this.remarkForm.未完成说明])
      params.push(['派工特殊说明', this.remarkForm.派工特殊说明])
      params.push(['最后编辑人', this.$store.state.user.name])

      const Data = this.CreateData('12', 'MES_OrderPlanned_DescriptionEdit', params)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result !== '1') {
          this.$message.error('保存失败')
          return
        }
        this.$message.success('保存成功')
        this.remarkDialogVisible = false
        this.searchTable()
        this.donesearchTable()
      }).finally(() => {
        this.remarkSubmitLoading = false
      })
    },
    // 格式化日期以适应 FullCalendar (需要 'yyyy-MM-dd')
    formatDateForCalendar(date, isEnd = false) {
      if (!date) return null
      try {
        let d
        if (typeof date === 'string') {
          // 如果是字符串，解析日期部分
          const datePart = date.split(' ')[0]
          const [year, month, day] = datePart.split('-').map(Number)
          d = new Date(Date.UTC(year, month - 1, day))
        } else if (date instanceof Date) {
          d = new Date(date.getTime())
        }

        if (isEnd) {
          d.setUTCDate(d.getUTCDate() + 1)
        }
        // 转换为 ISO 格式并取日期部分
        const isoString = d.toISOString()
        return isoString.split('T')[0]
      } catch (error) {
        console.error('Error formatting date for calendar:', date, error)
        return null
      }
    },

    // 处理日历事件拖拽完成后的逻辑
    handleEventDrop(info) {
      const event = info.event
      const newStart = this.formatDateForCalendar(event.startStr)
      const endDate = new Date(event.endStr)
      endDate.setUTCDate(endDate.getUTCDate() - 1)
      const newEnd = this.formatDateForCalendar(endDate)

      this.updateTaskTime(event.extendedProps, newStart, newEnd, info.revert)
    },

    // 处理日历事件调整大小完成后
    handleEventResize(info) {
      const event = info.event
      const newStart = this.formatDateForCalendar(event.startStr)
      const endDate = new Date(event.endStr)
      endDate.setUTCDate(endDate.getUTCDate() - 1)
      const newEnd = this.formatDateForCalendar(endDate)

      if (!newStart || !newEnd) {
        this.$message.error('日期格式错误，无法更新')
        info.revert()
        return
      }

      this.updateTaskTime(event.extendedProps, newStart, newEnd, info.revert)
    },
    // 更新时间 传入 revert 回调用于失败时恢复事件位置
    updateTaskTime(taskInfo, startTime, endTime, revertCallback) {
      this.$confirm('确认修改计划时间?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = []
        params.push(['订单号', taskInfo.订单号])
        params.push(['订单行号', taskInfo.订单行号])
        params.push(['订单拆分内码', taskInfo.拆分内码])
        params.push(['计划开始时间', startTime])
        params.push(['计划完成时间', endTime])

        const Data = this.CreateData('12', '计划排产_自制件_日程时间修改', params)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result !== '1') {
            this.$message.error('计划时间更新失败')
            if (revertCallback) revertCallback()
            return
          }
          const row = this.tableData.find(item =>
            item.订单号 === taskInfo.订单号 &&
            item.订单行号 === taskInfo.订单行号 &&
            item.拆分内码 === taskInfo.拆分内码
          )

          if (row) {
            row.计划开始时间 = startTime
            row.计划完成时间 = endTime
            // 注意：这里不要触发 deep watch 的性能问题，但数据必须更新
          }

          this.$message.success('计划时间更新成功')
          this.donesearchTable()
        }).catch(() => {
          this.$message.error('更新失败')
          if (revertCallback) revertCallback()
        })
      }).catch(() => {
        if (revertCallback) revertCallback()
      })
    }
  }
}
</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;
}
::v-deep .special-row {
  background-color: #ff9800 !important; /* 橙色背景 */
  color: #000000 !important;
  border: #ff9800;
}
::v-deep .special-row td {
  background-color: #ff9800 !important;
  color: #000000 !important;
  border: #ff9800;
}
.el-table ::v-deep td.el-table__cell .editable-cell{
  height: inherit;
}
.show-text {
  margin-right: 5px;
  line-height: 32px;
}
.show-head {
  margin-right: 5px;
  line-height: 32px;
  font-size: 15px;
}
.el-dialog__body {
  padding: 20px;
}
.el-form-item {
  margin-bottom: 15px;
}
.custom-tabs {
  margin-top: 20px;
}
.station-board {
  height: 63vh;
  min-height: 300px;
  overflow: hidden;
  border: 1px solid #e6ebf2;
  background: #fff;
}
.station-table-wrap {
  width: 100%;
  height: 100%;
  overflow: auto;
}
.station-table {
  width: 100%;
  min-width: 2800px;
  border-collapse: collapse;
  table-layout: fixed;
  color: #24364a;
  font-size: 12px;
}
.station-table th,
.station-table td {
  height: 30px;
  padding: 0 8px;
  border-right: 1px solid #e6ebf2;
  border-bottom: 1px solid #e6ebf2;
  text-align: left;
  vertical-align: middle;
  white-space: wrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.station-table th {
  position: sticky;
  top: 0;
  z-index: 2;
  height: 32px;
  background: #f5f7fa;
  color: #3f5067;
  font-weight: 600;
}
.station-table tbody tr:hover td {
  background: #f7fbff;
}
.station-table .summary-row td {
  background: #eef1f5;
  color: #172333;
  font-weight: 700;
}
.station-table .station-row td {
  background: #e3e7ec;
  cursor: pointer;
}
.station-table .date-row td {
  background: #f1f4f8;
  cursor: pointer;
}
.station-table .task-row td {
  background: #fff;
}
.station-table .task-row.is-priority td {
  background: #fff6f5;
  color: #b42318;
}
.station-table .date-row .tree-cell {
  padding-left: 28px;
}
.station-table .group-arrow {
  margin-right: 8px;
  color: #516274;
  font-size: 12px;
}
.station-table .date-arrow {
  color: #60758c;
}
.station-table .number-cell {
  text-align: center;
}
.station-table .tag-cell {
  text-align: center;
}
.station-table .name-cell .el-tag {
  margin-left: 6px;
}
.station-table .action-cell {
  color: #2f72c4;
  width: 200px;
}
.station-table .action-cell ::v-deep .el-button--mini {
  padding: 0;
}
.station-table .compact-input {
  width: 70px;
}
.station-table .compact-select {
  width: 110px;
}
.station-table .compact-date {
  width: 120px;
}
.station-table .compact-personnel {
  width: 180px;
}
.station-table .compact-group {
  width: 110px;
}
.station-table .work-hour-button {
  max-width: 100px;
  padding: 0;
}
.station-table ::v-deep .el-input__inner {
  height: 24px;
  padding: 0 8px;
  border-color: #d8e0ea;
  border-radius: 2px;
  line-height: 24px;
}
.station-table ::v-deep .el-input__icon {
  line-height: 24px;
}
.station-table ::v-deep .el-tag {
  height: 20px;
  line-height: 18px;
  border-radius: 2px;
}
.col-tree { width: 140px; }
.col-num { width: 90px; }
.col-order { width: 80px; }
.col-plan { width: 80px; }
.col-contract { width: 120px; }
.col-code { width: 170px; }
.col-name { width: 170px; }
.col-plan-num { width: 70px; }
.col-hours { width: 90px; }
.col-settlement-hours { width: 90px; }
.col-settlement-piece { width: 120px; }
.col-process { width: 120px; }
.col-station { width: 120px; }
.col-date { width: 130px; }
.col-personnel { width: 190px; }
.col-priority { width: 80px; }
.col-text { width: 130px; }
.col-group { width: 120px; }
.col-user { width: 100px; }
.col-time { width: 170px; }
.col-actions { width: 90px; }
.schedule-container {
  min-height: 67vh;
}

.schedule-container ::v-deep .fc-daygrid-day-frame {
  padding: 2px;
  min-height: auto;
}

.schedule-container ::v-deep .fc-event {
  font-size: 12px;
  padding: 1px 2px;
  margin-bottom: 1px;
  line-height: 1.4;
}

.schedule-container ::v-deep .fc-daygrid-event-harness {
  margin-bottom: 1px;
}

.schedule-container ::v-deep .fc-daygrid-day-top {
  padding: 2px;
}

.schedule-container ::v-deep .fc-daygrid-more-link {
  font-size: 12px;
  padding: 0 2px;
}
::v-deep .el-checkbox__label {
    display: inline-block;
    padding-left: 10px;
    line-height: 16px;
    font-size: 14px;
    font-weight: bold;
}
::v-deep .el-table__fixed {
  height: auto !important;
  bottom: 12px !important; /* 给滚动条留出空间 */
}

.el-picker-panel__icon-btn{
  padding: 0;
}
</style>
