<template>
  <XtfConfigProvider class="demo-theme-root" :theme="demoTheme">
    <scroll-view class="share-demo-scroll xtf-page-scroll" direction="vertical">
      <view class="share-demo-page xtf-page-scroll-content">
        <text class="share-demo-title">Share Sheet</text>
        <view class="share-demo-section">
          <text class="share-demo-heading">基础分享面板</text>
          <XtfButton id="ss-basic-open" label="打开分享面板" @click="openScene('basic')" />
          <text id="ss-copy-result" class="share-demo-state">{{ copyResult }}</text>
        </view>
        <view class="share-demo-section">
          <text class="share-demo-heading">分组选择</text>
          <XtfButton id="ss-grouped-open" type="outline" label="渠道与工具" @click="openScene('grouped')" />
        </view>
        <view class="share-demo-section">
          <text class="share-demo-heading">普通与禁用选项</text>
          <XtfButton id="ss-disabled-open" type="outline" label="选择渠道" @click="openScene('disabled')" />
        </view>
        <view class="share-demo-section">
          <text class="share-demo-heading">自定义字段与业务数据</text>
          <XtfButton id="ss-payload-open" type="outline" label="订单操作" @click="openScene('payload')" />
          <text id="ss-payload-result" class="share-demo-state">{{ payloadResult }}</text>
        </view>
        <view class="share-demo-section">
          <text class="share-demo-heading">取消与遮罩</text>
          <view class="share-demo-row"><text class="share-demo-label">点击遮罩关闭</text><switch id="ss-overlay-toggle" :checked="overlayClosable" @change="overlayClosable = $event.detail.value" /></view>
          <XtfButton id="ss-cancel-open" type="outline" label="打开取消场景" @click="openScene('cancel')" />
        </view>
        <view class="share-demo-section">
          <text class="share-demo-heading">外部显隐</text>
          <XtfButton id="ss-external-open" type="outline" label="show 打开" @click="openScene('external')" />
          <view class="share-demo-gap"><XtfButton id="ss-external-timed" type="light" label="打开并于两秒后外部关闭" @click="openTimed" /></view>
          <text id="ss-visibility" class="share-demo-state">{{ 'modelValue=' + modelShow + '; show=' + externalShow }}</text>
        </view>
        <text id="ss-result" class="share-demo-state">{{ status }}</text>
        <view class="share-demo-gap"><XtfButton id="ss-log-clear" type="outline" size="sm" label="清空日志" @click="logs = []" /></view>
        <text id="ss-event-log" class="share-demo-log">{{ logs.join('\n') }}</text>
      </view>
    </scroll-view>
    <XtfShareSheet :model-value="scene == 'external' ? null : modelShow" :show="externalShow" :title="sheetTitle"
      :description="scene == 'payload' ? '订单 SB-20261019' : ''" :options="options" :close-on-click-overlay="scene == 'cancel' ? overlayClosable : true"
      @select="select" @cancel="record('cancel')" @update:show="updateShow" @update:modelValue="updateModel"
      @open="record('open')" @opened="record('opened')" @close="record('close')" @closed="record('closed')" />
  </XtfConfigProvider>
</template>

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

