<template>
  <XtfConfigProvider class="demo-theme-root" :theme="demoTheme" :safe-area="true" :locale="english ? 'en-US' : 'zh-Hans'">
    <scroll-view class="dateformat-demo-scroll" direction="vertical">
      <view class="dateformat-demo-page">
        <view class="dateformat-demo-header">
          <text class="dateformat-demo-title">Dateformat 日期格式化</text>
        </view>

        <view class="dateformat-demo-section">
          <text class="dateformat-demo-heading">输入类型</text>
          <picker id="df-input-type" data-testid="df-input-type" :range="inputTypes" :value="inputType" @change="changeInputType">
            <view class="dateformat-demo-control"><text class="dateformat-demo-label">{{ inputTypes[inputType] }} ▾</text></view>
          </picker>
          <input id="df-input" data-testid="df-input" class="dateformat-demo-input" :value="inputText" @input="inputText = $event.detail.value" />
          <view class="dateformat-demo-result">
            <XtfDateformat id="df-input-result" data-testid="df-input-result" :date="inputDate" :threshold="[0, 0]" :format="format" />
          </view>
        </view>

        <view class="dateformat-demo-section">
          <text class="dateformat-demo-heading">格式 Token</text>
          <input id="df-format" data-testid="df-format" class="dateformat-demo-input" :value="format" @input="format = $event.detail.value" />
          <view class="dateformat-demo-result"><XtfDateformat id="df-token-result" data-testid="df-token-result" :date="tokenDate" :threshold="[0, 0]" :format="format" /></view>
          <view class="dateformat-demo-result"><XtfDateformat id="df-all-tokens" data-testid="df-all-tokens" :date="tokenDate" :threshold="[0, 0]" format="yyyy|yy|MM|M|dd|d|HH|hh|h|mm|m|ss|s|SSS|SS|S" /></view>
          <view class="dateformat-demo-actions">
            <button id="df-format-date" data-testid="df-format-date" class="dateformat-demo-button" size="mini" @click="format = 'yyyy-MM-dd'">日期</button>
            <button id="df-format-time" data-testid="df-format-time" class="dateformat-demo-button" size="mini" @click="format = 'HH:mm:ss.SSS'">时间</button>
          </view>
        </view>

        <view class="dateformat-demo-section">
          <text class="dateformat-demo-heading">相对时间更新</text>
          <view class="dateformat-demo-row"><text class="dateformat-demo-label">英文</text><switch id="df-locale" data-testid="df-locale" :checked="english" @change="english = $event.detail.value" /></view>
          <view class="dateformat-demo-row"><text class="dateformat-demo-label">自动刷新 1000ms</text><switch id="df-auto-toggle" data-testid="df-auto-toggle" :checked="autoRefresh" @change="autoRefresh = $event.detail.value" /></view>
          <view class="dateformat-demo-row"><text class="dateformat-demo-label">手动</text><XtfDateformat id="df-manual-result" data-testid="df-manual-result" ref="dateRef" :date="relativeDate" :threshold="[0, 3600000]" /></view>
          <view class="dateformat-demo-row"><text class="dateformat-demo-label">自动</text><XtfDateformat id="df-auto-result" data-testid="df-auto-result" :date="relativeDate" :threshold="[0, 3600000]" :refresh-rate="autoRefresh ? '1000' : 0" /></view>
          <view class="dateformat-demo-actions">
            <button id="df-refresh" data-testid="df-refresh" class="dateformat-demo-button" size="mini" @click="refresh">手动刷新</button>
            <button id="df-reset" data-testid="df-reset" class="dateformat-demo-button" size="mini" @click="resetRelative">重置</button>
          </view>
          <text id="df-refresh-count" data-testid="df-refresh-count" class="dateformat-demo-label">手动调用次数：{{ refreshCount }}</text>
        </view>

        <view class="dateformat-demo-section">
          <text class="dateformat-demo-heading">空值与异常输入</text>
          <view class="dateformat-demo-row"><text class="dateformat-demo-label">默认</text><XtfDateformat id="df-default" data-testid="df-default" /></view>
          <view v-for="item in edgeCases" :key="item.id" class="dateformat-demo-row">
            <text class="dateformat-demo-label">{{ item.label }}</text>
            <view class="dateformat-demo-edge"><XtfDateformat :id="item.id" :data-testid="item.id" :date="item.date" :threshold="[0, 0]" /></view>
          </view>
        </view>

        <view class="dateformat-demo-section">
          <text class="dateformat-demo-heading">阈值与未来时间</text>
          <button id="df-boundary-reset" data-testid="df-boundary-reset" class="dateformat-demo-button" size="mini" @click="boundaryNow = Date.now()">重置边界样例</button>
          <view v-for="item in boundaryCases" :key="item.id" class="dateformat-demo-row">
            <text class="dateformat-demo-label">{{ item.label }}</text>
            <XtfDateformat :key="item.id + boundaryNow.toString()" :id="item.id" :data-testid="item.id" :date="boundaryNow + item.offset" />
          </view>
          <view class="dateformat-demo-row"><text class="dateformat-demo-label">闰日跨月</text><XtfDateformat id="df-leap" data-testid="df-leap" :date="leapDate" :threshold="[0, 0]" /></view>
          <view class="dateformat-demo-row"><text class="dateformat-demo-label">跨年</text><XtfDateformat id="df-year" data-testid="df-year" :date="yearDate" :threshold="[0, 0]" /></view>
        </view>
      </view>
    </scroll-view>
  </XtfConfigProvider>
