<script lang="ts" setup>
import type { ImageResult } from './ImageContainer.vue'
import {
  ResizableHandle,
  ResizablePanel,
  ResizablePanelGroup,
} from '~/components/ui/resizable'

const props = defineProps<{
  imageQuery: string
  extraErrorHandle?: (resp: Response) => {
    type: string
    message: string
  }
  extraResponseHandle?: (resp: Response) => Promise<ImageResult>
}>()

defineEmits(['submit'])
const imageResult = reactive<ImageResult>({
  result: 'idle',
  resourceId: '',
  message: '请你选择一个模式和日期',
})

const urlRef = computed(() => {
  return props.imageQuery
})

const { onFetchResponse, onFetchError, isFetching, execute } = baseFetch(
  urlRef,
  { immediate: false },
)
watch(isFetching, (fetching) => {
  if (fetching) {
    imageResult.result = 'pending'
  }
})

onFetchResponse(async (resp) => {
  if (props.extraResponseHandle) {
    const newResult = await props.extraResponseHandle(resp)
    imageResult.result = newResult.result
    imageResult.resourceId = newResult.resourceId
    imageResult.message = newResult.message
  }
  else {
    const blob = await resp.blob()
    const url = URL.createObjectURL(blob)
    imageResult.result = 'success'
    imageResult.resourceId = url
  }
})

onFetchError(async (error) => {
  imageResult.result = 'error'
  imageResult.message = error
})
</script>

<template>
  <div flex="~ row h-full items-begin justify-stretch gap-3 p-8 w-full">
    <ResizablePanelGroup
      id="demo-group-1"
      direction="horizontal"
      class="w-full border rounded-lg"
    >
      <ResizablePanel id="demo-panel-1" :default-size="200" py-5>
        <ParamsCard
          @submit="() => {
            $emit('submit')
            execute()
          }"
        >
          <slot />
        </ParamsCard>
      </ResizablePanel>
      <ResizableHandle id="demo-handle-1" />
      <ResizablePanel id="demo-panel-2" :default-size="500">
        <ImageContainer :image-result="imageResult" />
      </ResizablePanel>
    </ResizablePanelGroup>
  </div>
</template>
