<template>
  <div class="workspace">
    <div class="workspace-header">
      <n-button quaternary circle @click="refresh" style="margin-left: auto;">
        <template #icon>
          <Icon icon="tabler:refresh" />
        </template>
      </n-button>
    </div>

    <div v-if="loading" class="loading"></div>
    <div v-else class="content">
      <div class="grid-12">
        <template v-for="item in items" :key="item.key">
          <div v-if="item.type==='card'" class="card" :class="item.classes">
            <div class="card-header">
              <div class="card-title">{{ t(item.title) }}</div>
            </div>
            <div class="card-body">
              <div class="card-links">
                <a v-for="link in item.links" :key="link.label" class="link" @click.prevent="openLink(link)">
                  <span class="link-text">{{ t(link.label) }}</span>
                  <Icon class="link-icon" icon="tabler:arrow-up-right" />
                </a>
              </div>
            </div>
          </div>
          <div v-else-if="item.type==='shortcut'" class="shortcut" :class="item.classes">
            <div class="shortcut-content" @click="openShortcut(item.shortcutData)">
              <span class="shortcut-text">{{ t(item.title) }}</span>
              <Icon class="shortcut-icon" icon="tabler:arrow-up-right" />
            </div>
          </div>
          <div v-else-if="item.type==='header'" class="header" :class="item.classes">
            <div class="header-content" v-html="item.text"></div>
          </div>
          <div v-else-if="item.type==='spacer'" class="spacer span-12" />
        </template>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { NButton, useMessage } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { t } from '@/shared/i18n'
import { getWorkspace } from '@/shared/api/common'
import { pageTypeToSlug } from '@/shared/utils/slug'

const route = useRoute()
const router = useRouter()
const message = useMessage()

const name = computed(() => String(route.params.name || 'Build'))
const decodedName = computed(() => decodeURIComponent(name.value))

const loading = ref(true)
const pageTitle = ref('Workspace')
const isPublic = ref(true)
const items = ref<any[]>([])

async function load() {
  loading.value = true
  const { success, data, message: err } = await getWorkspace(decodedName.value)
  if (!success) {
    message.error(err || 'Failed to load workspace')
    loading.value = false
    return
  }

  pageTitle.value = data?.title || decodedName.value
  isPublic.value = Boolean(data?.public ?? true)

  // 解析 content（布局）与 links（数据项）。
  const layout = parseJSON(data?.content) as Array<any>
  const links = Array.isArray(data?.links) ? data.links : []

  // 将 links 按 Card Break 分组：每个 Card Break(label) 之后的连续 Link 归入该分组。
  const grouped: Record<string, any[]> = {}
  let current: string = ''
  for (const ln of links) {
    if (ln.type === 'Card Break') {
      current = ln.label || 'Untitled'
      if (!grouped[current]) grouped[current] = []
    } else if (ln.type === 'Link' && current) {
      grouped[current].push({ label: ln.label, link_type: ln.link_type, link_to: ln.link_to })
    }
  }

  // 将每个 card 作为一个卡片，col 为 12 栅格宽度；默认 6 ⇒ 两列布局
  const resultItems: any[] = []
  for (const block of layout || []) {
    if (block.type === 'card') {
      const title = block.data?.card_name || 'Section'
      const col = Number(block.data?.col || 6) // 按 12 栅格，6=两列，3=四列
      resultItems.push({ key: `card-${title}-${col}-${resultItems.length}` , type:'card', title, col, links: grouped[title] || [], classes: mapColToClasses(col) })
    } else if (block.type === 'shortcut') {
      // 处理快捷方式
      const title = block.data?.shortcut_name || 'Shortcut'
      const col = Number(block.data?.col || 3) // 默认3列宽度
      // 从shortcuts数组中查找对应的数据
      const shortcutData = data?.shortcuts?.find((s: any) => s.label === title)
      resultItems.push({ 
        key: `shortcut-${title}-${col}-${resultItems.length}`, 
        type: 'shortcut', 
        title, 
        col, 
        shortcutData,
        classes: mapColToClasses(col) 
      })
    } else if (block.type === 'header') {
      // 处理标题
      const text = block.data?.text || 'Header'
      const col = Number(block.data?.col || 12) // 标题通常占满一行
      resultItems.push({ 
        key: `header-${text}-${col}-${resultItems.length}`, 
        type: 'header', 
        text, 
        col,
        classes: ['span-12'] 
      })
    } else if (block.type === 'spacer') {
      // 插入占满一行的分隔，仅用于换行
      resultItems.push({ key: `spacer-${resultItems.length}`, type: 'spacer' })
    }
  }
  items.value = resultItems

  loading.value = false
}