</template>

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

const inputTypes = ["毫秒", "秒（显式转毫秒）", "ISO 字符串", "Date（结构化构造）"]
const inputType = ref(0)
const samples = ["1709184123000", "1709184123", "2024-02-29T13:22:03+08:00", "2024,2,29,13,22,3"]
const inputText = ref(samples[0])
const format = ref("yyyy-MM-dd HH:mm:ss.SSS")
const tokenDate = new Date(2024, 1, 29, 13, 2, 3, 456)
const inputDate = computed((): any => {
  const text = inputText.value.trim()
  if (text.length == 0) return ""
  if (inputType.value == 0) return Number(text)
  if (inputType.value == 1) return Number(text) * 1000
  if (inputType.value == 2) return text
  // Date 模式采用固定字段顺序，不推测日期字符串格式。
  const fields = text.split(",")
  if (fields.length != 6) return null
  const values = fields.map((field: string): number => field.trim().length == 0 ? NaN : Number(field))
  if (values.some((value: number): boolean => !isFinite(value) || Math.floor(value) != value)) return null
  return new Date(values[0], values[1] - 1, values[2], values[3], values[4], values[5])
})
function changeInputType(event: UniPickerChangeEvent): void {
  inputType.value = Number(event.detail.value)
  inputText.value = samples[inputType.value]
}

const english = ref(false)
const autoRefresh = ref(true)
const relativeDate = ref(Date.now() - 5000)
const dateRef = ref<any>(null)
const refreshCount = ref(0)
function refresh(): void { dateRef.value?.refresh(); refreshCount.value += 1 }
function resetRelative(): void { relativeDate.value = Date.now() - 5000; refreshCount.value = 0 }

type EdgeCase = { id: string; label: string; date: any }
const edgeCases: EdgeCase[] = [
  { id: "df-empty", label: "空字符串", date: "" },
  { id: "df-null", label: "null", date: null },
  { id: "df-invalid", label: "非法字符串", date: "not-a-date" },
  { id: "df-object", label: "普通对象", date: {} },
  { id: "df-zero", label: "0 毫秒", date: 0 },
  { id: "df-nan", label: "NaN", date: NaN },
  { id: "df-infinity", label: "Infinity", date: Infinity },
  { id: "df-invalid-date", label: "Invalid Date", date: new Date(NaN) }
]
const boundaryNow = ref(Date.now())
type BoundaryCase = { id: string; label: string; offset: number }
const boundaryCases: BoundaryCase[] = [
  { id: "df-recent", label: "30 秒前", offset: -30000 },
  { id: "df-first-boundary", label: "60 秒前（下界）", offset: -60000 },
  { id: "df-relative", label: "30 分钟前", offset: -1800000 },
  { id: "df-second-boundary", label: "60 分钟前（上界）", offset: -3600000 },
  { id: "df-future-soon", label: "30 秒后", offset: 30000 },
  { id: "df-future", label: "30 分钟后", offset: 1800000 },
  { id: "df-future-absolute", label: "2 小时后", offset: 7200000 }
]
const leapDate = new Date(2024, 1, 29, 23, 59, 60)
const yearDate = new Date(2023, 11, 31, 23, 59, 60)
</script>

<style>
.dateformat-demo-scroll { display: flex; flex-direction: column; flex: 1; width: 100%; min-height: 0; }
.dateformat-demo-page { display: flex; flex-direction: column; padding: 16px; background-color: var(--xtf-color-page, #f8fafc); }
.dateformat-demo-header { display: flex; flex-direction: column; padding: 20px; background-color: #0f766e; }
.dateformat-demo-title { font-size: 24px; color: #ffffff; }
.dateformat-demo-section { display: flex; flex-direction: column; margin-top: 16px; padding-top: 16px; border-top-width: 1px; border-top-style: solid; border-top-color: var(--xtf-color-border, #cbd5e1); }
.dateformat-demo-heading { font-size: 18px; color: var(--xtf-color-text, #0f172a); margin-bottom: 12px; }
.dateformat-demo-label { font-size: 14px; color: var(--xtf-color-text-secondary, #475569); flex-shrink: 1; }
.dateformat-demo-control { display: flex; flex-direction: column; padding: 12px; border-radius: 4px; background-color: var(--xtf-color-surface-muted, #e2e8f0); }
.dateformat-demo-input { height: 44px; margin-top: 8px; padding: 8px; font-size: 14px; background-color: var(--xtf-color-surface, #ffffff); color: var(--xtf-color-text, #0f172a); border-width: 1px; border-style: solid; border-color: var(--xtf-color-border, #cbd5e1); border-radius: 4px; }
.dateformat-demo-result { display: flex; flex-direction: column; min-height: 32px; margin-top: 12px; }
.dateformat-demo-row { display: flex; flex-direction: row; flex-wrap: wrap; align-items: center; justify-content: space-between; min-height: 44px; margin-top: 8px; }
.dateformat-demo-edge { display: flex; flex-direction: column; min-width: 40px; min-height: 24px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: var(--xtf-color-border, #cbd5e1); }
.dateformat-demo-actions { display: flex; flex-direction: row; flex-wrap: wrap; margin-top: 12px; }
.dateformat-demo-button { margin: 0 12px 12px 0; }
</style>
