<template>
  <XtfConfigProvider class="demo-theme-root" :theme="demoTheme" component-size="md" :safe-area="true">
    <scroll-view class="input-demo-scroll xtf-page-scroll" direction="vertical">
      <view id="input-demo" class="input-demo-page xtf-safe-bottom xtf-page-scroll-content">
        <view class="input-demo-header"><text class="input-demo-eyebrow">XTF LINKUI / COMPONENTS</text><text class="input-demo-title">Input 输入框</text></view>

        <view id="input-variants" class="input-demo-section">
          <text class="input-demo-heading">01 / 基础输入与变体</text>
          <XtfInput label="Surface" placeholder="输入账单名称" clearable prefix-icon="edit" />
          <XtfInput class="demo-gap" label="Outline" variant="outline" value="周末采购" />
          <XtfInput class="demo-gap" label="Underlined" variant="underlined" value="用于快速编辑" />
          <XtfInput class="demo-gap" label="Card" variant="card" placeholder="卡片表面" />
          <XtfInput class="demo-gap" label="Glass" variant="glass" placeholder="玻璃表面" />
          <XtfInput class="demo-gap" label="Borderless" variant="borderless" placeholder="无边框输入" />
        </view>

        <view id="input-states" class="input-demo-section">
          <text class="input-demo-heading">02 / 状态与访问限制</text>
          <XtfInput label="成功状态" status="success" message="名称可用" value="三月账单" show-status-icon />
          <XtfInput class="demo-gap" label="提醒状态" status="warning" message="接近本月预算" value="预算 900 元" show-status-icon />
          <XtfInput class="demo-gap" label="错误状态" status="error" message="请核对账单编号" value="INVALID" show-status-icon />
          <XtfInput class="demo-gap" label="只读值" value="系统自动生成" readonly />
          <XtfInput class="demo-gap" label="已禁用" value="已归档账单" disabled clearable />
        </view>

        <view id="input-password-scene" class="input-demo-section">
          <text class="input-demo-heading">03 / 密码与聚焦清除</text>
          <XtfInput id="input-password" v-model="password" label="登录密码" type="safe-password" show-password-toggle clearable placeholder="输入演示密码" />
          <text id="input-password-count" class="input-demo-result">密码长度：{{ password.length }}</text>
          <XtfInput id="input-clear-focus" class="demo-gap" v-model="clearText" label="联系人" clearable clear-trigger="focus" placeholder="联系人姓名" @focus="clearFocused = true" @blur="clearFocused = false" @clear="clearCount++" />
          <view class="input-demo-tools"><button id="input-clear-refill" class="input-demo-button" @click="clearText = '张三'">回填联系人</button></view>
          <text id="input-clear-result" class="input-demo-result">{{ clearFocused ? '已聚焦' : '未聚焦' }} / 清除次数：{{ clearCount }} / 当前值：{{ clearText }}</text>
        </view>

        <view id="input-amount-scene" class="input-demo-section">
          <text class="input-demo-heading">04 / 金额解析与格式化</text>
          <XtfInput id="input-amount" v-model="amount" label="账单金额" type="text" inputmode="decimal" :maxlength="30" :parser="parseAmount" :formatter="formatAmount" clearable placeholder="例如 1234.567 或 ￥1,234.50" @change="onAmountChange">
            <template #prefix><text class="slot-mark">¥</text></template>
            <template #suffix><text class="slot-mark">元</text></template>
          </XtfInput>
          <view class="input-demo-tools"><button id="input-amount-fill" class="input-demo-button" @click="fillAmount">回填 1234.50</button></view>
          <text id="input-amount-raw" class="input-demo-result">原始金额（页面解析）：{{ amountRaw }}</text>
          <text id="input-amount-display" class="input-demo-result">显示值 / v-model：{{ amount }}</text>
        </view>

        <view id="input-rules-scene" class="input-demo-section">
          <text class="input-demo-heading">05 / 同步规则与触发时机</text>
          <XtfInput id="input-phone" v-model="phone" label="手机号" type="tel" :maxlength="11" clearable :rules="phoneRules" show-status-icon placeholder="输入 11 位手机号" />
          <XtfInput id="input-required" class="demo-gap" label="必填联系人" required placeholder="联系人姓名" />
          <view class="input-demo-row"><text class="input-demo-label">规则触发</text><picker id="input-rule-trigger" class="input-demo-picker" :range="ruleTriggers" :value="ruleTriggerIndex" @change="onRuleTriggerChange"><text class="input-demo-picker-text">{{ ruleTriggers[ruleTriggerIndex] }}</text></picker></view>
          <XtfInput id="input-rule-code" :key="ruleTriggerIndex" v-model="ruleCode" label="报销码" :rules="codeRules" show-status-icon confirm-type="done" placeholder="TF-2026" />
          <text id="input-rule-result" class="input-demo-result">{{ ruleResult }}</text>
          <text id="input-rule-count" class="input-demo-result">同步校验调用：{{ ruleCalls }}</text>
        </view>

        <view id="input-textarea-scene" class="input-demo-section">
          <text class="input-demo-heading">06 / 备注与字数上限</text>
          <view class="input-demo-row"><text class="input-demo-label">自动增高</text><switch id="input-auto-height" :checked="autoHeight" color="#17796b" @change="autoHeight = $event.detail.value" /></view>
          <XtfInput id="input-textarea" v-model="note" label="账单备注" type="textarea" :rows="3" :maxlength="120" show-count :auto-height="autoHeight" placeholder="记录这笔账单的说明" />
          <view class="input-demo-tools"><button id="input-note-fill" class="input-demo-button" @click="fillNote">填入多行备注</button><button id="input-note-limit" class="input-demo-button" @click="fillNoteLimit">填满 120 字</button><button id="input-note-reset" class="input-demo-button" @click="note = ''">清空备注</button></view>
          <text id="input-note-count" class="input-demo-result">{{ note.length }} / 120</text>
          <XtfInput id="input-word-limit" class="demo-gap" v-model="shortNote" label="摘要" :maxlength="20" show-word-limit placeholder="账单摘要" />
        </view>

        <view id="input-slots-scene" class="input-demo-section">
          <text class="input-demo-heading">07 / 前后缀与消息插槽</text>
          <XtfInput id="input-slots" v-model="slotValue" label="结算金额" :maxlength="20" show-count placeholder="输入结算金额">
            <template #prefix><text id="input-slot-prefix" class="slot-mark">¥</text></template>
            <template #suffix><text id="input-slot-suffix" class="slot-mark">元</text></template>
            <template #message><text id="input-slot-message" class="slot-message">结算金额：{{ slotValue.length > 0 ? slotValue : '待填写' }}</text></template>
          </XtfInput>
        </view>

        <view id="input-controlled-scene" class="input-demo-section">
          <text class="input-demo-heading">08 / 外部赋值、重置与焦点</text>
          <XtfInput id="input-controlled" v-model="controlledValue" label="账单名称" :focus="requestedFocus" clearable @focus="controlledFocused = true" @blur="onControlledBlur" />
          <view class="input-demo-tools"><button id="input-controlled-fill" class="input-demo-button" @click="controlledValue = '外部回填账单'">外部赋值</button><button id="input-controlled-reset" class="input-demo-button" @click="resetControlled">重置</button><button id="input-controlled-focus" class="input-demo-button" @click="requestFocus">聚焦</button></view>
          <text id="input-controlled-result" class="input-demo-result">{{ controlledFocused ? '已聚焦' : '未聚焦' }} / 当前值：{{ controlledValue }}</text>
        </view>

        <view id="input-events-scene" class="input-demo-section">
          <text class="input-demo-heading">09 / 搜索与事件</text>
          <XtfInput id="input-search" v-model="keyword" label="查找账单" prefix-icon="search" search-action-text="搜索" confirm-type="search" clearable placeholder="输入关键词" @input="recordEvent('input', $event)" @change="recordEvent('change', $event)" @blur="recordEvent('blur', keyword)" @confirm="recordEvent('confirm', $event)" @search="onSearch" />
          <text id="input-search-result" class="input-demo-result">{{ searchResult }}</text>
          <view class="input-demo-tools"><button id="input-events-reset" class="input-demo-button" @click="events = []">清空事件</button></view>
          <view id="input-event-log" class="input-demo-log"><text v-if="events.length == 0" class="input-demo-result">暂无事件</text><text v-for="entry in events" :key="entry.id" class="input-demo-event">{{ entry.id }}. {{ entry.name }}：{{ entry.value }}</text></view>
        </view>
      </view>
    </scroll-view>
  </XtfConfigProvider>
