<template>
  <div>
    <el-card>
      <div class="search-container">
        <span class="show-text">生产订单:</span>
        <el-input v-model="orderNo" placeholder="请输入生产订单" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">销售订单:</span>
        <el-input v-model="contractNo" placeholder="请输入销售订单" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">产品编码:</span>
        <el-input v-model="productCode" placeholder="请输入产品编码" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">产品名称:</span>
        <el-input v-model="productName" placeholder="请输入产品名称" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">工序名称:</span>
        <el-input v-model="processName" placeholder="请输入工序名称" clearable style="width: 150px;margin-right: 10px" />
        <br>
        <br>
        <span class="show-text">性质:</span>
        <el-input v-model="nature" placeholder="请输入性质" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">排产状态:</span>
        <el-select v-model="productionStatus" clearable placeholder="请选择状态" style="width: 150px;margin-right: 10px">
          <el-option label="全部" value="全部" />
          <el-option label="已完成" value="已完成" />
          <el-option label="未完成" value="未完成" />
        </el-select>
        <span class="show-text">要求完工日期:</span>
        <el-date-picker
          v-model="completionTime"
          :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" />
        <el-button :disabled="loading" icon="el-icon-search" plain type="primary" @click="searchTable()">查询</el-button>
        <el-button type="warning" size="mini" style="width: 100px;"  @click="AllworkPlan">批量排产</el-button>
        <el-button type="success" size="mini" style="width: 100px;"  @click="PlanFinish">排产完成</el-button>
        <el-button type="success" size="mini" style="width: 100px;" @click="submitForm" v-if="this.submitstatus">确认修改</el-button>
        <el-button type="warning" size="mini" style="width: 100px;"  @click="ChildTask_Add">拆分子任务</el-button>
      </div>

      <el-tabs v-model="activeTab" type="card" class="custom-tabs">
        <el-tab-pane label="表单" name="form">
          <div style="width: 100%;">
            <el-table
              v-loading="loading"
              :data="tableData"
              :height="'70vh'"
              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-key = "id"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              >
              <el-table-column align="center" type="selection"  width="50" fixed />
              <el-table-column align="center" label="序号" type="index" width="50"  />
              <el-table-column align="center" prop="合同号" label="销售订单" width="120" />
              <el-table-column align="center" prop="订单号" label="生产订单" width="100" fixed/>
              <el-table-column align="center" prop="订单行号" label="订单行号" width="120" />
              <el-table-column align="center" prop="拆分内码" label="拆分内码" width="120" />
              <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="80" fixed/>
              <el-table-column align="center" label="预计齐套时间" width="120">
                <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="80"/>
              <el-table-column align="center" label="备料日期" width="120">
                <template slot-scope="scope">
                  {{ formatDate(scope.row.备料日期) }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="加急" width="80">
                <template slot-scope="scope">
                  <div class="status-light" :class="scope.row.加急 === '加急' ? 'status-light-green' : 'status-light-gray'" />
                </template>
              </el-table-column>
              
              <el-table-column align="center" prop="总工时" label="总工时" width="100" />
              <el-table-column align="center" prop="排产状态" label="排产状态" width="150" />
              <!-- <el-table-column align="center" label="排产时间" width="120">
                <template slot-scope="scope">
                  {{ formatDate(scope.row.排产时间) }}
                </template>
              </el-table-column> -->
              <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="150" >
                <template slot-scope="scope">
                  <div v-if="!scope.row.editingTarget" style="height: 25px;" class="editable-cell" @click="startEditingTarget(scope.row)">
                    {{ scope.row.指派对象 }}
                  </div>
                  <div v-if="scope.row.editingTarget">
                    <el-select
                      v-model="scope.row.指派对象"
                      placeholder="请选择"
                      @change="editdomTask"
                      ref="TargetSelect"
                      style="width: 100%">
                      <el-option
                        v-for="item in stationOptions"
                        :key="item.code"
                        :label="item.label"
                        :value="item.value"
                        />
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="指派数量" label="指派数量" width="180" >
                <template slot-scope="scope">
                  <div v-if="!scope.row.editingNum" class="editable-cell" @click="startEditingNum(scope.row)">
                    {{ scope.row.指派数量 }}
                  </div>
                  <div v-if="scope.row.editingNum" >
                    <el-input class="editable-cell"
                      v-model="scope.row.指派数量"
                      size="small"
                      placeholder="数量"
                      @change="saveNum"
                      type="int"
                      style="width: 80px;"
                    ></el-input>
                    <el-button type="warning" size="mini" style="width: 50px;"  @click="editsum">确定</el-button>
                  </div>
                </template>
              </el-table-column>  
              <el-table-column align="center" label="计划开始" width="160">
                
                <el-date-picker
                  v-model="scope.row.计划开始时间"
                  type="date"
                  slot-scope="scope"
                  placeholder = "计划开始时间"
                  size = "small"
                  style="width: 135px;"
                  value-format="yyyy-MM-dd"
                  @change = "editstarTask"
                  >
                </el-date-picker>
              </el-table-column>
              <el-table-column align="center" label="计划完成" width="160">
                
                <el-date-picker
                  v-model="scope.row.计划完成时间"
                  type="date"
                  slot-scope="scope"
                  placeholder = "计划完成时间"
                  size = "small"
                  style="width: 135px;"
                  value-format="yyyy-MM-dd"
                  @change = "editendTask">
                </el-date-picker>
              </el-table-column>
              <el-table-column align="center" label="最晚开始" width="160">
                <el-date-picker
                  v-model="scope.row.最晚开始时间"
                  type="date"
                  slot-scope="scope"
                  placeholder = "最晚开始时间"
                  size = "small"
                  style="width: 135px;"
                  value-format="yyyy-MM-dd"
                  @change = "editlateTask">
                </el-date-picker>
              </el-table-column>
              <el-table-column align="center" prop="优先级" label="优先级" width="80" >
                <template slot-scope="scope">
                  <el-tag :type="scope.row.优先级 === '是' ? 'warning' : 'info'" size="mini">
                    {{ scope.row.优先级 }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="未完成说明" label="未完成说明" width="120" />
              <el-table-column align="center" prop="派工特殊说明" label="派工特殊备注" width="120" />
              <el-table-column align="center" prop="最后编辑人" label="最后编辑人" width="100" />
              <el-table-column align="center" label="最后编辑时间" width="170">
                <template slot-scope="scope">
                  {{ scope.row.最后编辑时间 }}
                </template>
              </el-table-column>
              <el-table-column align="center" prop="工序名称" label="工序名称" width="120" />

              <!-- <el-table-column align="center" label="加急状态1" width="80">
                <template slot-scope="scope">
                  <div class="status-light" :class="scope.row.加急状态1 === '加急' ? 'status-light-green' : 'status-light-gray'" />
                </template>
              </el-table-column> -->
              <el-table-column align="center" prop="性质" label="性质" width="100" />
              <!-- <el-table-column align="center" prop="总工时1" label="总工时1" width="80" /> -->
              <el-table-column align="center" prop="占用情况" label="占用情况" width="100" />
              <el-table-column align="center" label="派工状态" width="100">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.派工状态 === 1 ? 'success' : 'danger'" size="mini">
                    {{ scope.row.派工状态 === 1 ? '已完成' : '未完成' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column align="center" label="外协通知" width="100">
                <template slot-scope="scope">
                  <div class="status-light" :class="scope.row.外协通知 === 1 ? 'status-light-green' : 'status-light-gray'" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="排产" width="120">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click="editRemark(scope.row)">编辑</el-button>
                </template>
              </el-table-column>
              
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="日程" name="schedule">
          <div class="schedule-container">
            <FullCalendar ref="fullCalendar" :options="calendarOptions" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 拆分子任务及派工 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="拆分子任务及派工"
      center
      width="850px">
      <el-form
        ref="formData"
        :model="formData"
        label-width="120px"
        size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="指派对象" prop="指派对象">
              <el-select
                v-model="formData.指派对象"
                placeholder="请选择"
                style="width: 100%"
                @change="handleStationChange">
                <el-option
                  v-for="item in stationOptions"
                  :key="item.code"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分配数量" prop="指派数量">
              <el-input-number v-model="formData.指派数量" :min="1" :max="formData.计划数量" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划开始时间" prop="计划开始时间">
              <el-date-picker
                v-model="formData.计划开始时间"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划完成时间" prop="计划完成时间">
              <el-date-picker
                v-model="formData.计划完成时间"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最晚开始时间" prop="最晚开始时间">
              <el-date-picker
                v-model="formData.最晚开始时间"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="装配任务概述" prop="装配任务概述">
              <el-input
                v-model="formData.装配任务概述"
                :rows="3"
                type="textarea"
                placeholder="请输入装配任务概述" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          :loading="submitLoading"
          type="primary"
          @click="submitChildTask_Add">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑备注弹窗 -->
    <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>

    
  </div>
</template>


<script>
// 这三个组件用于绘制日历
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from '@fullcalendar/interaction'

export default {
  components: { FullCalendar },
  data() {
    return {
      activeTab: 'form',
      orderNo: '',
      contractNo: '',
      productCode: '',
      productName: '',
      processName: '',
      nature: '',
      productionStatus: '未完成',

      Doing:"",
      Doingoptions:[],
      
      completionTime: [],
      loading: false,
      tableData: [],


      multipleSelection: [],
      dialogVisible: false,
      submitLoading: false,
      currentRow: {},
      stationOptions: [],
      selectedRow: {},
      editnumber:0,
      submitstatus:0,
      formData: {
        指派对象编号: '',
        指派对象: '',
        指派数量: 0,
        计划开始时间: '',
        计划完成时间: '',
        装配任务概述: '',
        最晚开始时间:''
      },
      remarkDialogVisible: false,
      remarkSubmitLoading: false,
      remarkForm: {
        优先级: '',
        未完成说明: '',
        派工特殊说明: ''
      },
      // 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, // 调整大小完成后回调
        height: 'auto', // 设置高度为auto，使其自适应内容
        dayMaxEvents: true // 限制每天显示的事件数量
      }
    }
  },
  computed: {
    calendarEvents() {
      return this.tableData.map(item => ({
        id: `${item.订单号}-${item.订单行号}-${item.拆分内码}`,
        title: `${item.订单号} | ${item.产品名称} | ${item.指派对象} | ${item.计划数量}`,
        start: this.formatDateForCalendar(item.计划开始时间),
        end: this.formatDateForCalendar(item.计划完成时间, true),
        extendedProps: {
          订单号: item.订单号,
          订单行号: item.订单行号,
          拆分内码: item.拆分内码,
          
        }
      }))
      
    }
  },
  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
        })
      }
    },
    tableData: {
      handler() {
        this.calendarOptions.events = this.calendarEvents
        if (this.activeTab === 'schedule') {
          this.$nextTick(() => {
            const calendarApi = this.$refs.fullCalendar && this.$refs.fullCalendar.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.searchTable()
    this.getStationList()
    this.getDoing()
    
  },
  methods: {
    getDoing(){
      var Data = this.CreateData('11', 'MES_登录_工位与名称_查询')
      this.ExecDatabase(Data).then(response => {
          this.loading = false
          if (response.data.length !== 0) {
              this.Doingoptions= response.data
              
          }
      })
    },
    Doingform(value){
      console.log(value)
    },
    formatDate(date) {
      if (!date) return ''
      return date.split(' ').length > 1 ? date.split(' ')[0] : date
    },
    PlanFinish(){
      var row = this.selectedRow
      
      if (row.订单号){
        this.$confirm('确认完成生产订单【' + row.订单号 +'】的计划排产，并提交到erp吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var param = []
          param.push(['订单号', row.订单号])
          param.push(['派工操作人', this.$store.state.user.name])
          var Data = this.CreateData('12', 'MES_OrderPlanned_Finish', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result !== '1') {
              console.log(response)
              this.$message.error('修改失败')
              return
            }
            this.$message({
              type: 'success',
              message: '排产成功!',
            });
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '排产取消'
          });          
        });
      }else{
        this.$message.error('请先选择数据')
      }
      
    },
    ChildTask_Add(){
      
      this.dialogVisible = true
      
    },
    submitChildTask_Add(data){
      var row = this.selectedRow
      console.log(this)
      var param = []
      param.push(['TaskAID', this.$refs.formData.model.TaskAID])
      param.push(['任务描述', this.$refs.formData.model.装配任务概述])
      param.push(['指派对象', this.$refs.formData.model.指派对象])
      param.push(['指派对象编号', this.$refs.formData.model.指派对象编号])
      param.push(['指派数量', this.$refs.formData.model.指派数量])
      param.push(['计划开始时间', this.$refs.formData.model.计划开始时间])
      param.push(['计划结束时间', this.$refs.formData.model.计划完成时间])
      param.push(['最晚开始时间', this.$refs.formData.model.最晚开始时间])
      var Data = this.CreateData('12', 'MES_OrderPlanned_ChildTask_Add', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result !== '1') {
          this.$message.error('修改失败')
          return
        }
        this.dialogVisible = false
        searchTable()
        this.$message.success('修改成功')
      })

    },
    ChildTask_Get(firstlist){
      var params = []
      params.push(['TaskAID', 0])
      var ChildTasktable = this.CreateData('11', 'MES_OrderPlanned_ChildTask_Get', params)
      
      this.ExecDatabase(ChildTasktable).then(response => {
        if(!response || !response.data) {
          this.tableData = firstlist;
          return;
        }

        // 创建新的数组，避免直接修改原数组
        const newTableData = firstlist.map(item => ({
          ...item,
          id: `parent_${item.TaskAID}`, // 为父项创建唯一ID
          children: [],
          
        }));

        const parentMap = new Map();
        newTableData.forEach(item => {
          parentMap.set(item.TaskAID, item);
        });

        response.data.forEach(childItem => {
          const parentItem = parentMap.get(childItem.TaskAID);
          if(parentItem){
            parentItem.children.push({
              ...childItem,
              id: `child_${childItem.AID}`, // 为子项创建唯一ID
              isChild: true // 标记为子项
            });
          }
        });
        console.log(newTableData)
        console.log(newTableData[0].children)
        this.tableData = newTableData;
        
      })
    },
    searchTable() {
      this.loading = true
      this.tableData = []
      var param = []
      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.productionStatus])
      var Data = this.CreateData('11', 'MES_OrderPlanned_Query', param)
      this.ExecDatabase(Data).then(response => {
        console.log(response.data.length)
        this.loading = false
        if (response.data.length !== 0) {
          this.ChildTask_Get(response.data)
          
          
        }
      }).catch(() => {
        this.loading = false
      })
    },
    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
          }))
        }
      })
    },
    handleStationChange(value) {
      const selected = this.stationOptions.find(item => item.value === value)
      this.formData.指派对象编号 = selected ? selected.code : ''
    },
    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('修改成功')
      })
    },
    AllworkPlan() {
      const params = []
      var multipleSelectionrow = this.multipleSelection
      var BindRpt_ALLtaskids = ''
      if(multipleSelectionrow.length<2){
        return this.$message.error('请选择多个任务')
      }
      var firstpo = multipleSelectionrow[0]
      if (!firstpo.指派对象 || !firstpo.指派数量 || !firstpo.计划开始时间 || !firstpo.计划完成时间 || !firstpo.最晚开始时间){
          return this.$message.error('请填写第一道工序内容')
      }
      multipleSelectionrow.forEach(item => {
        if (item.订单号 == firstpo.订单号){
          item.指派对象 = firstpo.指派对象
          item.指派数量 = firstpo.指派数量
          item.计划开始时间 = firstpo.计划开始时间
          item.计划完成时间 = firstpo.计划完成时间
          item.最晚开始时间 = firstpo.最晚开始时间
        }else{
          return this.$message.error('请选择同一订单任务')
        }
      });
      this.submitstatus = 1
      this.multipleSelection = multipleSelectionrow
      console.log(multipleSelectionrow)
    },
    editsum(){
      var row = this.selectedRow
      const params = []
      if(this.editnumber<=row.指派数量 || !this.editnumber){
        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()
      }).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.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
    },
    handleRowClick(row) {
      this.formData = row
      this.selectedRow = row
      this.formData = {
        TaskAID:row.TaskAID,
        指派对象编号:row.指派对象编号,
        指派对象:row.指派对象,
        指派数量:row.指派数量,
        计划开始时间:row.计划开始时间,
        计划完成时间:row.计划完成时间,
        最晚开始时间:row.最晚开始时间,
        装配任务概述 : row.齐套检测 + row.合同号 + row.产品名称 + row.产品编码 +"数量:"+row.指派数量
      }
    },
    // 取消所有编辑
    cancelAllEditing() {
      this.tableData.forEach(row => {
        this.$set(row, 'editingNum', false);
        this.$set(row, 'editingStatus', false);
        this.$set(row, 'editingTarget', false);
      });
    },
    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()
      }).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 = []
        var editstr = "[计划开始时间] = '"+ startTime+"' , [计划完成时间] = '"+ endTime+"'"
        params.push(['editstr', editstr])
        params.push(['订单号', taskInfo.订单号])
        params.push(['订单行号', taskInfo.订单行号])
        params.push(['订单拆分内码', taskInfo.拆分内码])


        const Data = this.CreateData('12', 'MES_OrderPlanned_EditTaskPlanned', params)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result !== '1') {
            this.$message.error('计划时间更新失败')
            if (revertCallback) revertCallback()
            return
          }
          this.$message.success('计划时间更新成功')
          this.searchTable()
        })
      }).catch(() => {
        if (revertCallback) revertCallback()
      })
    }
  }
}
</script>

<style scoped>
.el-table ::v-deep td.el-table__cell div{
  height: 50px;
  line-height: 50px;
}
::v-deep .el-input--suffix .el-input__inner{
  padding-right: 0;
}
::v-deep .el-input__suffix{
  display: none;
}

.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;
}
.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;
}

</style>
