<template>
  <ContentWrap>
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
      <el-form-item :label="t('GanttChart.Index.searchTimeLabel')" prop="range">
        <el-date-picker
          v-model="queryRange"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="-"
          :start-placeholder="t('GanttChart.Index.startPlaceholder')"
          :end-placeholder="t('GanttChart.Index.endPlaceholder')"
          class="!w-360px"
        />
      </el-form-item>
      <el-form-item :label="t('GanttChart.Index.deviceLabel')" prop="deviceIds">
        <el-select v-model="queryParams.deviceIds" :placeholder="t('GanttChart.Index.devicePlaceholder')" clearable multiple collapse-tags class="!w-240px">
          <el-option v-for="item in deviceOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" />{{ t('GanttChart.Index.buttonSearch') }}</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" />{{ t('GanttChart.Index.buttonReset') }}</el-button>
        <el-button circle @click="toggleViewMode">
          <el-icon><Switch /></el-icon>
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap v-if="viewMode === 'gantt'">
    <div v-loading="loading">
      <ScheduleGanttPanel :schedule-list="filteredList" :editable="false" height="calc(100vh - 320px)" />
    </div>
  </ContentWrap>

  <div v-else style="width: 100%; height: calc(100vh - 60px)">
    <div v-loading="loading" style="width: 100%; height: 100%">
      <ScheduleCardView :schedule-list="filteredList" @refresh="getList" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { Switch } from '@element-plus/icons-vue'
import { PlanApi } from '@/api/mes/plan'
import ScheduleGanttPanel from '@/views/mes/components/ScheduleGanttPanel.vue'
import ScheduleCardView from '@/views/mes/ganttChart/components/ScheduleCardView.vue'
import dayjs from 'dayjs'
import { useI18n } from '@/hooks/web/useI18n'

defineOptions({ name: 'MesGanttChart' })

const { t } = useI18n()

type UnifiedPlan = {
  taskId: string | number
  taskDetailId: string | number
  taskCode: string
  productCode: string
  productName: string
  planNumber: number
  planStartTimeStr: string
  planEndTimeStr: string
  latestStartTimeStr: string
  deliveryDateStr: string
  scheduleDays: number
  sourceType: 'HISTORY'
}

type UnifiedDevice = {
  deviceId: string | number
  deviceName: string
  ratedCapacity?: number | string
  plans: UnifiedPlan[]
}

const loading = ref(false)
const queryFormRef = ref()
const scheduleList = ref<UnifiedDevice[]>([])
const viewMode = ref<'gantt' | 'card'>('gantt')

const buildDefaultRange = () => {
  const start = dayjs().startOf('month').startOf('day')
  const end = dayjs().endOf('month').endOf('day')
  return [start.format('YYYY-MM-DD HH:mm:ss'), end.format('YYYY-MM-DD HH:mm:ss')]
}

const queryRange = ref<string[]>(buildDefaultRange())
const queryParams = reactive({
  startTime: queryRange.value[0],
  endTime: queryRange.value[1],
  deviceIds: [] as (string | number)[]
})

const deviceOptions = computed(() =>
  scheduleList.value.map((device) => ({
    label: device.deviceName,
    value: device.deviceId
  }))
)

const filteredList = computed(() => {
  if (!queryParams.deviceIds.length) return scheduleList.value
  return scheduleList.value.filter((device) => queryParams.deviceIds.includes(device.deviceId))
})

const getList = async () => {
  loading.value = true
  try {
    const data = await PlanApi.getGanttByDevice({
      startTime: queryParams.startTime,
      endTime: queryParams.endTime
    })
    scheduleList.value = data
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  const [startTime, endTime] = Array.isArray(queryRange.value) ? queryRange.value : []
  queryParams.startTime = startTime || ''
  queryParams.endTime = endTime || ''
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryRange.value = buildDefaultRange()
  queryParams.startTime = queryRange.value[0]
  queryParams.endTime = queryRange.value[1]
  getList()
}

const toggleViewMode = () => {
  viewMode.value = viewMode.value === 'gantt' ? 'card' : 'gantt'
}

onMounted(() => {
  handleQuery()
})
</script>