</template>

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

type InputRule = { required?: boolean, minLength?: number, maxLength?: number, pattern?: string, validator?: (value: string, rule: InputRule) => boolean, message?: string, trigger?: string }
type InputFormatterContext = { type: string, value: string }
type EventEntry = { id: number, name: string, value: string }
const password = ref("")
const clearText = ref("张三")
const clearFocused = ref(false)
const clearCount = ref(0)
const amount = ref("")
const amountRaw = ref("")
const phone = ref("")
const phoneRules: InputRule[] = [{ pattern: "^1[3-9]\\d{9}$", message: "请输入有效的 11 位手机号", trigger: "blur" }]
const ruleTriggers = ["change", "blur", "confirm", "all"]
const ruleTriggerIndex = ref(1)
const ruleCode = ref("")
const ruleCalls = ref(0)
const ruleResult = ref("尚未校验")
const codeRules = computed((): InputRule[] => [{ validator: validateCode, message: "报销码须为 TF- 加四位数字", trigger: ruleTriggers[ruleTriggerIndex.value] }])
const note = ref("")
const shortNote = ref("本月日常采购汇总，待复核确认金额")
const autoHeight = ref(true)
const slotValue = ref("")
const controlledValue = ref("")
const requestedFocus = ref(false)
const controlledFocused = ref(false)
const keyword = ref("")
const searchResult = ref("尚未搜索")
const events = ref<EventEntry[]>([])
let eventId = 0