function refresh() { load() }

function openLink(link: { link_type: string; link_to: string }) {
  // 简单导航：PageType 走 /app/:entity 列表；Page 则走 /:page；Report 保持 /app/:entity
  if (!link) return
  const to = (link.link_type || '').toLowerCase()
  if (to === 'pagetype' || to === 'report') {
    const slug = pageTypeToSlug(link.link_to)
    router.push(`/app/${slug}`)
  } else if (to === 'page') {
    router.push(`/${link.link_to}`)
  }
}

function openShortcut(shortcutData: any) {
  if (!shortcutData) return
  
  if (shortcutData.url) {
    // 如果有URL，直接打开外部链接
    window.open(shortcutData.url, '_blank')
  } else if (shortcutData.link_to) {
    const slug = pageTypeToSlug(shortcutData.link_to)
    router.push(`/app/${slug}`)
  }
}

watch(() => route.params.name, load)
onMounted(load)
</script>

<style scoped>
.workspace { padding: 16px; }
.workspace-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }
.title-wrap { display: flex; align-items: center; gap: 8px; }
.title { margin: 0; font-size: 20px; }
.content { min-height: calc(100vh - 160px); }
.grid-12 { display: grid; grid-template-columns: repeat(12, minmax(0, 1fr)); gap: 16px; }
/* 基线：移动端单列 */
.span-12 { grid-column: span 12; }
/* Bootstrap 对齐的断点：sm=576, md=768, lg=992 */
@media (min-width: 576px) { .sm-span-6 { grid-column: span 6; } }
@media (min-width: 768px) { .md-span-4 { grid-column: span 4; } }
@media (min-width: 992px) { 
  .lg-span-3 { grid-column: span 3; }
  .lg-span-2 { grid-column: span 2; }
}
.card { background: #fff; border: 1px solid #eef2f7; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(15,23,42,0.04); }
.card-header { padding: 14px 16px; border-bottom: 1px solid #f1f5f9; }
.card-title { font-weight: 600; color: #0f172a; }
.card-body { padding: 12px 16px; color: #334155; }
.card-links { display: grid; gap: 8px; }
.link { display: inline-flex; align-items: center; gap: 10px; color: #0f172a; text-decoration: none; cursor: pointer; }
.link:hover { color: #18a058; }
.link-icon { color: #94a3b8; font-size: 13px; transition: all .15s ease; margin-left: 2px; }
.link:hover .link-icon { color: #18a058; transform: translate(1px, -1px); }

.shortcut { background: #fff; border: 1px solid #eef2f7; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(15,23,42,0.04); }
.shortcut-content { padding: 16px; display: inline-flex; align-items: center; gap: 10px; cursor: pointer; transition: all .15s ease; }
.shortcut-content:hover { background: #f8fafc; }
.shortcut-text { font-weight: 500; color: #0f172a; }
.shortcut-icon { color: #94a3b8; font-size: 13px; transition: all .15s ease; margin-left: 2px; }
.shortcut-content:hover .shortcut-icon { color: #18a058; transform: translate(1px, -1px); }

.header { margin: 16px 0 8px 0; }
.header-content { font-size: 18px; font-weight: 600; color: #0f172a; }

.spacer { height: 8px; }
.loading { color: #64748b; }
@media (max-width: 1024px) { .grid-12 { grid-template-columns: 1fr; } }
</style>

<script lang="ts">
// 本地工具：安全解析 JSON
export function parseJSON(input: any): any[] {
  try {
    if (typeof input === 'string') return JSON.parse(input)
    if (Array.isArray(input)) return input
    return []
  } catch {
    return []
  }
}

// 将 jingrow 的 set_col_class 规则映射到 CSS Grid 的响应式 span 类
export function mapColToClasses(width: number): string[] {
  const classes = ['span-12']
  if (width <= 12 && width >= 7) {
    // 大卡：保持整行基线（移动端1列），可按需扩展
  } else if (width === 6 || width === 5) {
    classes.push('sm-span-6')
  } else if (width === 4) {
    classes.push('sm-span-6', 'md-span-4')
  } else if (width === 3 || width === 2) {
    classes.push('sm-span-6', 'md-span-4', `lg-span-${width}`)
  }
  return classes
}
</script>


