<template>
  <Dialog v-model="previewVisible" :title="t('GanttChart.GanttPanel.dialogTitle')" width="100%" align-center>
    <div class="preview-options">
      <el-form :inline="true">
        <el-form-item :label="t('GanttChart.GanttPanel.workerLabel')">
          <el-select v-model="scheduleOptions.workerId" clearable filterable :placeholder="t('GanttChart.GanttPanel.workerPlaceholder')" style="width: 200px">
            <el-option v-for="item in workerList" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('GanttChart.GanttPanel.calcLossLabel')">
          <el-switch v-model="scheduleOptions.isCalculateLoss" />
        </el-form-item>
        <el-form-item>
          <el-button :type="ganttEditable ? 'primary' : 'default'" @click="toggleGanttEditable">
            <Icon :icon="ganttEditable ? 'ep:unlock' : 'ep:lock'" class="mr-4px" />
            {{ ganttEditable ? t('GanttChart.GanttPanel.unlockBtn') : t('GanttChart.GanttPanel.lockBtn') }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="!ganttEditable" @click="handleUndo">
            <Icon icon="ep:refresh-left" class="mr-4px" />
            {{ t('GanttChart.GanttPanel.undoBtn') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <ScheduleGanttPanelEditable ref="ganttPanelRef" :schedule-list="previewScheduleList" :editable="ganttEditable" height="800px" />
    <template #footer>
      <el-button type="primary" :loading="previewSaveLoading" @click="handlePreviewSave">{{ t('GanttChart.GanttPanel.buttonSave') }}</el-button>
      <el-button @click="previewVisible = false">{{ t('GanttChart.GanttPanel.buttonClose') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { PlanApi } from '@/api/mes/plan'
import * as UserApi from '@/api/system/user'
import ScheduleGanttPanelEditable from './ScheduleGanttPanelEditable.vue'
import dayjs from 'dayjs'
import { useI18n } from '@/hooks/web/useI18n'

defineOptions({ name: 'TaskSchedulePreviewDialog' })

const { t } = useI18n()

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 ganttEditable = ref(false)
const ganttPanelRef = ref<InstanceType<typeof ScheduleGanttPanelEditable>>()

const toggleGanttEditable = () => {
  ganttEditable.value = !ganttEditable.value
}

const handleUndo = () => {
  ganttPanelRef.value?.undo()
}

const workerList = ref<UserApi.UserVO[]>([])
const scheduleOptions = reactive({
  workerId: undefined as number | undefined,
  isCalculateLoss: true
})

const loadWorkerList = async () => {
  try {
    workerList.value = await UserApi.getSimpleUserList()
  } catch {
    workerList.value = []
  }
}

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

watch(previewVisible, (visible) => {
  if (visible) {
    if (workerList.value.length === 0) {
      loadWorkerList()
    }
    ganttEditable.value = false
  }
})

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: scheduleOptions.workerId ?? plan?.workerId,
          isCalculateLoss: scheduleOptions.isCalculateLoss,
          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(t('GanttChart.GanttPanel.warningNoPlanData'))
    return
  }

  previewSaveLoading.value = true
  try {
    await PlanApi.createBatch({ createReqVOList })
    message.success(t('GanttChart.GanttPanel.saveSuccess'))
    previewVisible.value = false
    emit('saved')
  } finally {
    previewSaveLoading.value = false
  }
}
</script>
