<template>
  <el-dialog
    :model-value="modelValue"
    title="选择链接"
    width="680px"
    destroy-on-close
    @update:model-value="$emit('update:modelValue', $event)"
  >
    <el-tabs v-model="tab">
      <el-tab-pane label="本站页面" name="pages">
        <p class="tab-tip">当前站点下已创建的网页（含首页 /）</p>
        <el-table
          v-loading="loadingPages"
          :data="pageRows"
          highlight-current-row
          max-height="320"
          @row-click="(row) => confirm(row.path)"
        >
          <el-table-column prop="title" label="标题" min-width="130" />
          <el-table-column prop="path" label="前台路径" min-width="140" />
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button type="primary" link @click.stop="confirm(row.path)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-if="!loadingPages && !pageRows.length" description="暂无页面，请先在网页管理中创建" />
      </el-tab-pane>

      <el-tab-pane v-if="showOtherSites" label="其他站点首页" name="sites">
        <p class="tab-tip">同账号下其他站点的首页链接（需在站点管理中填写「域名」）</p>
        <el-table
          v-loading="loadingSites"
          :data="otherSiteRows"
          max-height="320"
        >
          <el-table-column prop="name" label="站点名称" min-width="120" />
          <el-table-column prop="domain" label="已配置域名" min-width="180" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.domain">{{ row.domain }}</span>
              <el-text v-else type="warning" size="small">未填写</el-text>
            </template>
          </el-table-column>
          <el-table-column prop="previewUrl" label="将填入的链接" min-width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button
                type="primary"
                link
                :disabled="!row.homeUrl"
                @click="confirmOtherSite(row)"
              >选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-if="!loadingSites && !otherSiteRows.length" description="没有其他站点" />
      </el-tab-pane>

      <el-tab-pane v-if="showDownloadableFiles" label="可下载文件" name="files">
        <el-table
          v-loading="loadingFiles"
          :data="files"
          max-height="320"
          @row-click="(row) => confirm(fileUrl(row))"
        >
          <el-table-column prop="name" label="文件名" min-width="160" />
          <el-table-column prop="file_path" label="存储路径" min-width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button type="primary" link @click.stop="confirm(fileUrl(row))">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-if="!loadingFiles && !files.length" description="无标记为可下载的文件，请到文件管理上传并勾选允许下载" />
      </el-tab-pane>

      <el-tab-pane label="自定义地址" name="custom">
        <el-input v-model="customUrl" placeholder="https:// 或 /path" clearable />
        <div style="margin-top: 16px">
          <el-button type="primary" @click="confirmCustom">使用此地址</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getPages, getDownloadableAssets, getSites } from '../api/admin'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  siteId: { type: String, default: '' },
  showDownloadableFiles: { type: Boolean, default: true },
  showOtherSites: { type: Boolean, default: true }
})
const emit = defineEmits(['update:modelValue', 'select'])

const tab = ref('pages')
const pageRows = ref([])
const otherSiteRows = ref([])
const files = ref([])
const loadingPages = ref(false)
const loadingSites = ref(false)
const loadingFiles = ref(false)
const customUrl = ref('')

function effectivePath(p) {
  if (p.route_path) {
    const r = String(p.route_path).trim()
    return r.startsWith('/') ? r : '/' + r
  }
  if (!p.slug || p.slug === 'index') return '/'
  return '/' + p.slug
}

/** 站点首页完整 URL：依赖站点 domain；无域名则无法生成外链 */
function siteHomepageUrl(site) {
  let d = (site.domain || '').trim()
  if (!d) return ''
  if (!/^https?:\/\//i.test(d)) d = 'https://' + d
  return d.replace(/\/$/, '') + '/'
}

async function loadPages() {
  if (!props.siteId) return
  loadingPages.value = true
  try {
    const res = await getPages({ site_id: props.siteId })
    const list = res.list || []
    pageRows.value = list.map((p) => ({
      title: (p.type === 'homepage' || p.slug === 'index' ? '【首页】' : '') + (p.title || p.slug),
      path: effectivePath(p),
      slug: p.slug
    }))
  } catch {
    pageRows.value = []
  } finally {
    loadingPages.value = false
  }
}

async function loadOtherSites() {
  loadingSites.value = true
  try {
    const res = await getSites()
    const list = (res.list || []).filter((s) => s.id !== props.siteId)
    otherSiteRows.value = list.map((s) => {
      const homeUrl = siteHomepageUrl(s)
      return {
        id: s.id,
        name: s.name || s.id,
        domain: (s.domain || '').trim(),
        homeUrl,
        previewUrl: homeUrl || '（未配置域名）'
      }
    })
  } catch {
    otherSiteRows.value = []
  } finally {
    loadingSites.value = false
  }
}

function confirmOtherSite(row) {
  if (!row.homeUrl) {
    ElMessage.warning('请先在「站点管理」中为该站点填写访问域名')
    return
  }
  confirm(row.homeUrl)
}

async function loadFiles() {
  if (!props.siteId) return
  loadingFiles.value = true
  try {
    const res = await getDownloadableAssets(props.siteId)
    files.value = res.list || []
  } catch {
    files.value = []
  } finally {
    loadingFiles.value = false
  }
}

function fileUrl(row) {
  return `/api/web/sites/${props.siteId}/assets/${row.id}/download`
}

function confirm(url) {
  if (!url) return
  emit('select', url)
  emit('update:modelValue', false)
}

function confirmCustom() {
  const u = (customUrl.value || '').trim()
  if (!u) {
    ElMessage.warning('请输入地址')
    return
  }
  confirm(u)
}

watch(
  () => props.modelValue,
  (v) => {
    if (v) {
      customUrl.value = ''
      tab.value = 'pages'
      loadPages()
      if (props.showOtherSites) loadOtherSites()
      if (props.showDownloadableFiles) loadFiles()
    }
  }
)
</script>

<style scoped>
.tab-tip {
  font-size: 12px;
  color: #909399;
  margin: 0 0 8px;
}
</style>