function parseAmount(value: string): string {
  const cleaned = value.replace(/[^0-9.]/g, "")
  const point = cleaned.indexOf(".")
  if (point < 0) return cleaned
  const integer = cleaned.slice(0, point)
  return (integer.length > 0 ? integer : "0") + "." + cleaned.slice(point + 1).replace(/\./g, "").slice(0, 2)
}
function formatAmount(value: string, _context: InputFormatterContext): string {
  const parts = value.split(".")
  const integer = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")
  return parts.length > 1 ? integer + "." + parts[1] : integer
}
function onAmountChange(value: string): void { amountRaw.value = parseAmount(value) }
function fillAmount(): void {
  amountRaw.value = "1234.50"
  // 外部赋值只触发组件的值监听，不会经过 parser / formatter。
  amount.value = formatAmount(amountRaw.value, { type: "text", value: amount.value })
}
function validateCode(value: string, rule: InputRule): boolean {
  const valid = /^TF-\d{4}$/.test(value)
  ruleCalls.value++
  ruleResult.value = (rule.trigger ?? "all") + " / " + (valid ? "通过" : "未通过") + " / " + (value.length > 0 ? value : "（空）")
  return valid
}
function onRuleTriggerChange(event: UniPickerChangeEvent): void {
  ruleTriggerIndex.value = Number(event.detail.value)
  ruleCalls.value = 0
  ruleResult.value = "尚未校验"
}
function fillNote(): void { note.value = "周末采购\n蔬菜水果与日用品\n已核对小票\n等待报销\n备注附件齐全" }
function fillNoteLimit(): void { note.value = "采购备注已核对".repeat(18).slice(0, 120) }
function resetControlled(): void { controlledValue.value = ""; requestedFocus.value = false }
async function requestFocus(): Promise<void> { requestedFocus.value = false; await nextTick(); requestedFocus.value = true }
function onControlledBlur(): void { controlledFocused.value = false; requestedFocus.value = false }
function recordEvent(name: string, value: string): void {
  eventId++
  events.value.push({ id: eventId, name, value: value.length > 0 ? value.slice(0, 60) : "（空）" })
  if (events.value.length > 8) events.value.shift()
}
function onSearch(value: string): void {
  searchResult.value = value.trim().length > 0 ? "已搜索：" + value : "请输入搜索内容"
  recordEvent("search", value)
}
</script>

<style>
.input-demo-scroll { display: flex; flex-direction: column; flex: 1; width: 100%; height: 100%; min-height: 0; }
.input-demo-page { display: flex; flex-direction: column; width: 100%; padding: 24rpx; background-color: var(--xtf-color-page, #f8fafc); }
.input-demo-header { display: flex; flex-direction: column; padding: 12rpx 0 24rpx; }
.input-demo-eyebrow { color: #17796b; font-size: 22rpx; }
.input-demo-title { margin-top: 8rpx; color: var(--xtf-color-text, #232d2b); font-size: 38rpx; font-weight: 700; }
.input-demo-section { display: flex; flex-direction: column; padding: 24rpx 0; border-top-width: 1rpx; border-top-style: solid; border-top-color: var(--xtf-color-border, #cbd5e1); }
.input-demo-heading { margin-bottom: 20rpx; color: var(--xtf-color-text, #232d2b); font-size: 28rpx; font-weight: 600; }
.demo-gap { margin-top: 18rpx; }
.input-demo-row { display: flex; flex-direction: row; align-items: center; justify-content: space-between; margin-top: 16rpx; margin-bottom: 16rpx; }
.input-demo-label { color: var(--xtf-color-text-secondary, #475569); font-size: 24rpx; }
.input-demo-picker { display: flex; flex-direction: column; width: 180rpx; padding: 12rpx 20rpx; border-radius: 8rpx; background-color: #e6f3ef; }
.input-demo-picker-text { color: #17796b; font-size: 24rpx; text-align: center; }
.input-demo-tools { display: flex; flex-direction: row; flex-wrap: wrap; margin-top: 12rpx; }
.input-demo-button { display: flex; flex-direction: row; align-items: center; justify-content: center; min-height: 64rpx; margin: 0 12rpx 8rpx 0; padding: 8rpx 20rpx; border-radius: 8rpx; background-color: #e6f3ef; color: #17796b; font-size: 24rpx; line-height: 36rpx; }
.input-demo-result { margin-top: 10rpx; color: var(--xtf-color-text-secondary, #475569); font-size: 24rpx; line-height: 36rpx; word-break: break-all; }
.slot-mark { color: var(--xtf-color-primary, #2563eb); font-size: 28rpx; font-weight: 700; }
.slot-message { flex: 1; min-width: 0; color: #17796b; font-size: 22rpx; word-break: break-all; }
.input-demo-log { display: flex; flex-direction: column; min-height: 96rpx; padding: 12rpx 0; }
.input-demo-event { color: var(--xtf-color-text-secondary, #475569); font-size: 22rpx; line-height: 34rpx; word-break: break-all; }
</style>
