<template>
  <Dialog v-model="previewVisible" title="排产甘特图预览" width="100%" align-center>
    <ScheduleGanttPanelEditable :schedule-list="previewScheduleList" height="800px" />
    <template #footer>
      <el-button type="primary" :loading="previewSaveLoading" @click="handlePreviewSave">保存</el-button>
      <el-button @click="previewVisible = false">关闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { PlanApi } from '@/api/mes/plan'
import ScheduleGanttPanelEditable from './ScheduleGanttPanelEditable.vue'
import dayjs from 'dayjs'

defineOptions({ name: 'TaskSchedulePreviewDialog' })

const props = defineProps<{
  modelValue: boolean
  scheduleList: any[]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'saved'): void
}>()

const message = useMessage()
const previewSaveLoading = ref(false)

const previewVisible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit('update:modelValue', value)
})

const previewScheduleList = computed(() => (Array.isArray(props.scheduleList) ? props.scheduleList : []))

const handlePreviewSave = async () => {
  const createReqVOList = previewScheduleList.value.flatMap((device: any) => {
    const plans = Array.isArray(device?.plans) ? device.plans : []
    return plans
      .filter((plan: any) => String(plan?.sourceType ?? '').toUpperCase() === 'CURRENT')
      .map((plan: any) => {
        const startValue = dayjs(plan?.planStartTimeStr)
        const endValue = dayjs(plan?.planEndTimeStr)
        const deliveryDateValue = dayjs(plan?.deliveryDateStr)
        const latestStartValue = dayjs(plan?.latestStartTimeStr)
        return {
          productId: plan?.productId,
          taskId: plan?.taskId,
          taskDetailId: plan?.taskDetailId,
          planNumber: Number(plan?.planNumber ?? 0),
          finishNumber: Number(plan?.finishNumber ?? 0),
          isCode: typeof plan?.isCode === 'boolean' ? plan.isCode : true,
          isPreProduction: Number(plan?.isPreProduction ?? 0),
          planStartTime: startValue.isValid() ? startValue.valueOf() : undefined,
          planEndTime: endValue.isValid() ? endValue.valueOf() : undefined,
          reyaNumber: Number(plan?.reyaNumber ?? plan?.planNumber ?? 0),
          workerId: plan?.workerId,
          feedingPipeline: plan?.feedingPipeline ?? device?.deviceId,
          deviceId: device?.deviceId ?? plan?.deviceId,
          deliveryDate: deliveryDateValue.isValid() ? deliveryDateValue.valueOf() : undefined,
          latestStartTime: latestStartValue.isValid() ? latestStartValue.valueOf() : undefined
        }
      })
  })

  if (!createReqVOList.length) {
    message.warning('暂无可保存的计划数据')
    return
  }

  previewSaveLoading.value = true
  try {
    await PlanApi.createBatch({ createReqVOList })
    message.success('排产计划保存成功')
    previewVisible.value = false
    emit('saved')
  } finally {
    previewSaveLoading.value = false
  }
}
</script>
