<script setup lang="ts">
const props = defineProps<{
  waveType: '潮汐波' | '行星波'
  isDay?: boolean
}>()

const selectedWave = computed(() => props.waveType)

const selectedMode = ref('2日行星波')
const selectedDateType = ref('month')
const selectedStation = ref('武汉左岭镇站')
const selectedYear = ref('2017')
const selectedWindType = ref('uwind')
const selectedH = ref(94)
const selectedDate = ref('20170316')
const selectedMonth = ref('1')

const modes = [
  '2日行星波',
  '5日行星波',
  '10日行星波',
  '16日行星波',
]

const paths = ref([] as string[])
const stations = ref<Set<string>>(new Set())
const years = ref<Set<string>>(new Set())
const dates = ref<Set<string>>(new Set())

const queryUrl = computed(() => {
  const station = selectedStation.value
  const year = encodeURIComponent(selectedYear.value)
  const mode = selectedWave.value === '潮汐波'
    ? '潮汐波'
    : selectedMode.value
  const windType = selectedWindType.value

  const query = new URLSearchParams()
  query.set('station', station)
  query.set('year', year)
  query.set('model_name', mode)
  query.set('wind_type', windType)
  query.set('H', (selectedH.value * 1000).toString())
  query.set('mode', props.isDay ? 'day' : selectedDateType.value)
  if (props.isDay) {
    const queryDay = `${selectedDate.value.slice(0, 4)}-${selectedDate.value.slice(4, 6)}-${selectedDate.value.slice(6, 8)}`
    query.set('day', queryDay)
  }
  if (!props.isDay && selectedDateType.value === 'month') {
    query.set('month', selectedMonth.value)
  }
  // const query = `?station=${station}&year=${year}&model_name=${mode}&wind_type=${windType}&H=${selectedH.value}`
  const path = `/radar/render/heatmap?${query}`
  return path
})

const urlModel = defineModel<string>()

syncRef(urlModel, queryUrl, { direction: 'rtl' })

onMounted(async () => {
  const resp = await baseFetch(`/radar/metadata`).json()
  const data = await resp.data.value
  // use regex to extract the year from the path,
  // ./radar/data\\武汉左岭镇站\\2017\\ZLT_MET01_DLL_L21_01D_20170316.txt
  const station_pattern = /data\/radar\/(.*?)\//
  const year_pattern = /(\d{4})\/ZLT_/
  const date_pattern = /01D_(\d{8})\.txt/
  const pairs = data.map((source_text: string) => {
    const station = source_text.match(station_pattern)?.[1]
    const year = source_text.match(year_pattern)?.[1]
    const date = source_text.match(date_pattern)?.[1]
    return { station, year, date }
  })
  pairs.forEach(({ station, year, date }: {
    station: string
    year: string
    date: string
  }) => {
    stations.value.add(station)
    years.value.add(year)
    dates.value.add(date)
  })

  paths.value = data
  if (props.isDay) {
    selectedDate.value = Array.from(dates.value).filter(
      d => d.startsWith(`${selectedYear.value}${selectedMonth.value.padStart(2, '0')}`),
    )[0]
  }
})

watch([selectedYear, selectedMonth], () => {
  selectedDate.value = Array.from(dates.value).filter(
    d => d.startsWith(`${selectedYear.value}${selectedMonth.value.padStart(2, '0')}`),
  )[0]
})
</script>

<template>
  <DenseFramework :image-query="queryUrl">
    <div>
      <div flex="~ col gap-3" py-3>
        <div v-if="selectedWave === '行星波'">
          <Label>行星波周期</Label>
          <Tabs v-model="selectedMode" default-value="2日行星波">
            <TabsList class="grid grid-cols-4 w-full">
              <TabsTrigger v-for="m in modes" :key="m" :value="m">
                {{ m.replace("行星波", "") }}
              </TabsTrigger>
            </TabsList>
          </Tabs>
        </div>
        <Label for="wind_type">风类型</Label>
        <Tabs id="wind_type" v-model="selectedWindType" default-value="uwind">
          <TabsList class="grid grid-cols-2 w-full">
            <TabsTrigger value="uwind">
              纬向风
            </TabsTrigger>
            <TabsTrigger value="vwind">
              经向风
            </TabsTrigger>
          </TabsList>
        </Tabs>
        <div v-if="!props.isDay">
          <Label for="H">日期类型</Label>
          <Tabs id="date_type" v-model="selectedDateType" default-value="month">
            <TabsList class="grid grid-cols-2 w-full">
              <!-- <TabsTrigger value="day">
                日
              </TabsTrigger> -->
              <TabsTrigger value="month">
                月
              </TabsTrigger>
              <TabsTrigger value="year">
                年
              </TabsTrigger>
            </TabsList>
          </Tabs>
        </div>
        <Label>观测站</Label>
        <Select v-model="selectedStation">
          <SelectTrigger>
            <SelectValue placeholder="Select a fruit" />
          </SelectTrigger>
          <SelectContent>
            <SelectGroup>
              <SelectLabel>观测站</SelectLabel>
              <SelectItem v-for="station in stations" :key="station" :value="station">
                {{ station }}
              </SelectItem>
            </SelectGroup>
          </SelectContent>
        </Select>
        <Label>高度（km）</Label>
        <NumberField
          id="start"
          v-model:model-value="selectedH" :format-options="{
            useGrouping: false,
          }" :default-value="94"
          :step="2"
          :max="110"
          :min="70"
        >
          <NumberFieldContent>
            <NumberFieldDecrement />
            <NumberFieldInput />
            <NumberFieldIncrement />
          </NumberFieldContent>
        </NumberField>
        <Label>年份</Label>
        <Select v-model="selectedYear">
          <SelectTrigger>
            <SelectValue placeholder="Select a fruit" />
          </SelectTrigger>
          <SelectContent>
            <SelectGroup>
              <SelectLabel>年</SelectLabel>
              <SelectItem v-for="year in years" :key="year" :value="year">
                {{ year }}
              </SelectItem>
            </SelectGroup>
          </SelectContent>
        </Select>

        <div v-if="selectedDateType === 'month'">
          <Label>月份</Label>
          <Select v-model="selectedMonth">
            <SelectTrigger>
              <SelectValue placeholder="Select a fruit" />
            </SelectTrigger>
            <SelectContent>
              <SelectGroup>
                <SelectLabel>月</SelectLabel>
                <SelectItem
                  v-for="month in [
                    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
                  ]" :key="month" :value="month.toString()"
                >
                  {{ month }}
                </SelectItem>
              </SelectGroup>
            </SelectContent>
          </Select>
        </div>
        <div v-if="props.isDay ">
          <Label>日期</Label>
          <Select v-model="selectedDate">
            <SelectTrigger>
              <SelectValue placeholder="Select a fruit" />
            </SelectTrigger>
            <SelectContent>
              <SelectGroup>
                <SelectLabel>天</SelectLabel>
                <SelectItem
                  v-for="date in Array.from(dates).filter(
                    (d) => d.startsWith(`${selectedYear}${selectedMonth.padStart(2, '0')}`),
                  )" :key="date" :value="date"
                >
                  {{ date }}
                </SelectItem>
              </SelectGroup>
            </SelectContent>
          </Select>
        </div>
      </div>
    </div>
  </Denseframework>
</template>

  <style lang="scss" scoped>

  </style>
