<template>
  <div>
    <el-card>
      <div class="search-container">
        <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="orderNo" 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">性质:&nbsp;&nbsp;&nbsp;</span>
        <el-input v-model="nature" placeholder="请输入性质" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">要求完工日期:</span>
        <el-date-picker v-model="completionTime" :clearable="false" end-placeholder="结束时间" format="yyyy-MM-dd"
          range-separator="-" start-placeholder="开始时间" style="width: 230px;"type="datetimerange" value-format="yyyy-MM-dd" />
        <span class="show-text">指派对象:</span>
        <el-select v-model="Doing" multiple  @change = "Doingform">
          <el-option v-for="item in Doingoptions"
          :key="item.指南工位号"
          :label="item.指南工位号"
          :value="item.工位号" />
        </el-select>
        <el-button :disabled="loading" icon="el-icon-search" plain type="primary"
          @click="searchTable()">查询</el-button>
      </div>
      <el-tabs v-model="activeTab" type="card" class="custom-tabs">
        <el-tab-pane label="表单"  name="form">
          <div v-for=" (items,itemsname ) in tableData2" >
            <h3>{{ itemsname }}</h3> <!-- 显示组名 -->
            <el-table v-loading="loading" :data="items"  border
            element-loading-background="rgba(0, 0, 0, 0.2)" element-loading-spinner="el-icon-loading"
            highlight-current-row size="mini" style="width: 100%;margin-top: 20px;" tooltip-effect="dark"
            @row-click="handleRowClick">
            <el-table-column align="center" label="序号" type="index" width="50" fixed />
            <el-table-column align="center" prop="合同号" label="销售订单" width="120" fixed />
            <el-table-column align="center" prop="生产订单" label="生产订单" width="100" fixed />
            <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" />
            <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="120" />
            <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="120" />
            <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="70">
              <template slot-scope="scope">
                <div v-if =" scope.row.收料数量 < scope.row.计划数量 & scope.row.收料 == 1 "  class="status-light status-light-orange"  />
                <div v-if  =" scope.row.收料数量 >= scope.row.计划数量 & scope.row.收料 == 1 "class="status-light status-light-green " />
                <div v-if ="!scope.row.收料"class="status-light status-light-gray" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="进度" width="200">
              <template slot-scope="scope">
                <el-progress :percentage="scope.row.进度" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="序检" width="70">
              <template slot-scope="scope">
                <div v-if =" scope.row.进度 == 100 & scope.row.序检 == 0 "  class="status-light status-light-orange"  />
                <div v-else class="status-light" :class="scope.row.序检 ? 'status-light-green' : 'status-light-gray'" />
              </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="120" />
            <el-table-column align="center" prop="派工特殊说明" label="派工特殊备注" width="120" />
            <el-table-column align="center" label="编辑" width="120">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="editTask(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
            <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>
        </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="editDialogVisible" title="编辑任务信息" width="600px" center>
      <el-form ref="editForm" :model="editForm" label-width="140px" size="mini">
        <el-form-item label="优先级">
          <el-select v-model="editForm.优先级" 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="editForm.未完成说明" :rows="2" type="textarea" placeholder="请输入未完成说明" />
        </el-form-item>
        <el-form-item label="派工特殊备注">
          <el-input v-model="editForm.派工特殊说明" :rows="3" type="textarea" placeholder="请输入派工特殊备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button :loading="editSubmitLoading" type="primary" @click="submitEditForm">确 定</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: '',
      station: '',
      productionStatus: '全部',
      completionTime: [],
      loading: false,
      tableData: [],
      tableData2: [],
      selectedRow: null,
      editDialogVisible: false,
      editSubmitLoading: false,
      currentRow: {},
      editForm: {
        优先级: '',
        未完成说明: '',
        派工特殊说明: ''
      },
      taskAdjustVisible: false,
      taskSubmitLoading: false,
      stationOptions: [],
      taskForm: {
        指派对象: '',
        指派对象编号: '',
        指派数量: 0,
        计划开始时间: '',
        计划完成时间: '',
        最晚开始时间: '',
        派工特殊说明: ''
      },
      checkList: [],
      Doingoptions:[],
      Doing:"",
      dialogadjust:false,
      formData:[],
      // 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.产品编码} | 分配数量：${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.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
    },
    WorkTimeSum(tdata) {
      var param = []
      param.push(['计划开工_Start', this.completionTime ? this.completionTime[0] : ''])
      param.push(['计划开工_End', this.completionTime ? this.completionTime[1] : ''])
      var Data = this.CreateData('11', 'MES_ProductTask_WorkTimeSum', param)
      this.ExecDatabase(Data).then(response => {
        this.loading = false
        tdata.forEach(item => {
          response.data.forEach(itemtime => {
            if (itemtime.TaskAID == item.TaskAID & itemtime.工序名称 == item.工序名称) {
              item.总工时 = itemtime.总工时
            }
          })
        })
        var newtdata = tdata.reduce((acc, item) => {
          const key = `${item.指派对象}【${item.计划开始时间}】`; // 创建一个唯一的键来区分不同的组
          if(item.指派对象 ){
            if (!acc[key]) {
              acc[key] = []; // 如果键不存在，初始化一个空数组
            }
              acc[key].push(item); // 将当前项添加到对应的数组中
            return acc
          }
          return acc
        }, {}); // 初始值为一个空对象{}
        this.tableData2 = newtdata
        console.log(newtdata)
      }).catch(() => {
          this.loading = false
      })

    },
    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 ? this.completionTime[0] : ''])
      param.push(['要求完工日期2', this.completionTime ? this.completionTime[1] : ''])
      param.push(['排产状态', this.productionStatus])
      param.push(['工位', this.Doing.toString()])

      var Data = this.CreateData('11', 'MES_ProductAdmin_Query', param)
      this.ExecDatabase(Data).then(response => {
        this.loading = false
        this.WorkTimeSum(response.data)
        if (response.data.length !== 0) {
          this.tableData = response.data
        }
      }).catch(() => {
        this.loading = false
      })
    },
    handleRowClick(row) {
      this.selectedRow = row
      console.log(row)
    },
    // 获取工位列表
    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.taskForm.指派对象编号 = selected ? selected.code : ''
    },
    // 提交派工调整
    editTask(row) {
      this.currentRow = row
      this.editForm = {
        优先级: row.优先级 || '',
        未完成说明: row.未完成说明 || '',
        派工特殊说明: row.派工特殊说明 || ''
      }
      this.editDialogVisible = true
    },
    submitEditForm() {
      this.editSubmitLoading = true
      const params = []
      params.push(['订单号', this.currentRow.订单号])
      params.push(['订单行号', this.currentRow.订单行号])
      params.push(['订单拆分内码', this.currentRow.拆分内码])
      params.push(['优先级', this.editForm.优先级])
      params.push(['未完成说明', this.editForm.未完成说明])
      params.push(['派工特殊说明', this.editForm.派工特殊说明])
      params.push(['最后编辑人', this.$store.state.user.name])

      const Data = this.CreateData('12', 'MES_OrderPlanned_DescriptionEdit', params)
      this.ExecDatabase(Data).then(() => {
        this.$message.success('保存成功')
        this.editDialogVisible = false
        this.searchTable()
      }).catch(() => {
        this.$message.error('保存失败')
      }).finally(() => {
        this.editSubmitLoading = 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.拆分内码])
        // params.push(['计划开始时间', startTime])
        // params.push(['计划完成时间', endTime])
        
        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()
          this.donesearchTable()
        })
      }).catch(() => {
        if (revertCallback) revertCallback()
      })
    }
  }
}
</script>
  
<style scoped>
.search-container {
  margin-bottom: 20px;
}

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

.status-light {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
}
.status-light-orange {
  background-color: #e4a629;
}

.status-light-green {
  background-color: #67C23A;
}

.status-light-gray {
  background-color: #909399;
}

.dialog-footer {
  text-align: right;
}
/* .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>
  