<template>
  <XtfConfigProvider class="demo-theme-root" :theme="demoTheme">
  <scroll-view class="lazy-demo-scroll" direction="vertical" :style="{ height: viewportHeight + 'px' }">
    <view class="lazy-demo-page">
      <text class="lazy-demo-title">图片懒加载</text>
      <text class="lazy-demo-label">首屏 · 本地 Logo</text>
      <XtfLazyload ref="firstImage" :src="firstSrc" :threshold="0" :height="240" fit="aspectFit"
        @load="record('first', 'load', $event)" @error="record('first', 'error', $event)" />
      <text class="lazy-demo-state">first · {{ states[0] }} · load {{ loads[0] }} / error {{ errors[0] }}</text>

      <view class="lazy-demo-gap" :style="{ height: viewportHeight * 2 + 'px' }" />
      <text class="lazy-demo-label">同排对照 · threshold 0 / 400 rpx</text>
      <view class="lazy-demo-row">
        <view class="lazy-demo-column">
          <XtfLazyload ref="zeroImage" :src="zeroSrc" :threshold="0" :height="240" fit="aspectFit"
            @load="record('zero', 'load', $event)" @error="record('zero', 'error', $event)" />
          <text class="lazy-demo-state">zero · {{ states[1] }} · {{ loads[1] }}/{{ errors[1] }}</text>
        </view>
        <view class="lazy-demo-column">
          <XtfLazyload ref="earlyImage" :src="earlySrc" threshold="400" :height="240" fit="aspectFit" :placeholder="placeholderSrc"
            @load="record('early', 'load', $event)" @error="record('early', 'error', $event)" />
          <text class="lazy-demo-state">early · {{ states[2] }} · {{ loads[2] }}/{{ errors[2] }}</text>
        </view>
      </view>

      <view class="lazy-demo-gap" :style="{ height: viewportHeight + 'px' }" />
      <text class="lazy-demo-label">错误占位图</text>
      <XtfLazyload ref="fallbackImage" :src="fallbackSrc" :error-img="errorSrc" :height="240" fit="aspectFit"
        @load="record('fallback', 'load', $event)" @error="record('fallback', 'error', $event)" />
      <text class="lazy-demo-state">fallback · {{ states[3] }} · {{ loads[3] }}/{{ errors[3] }}</text>

      <text class="lazy-demo-label">自定义插槽 · 坏图换好 · 手动重试</text>
      <XtfLazyload ref="switchImage" :src="switchSrc" :height="240" fit="aspectFit"
        @load="record('switch', 'load', $event)" @error="record('switch', 'error', $event)">
        <template #loading><text class="lazy-demo-slot">图片加载中</text></template>
        <template #error="{ retry }"><text class="lazy-demo-slot" @click="retry()">图片不可用，点击重试</text></template>
      </XtfLazyload>
      <text class="lazy-demo-state">switch · {{ states[4] }} · {{ loads[4] }}/{{ errors[4] }}</text>
      <button class="lazy-demo-button" @click="replaceSource(true)">换好图</button>
      <button class="lazy-demo-button" @click="replaceSource(false)">换坏图</button>
      <button class="lazy-demo-button" @click="retryImage">重试当前图片</button>

      <text class="lazy-demo-label">空源</text>
      <XtfLazyload ref="emptyImage" src="" :height="160"
        @load="record('empty', 'load', $event)" @error="record('empty', 'error', $event)" />
      <text class="lazy-demo-state">empty · {{ states[5] }} · {{ loads[5] }}/{{ errors[5] }}</text>
      <text v-for="(line, index) in logs" :key="index" class="lazy-demo-log">{{ line }}</text>
    </view>
  </scroll-view>
  </XtfConfigProvider>
</template>

<script setup lang="uts">
import { useDemoTheme } from '@/pages/demo-theme.uts'
import XtfConfigProvider from '@/uni_modules/xtf-linkuiunix/components/xtf-config-provider/xtf-config-provider.uvue'
const demoTheme = useDemoTheme()
import { onBeforeUnmount, onMounted, ref, watch } from "vue"
import XtfLazyload from "@/uni_modules/xtf-linkuiunix/components/xtf-lazyload/xtf-lazyload.uvue"