const scene = ref('basic')
const modelShow = ref(false)
const externalShow = ref(false)
const overlayClosable = ref(true)
const status = ref('等待选择')
const copyResult = ref('尚未复制')
const payloadResult = ref('尚未选择订单操作')
const logs = ref([] as string[])
let sequence = 0
let closeTimer: ReturnType<typeof setTimeout> | null = null
const link = 'https://example.com/orders/SB-20261019'
const basicOptions = [
  { key: 'system', label: '系统分享', icon: '↗', color: '#16a34a' },
  { key: 'copy', label: '复制链接', icon: '链', color: '#2563eb', url: link }
] as any[]
const options = computed((): any[] => {
  if (scene.value == 'grouped') return [
    [{ key: 'wechat', name: '微信好友', icon: '微', color: '#16a34a' }, { key: 'moments', label: '朋友圈', icon: '圈', color: '#0891b2' }],
    [{ key: 'copy', name: '复制链接', icon: '链', url: link }, { key: 'poster', name: '生成海报', icon: '图', color: '#e11d48' }]
  ] as any[]
  if (scene.value == 'disabled') return [
    { key: 'disabled', name: '不可用渠道', icon: '禁', disabled: true },
    { key: 'normal', label: '普通渠道', icon: '选', color: '#0891b2' },
    { key: '仅提供 key' }
  ] as any[]
  if (scene.value == 'payload') return [
    { key: 'order-detail', name: '查看订单', label: '不应展示此 label', icon: '单', payload: { orderId: 'SB-20261019', action: 'detail', amount: 128 } },
    { label: '标记订单', icon: '记', payload: { orderId: 'SB-20261019', action: 'mark', amount: 128 } },
    { text: '归档订单', icon: '档', payload: { orderId: 'SB-20261019', action: 'archive', amount: 128 } }
  ] as any[]
  return basicOptions
})
const sheetTitle = computed((): string => {
  if (scene.value == 'grouped') return '渠道与工具'
  if (scene.value == 'payload') return '订单操作'
  if (scene.value == 'cancel') return '取消与遮罩'
  return '分享到'
})
function record(event: string): void {
  sequence += 1
  const line = sequence.toString() + ' [' + scene.value + '] ' + event
  logs.value = logs.value.concat([line]).slice(-60)
  console.log('[share-sheet-demo] ' + line)
}
function openScene(value: string): void {
  if (closeTimer != null) { clearTimeout(closeTimer); closeTimer = null }
  scene.value = value
  record('external:open')
  if (value == 'external') externalShow.value = true
  else modelShow.value = true
}
function openTimed(): void {
  openScene('external')
  closeTimer = setTimeout(() => {
    closeTimer = null
    if (!externalShow.value) return
    record('external:show=false')
    externalShow.value = false
  }, 2000)
}
function updateShow(value: boolean): void {
  record('update:show=' + value)
  if (scene.value == 'external') externalShow.value = value
}
function updateModel(value: boolean): void {
  record('update:modelValue=' + value)
  if (scene.value != 'external') modelShow.value = value
}
function select(option: UTSJSONObject, index: number): void {
  status.value = '选择了 ' + option['name'] + '；index=' + index.toString()
  record('select(option,index): ' + JSON.stringify(option) + ', ' + index.toString())
  if (option['payload'] != null) payloadResult.value = JSON.stringify(option['payload']) ?? ''
  if (option['key'] != 'copy') {
    status.value += '；仅选择，未执行分享'
    return
  }
  copyResult.value = '复制中'
  const requestScene = scene.value
  uni.setClipboardData({
    data: option['url'] as string,
    showToast: false,
    success: () => {
      copyResult.value = '复制成功：' + option['url']
      record('clipboard:success [' + requestScene + ']')
    },
    fail: (error) => {
      copyResult.value = '复制失败：' + error.errMsg
      record('clipboard:fail [' + requestScene + '] ' + error.errMsg)
    },
    complete: () => { record('clipboard:complete [' + requestScene + ']') }
  })
}
onBeforeUnmount(() => { if (closeTimer != null) clearTimeout(closeTimer) })
</script>

<style>
.share-demo-scroll { display: flex; flex-direction: column; flex: 1; width: 100%; height: 100%; }
.share-demo-page { display: flex; flex-direction: column; width: 100%; padding: 32rpx 32rpx 64rpx; background-color: var(--xtf-color-page, #f8fafc); }
.share-demo-title { color: var(--xtf-color-text, #0f172a); font-size: 42rpx; font-weight: 700; }
.share-demo-section { display: flex; flex-direction: column; padding-top: 28rpx; padding-bottom: 24rpx; border-bottom-width: 1rpx; border-bottom-style: solid; border-bottom-color: var(--xtf-color-border, #e2e8f0); }
.share-demo-heading { margin-bottom: 20rpx; color: var(--xtf-color-text, #0f172a); font-size: 28rpx; font-weight: 600; }
.share-demo-row { display: flex; flex-direction: row; align-items: center; justify-content: space-between; margin-bottom: 20rpx; }
.share-demo-label { flex: 1; color: var(--xtf-color-text-secondary, #475569); font-size: 24rpx; }
.share-demo-gap { display: flex; flex-direction: column; margin-top: 16rpx; }
.share-demo-state { margin-top: 20rpx; color: var(--xtf-color-text-secondary, #475569); font-size: 24rpx; word-break: break-all; }
.share-demo-log { margin-top: 20rpx; color: var(--xtf-color-text-secondary, #475569); font-size: 22rpx; white-space: pre-wrap; word-break: break-all; }
</style>