const viewportHeight = uni.getWindowInfo().windowHeight
const session = Date.now().toString()
const cacheBust = uni.getAppBaseInfo().uniPlatform == "web"
function logo(name: string): string {
  return "/static/logo.png" + (cacheBust ? "?lazy-demo=" + name + "-" + session : "")
}
function missing(name: string): string {
  return "/static/lazy-demo-missing.png" + (cacheBust ? "?lazy-demo=" + name + "-" + session : "")
}
const firstSrc = logo("first")
const zeroSrc = logo("zero")
const earlySrc = logo("early")
const placeholderSrc = logo("placeholder")
const fallbackSrc = missing("fallback")
const errorSrc = logo("errorImg")
const switchSrc = ref(missing("switch"))
const firstImage = ref<InstanceType<typeof XtfLazyload> | null>(null)
const zeroImage = ref<InstanceType<typeof XtfLazyload> | null>(null)
const earlyImage = ref<InstanceType<typeof XtfLazyload> | null>(null)
const fallbackImage = ref<InstanceType<typeof XtfLazyload> | null>(null)
const switchImage = ref<InstanceType<typeof XtfLazyload> | null>(null)
const emptyImage = ref<InstanceType<typeof XtfLazyload> | null>(null)
const names = ["first", "zero", "early", "fallback", "switch", "empty"]
const states = ref(["loading", "loading", "loading", "loading", "loading", "error"])
const loads = ref([0, 0, 0, 0, 0, 0])
const errors = ref([0, 0, 0, 0, 0, 0])
const logs = ref<string[]>([])
function log(message: string): void {
  const line = Date.now().toString() + " " + message
  console.log("[lazy-demo] " + line)
  logs.value = [line, ...logs.value].slice(0, 40)
}
function record(name: string, kind: string, event: any): void {
  const index = names.indexOf(name)
  if (kind == "load") loads.value[index]++
  else errors.value[index]++
  log(name + " " + kind + " " + JSON.stringify(event.detail))
  console.log("[lazy-demo] " + name + " " + kind + " native event", event)
}
function replaceSource(good: boolean): void {
  switchSrc.value = good ? logo("switch-good-" + Date.now().toString()) : missing("switch-bad-" + Date.now().toString())
  log("switch src=" + switchSrc.value)
}
function retryImage(): void {
  log("switch resetLoader")
  switchImage.value?.resetLoader()
}
const stopStates = watch(() => [firstImage.value?.state, zeroImage.value?.state, earlyImage.value?.state,
  fallbackImage.value?.state, switchImage.value?.state, emptyImage.value?.state], (values) => {
  values.forEach((value, index) => {
    if (value != null && value != states.value[index]) {
      states.value[index] = value
      log(names[index] + " state=" + value)
    }
  })
}, { flush: "sync" })
onMounted(() => { names.forEach((name, index) => log(name + " initial=" + states.value[index])) })
onBeforeUnmount(() => stopStates())
</script>

<style>
.lazy-demo-scroll { display: flex; flex-direction: column; flex: 1; width: 100%; min-height: 0; }
.lazy-demo-page { display: flex; flex-direction: column; flex-shrink: 0; width: 100%; padding: 24rpx; background-color: var(--xtf-color-page, #f8fafc); }
.lazy-demo-title { color: var(--xtf-color-text, #0f172a); font-size: 36rpx; font-weight: 700; }
.lazy-demo-label { margin-top: 24rpx; margin-bottom: 16rpx; color: var(--xtf-color-text-secondary, #334155); font-size: 26rpx; }
.lazy-demo-state { margin-top: 12rpx; color: var(--xtf-color-text-secondary, #475569); font-size: 22rpx; }
.lazy-demo-gap { display: flex; flex-direction: column; flex-shrink: 0; width: 100%; }
.lazy-demo-row { display: flex; flex-direction: row; width: 100%; justify-content: space-between; }
.lazy-demo-column { display: flex; flex-direction: column; width: 48%; }
.lazy-demo-slot { color: var(--xtf-color-text-secondary, #64748b); font-size: 26rpx; padding: 24rpx; }
.lazy-demo-button { margin-top: 16rpx; width: 100%; font-size: 26rpx; }
.lazy-demo-log { margin-top: 12rpx; color: var(--xtf-color-text-secondary, #475569); font-size: 20rpx; }
</style>
