<template>
  <GuidePageFrame
    active-tab="explain"
    variant="static"
    :show-top-tabs="false"
    @tab-change="handleTopTabChange"
    @back="handleBack"
  >
    <view class="explain-business-unit-page">
      <ExplainHallSelect
        :business-units="explainBusinessUnitItems"
        stage="unit"
        :selected-hall-name="selectedExplainHallName"
        :loading="explainLoading"
        :error="explainError"
        @business-unit-click="handleExplainBusinessUnitClick"
        @back="handleBack"
      />
    </view>
  </GuidePageFrame>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import GuidePageFrame from '@/components/navigation/GuidePageFrame.vue'
import ExplainHallSelect, {
  type ExplainBusinessUnitSelectItem
} from '@/components/explain/ExplainHallSelect.vue'
import {
  explainUseCase
} from '@/usecases/explainUseCase'
import type {
  ExplainBusinessUnit
} from '@/domain/museum'
import {
  navigateToGuideTopTab,
  type GuideTopTab
} from '@/utils/guideTopTabs'

const selectedExplainHallId = ref('')
const selectedExplainHallName = ref('')
const explainBusinessUnits = ref<ExplainBusinessUnit[]>([])
const explainLoading = ref(false)
const explainError = ref('')

const explainBusinessUnitItems = computed<ExplainBusinessUnitSelectItem[]>(() => (
  explainBusinessUnits.value.map((unit) => ({
    id: unit.id,
    name: unit.name,
    hallId: unit.hallId,
    previewImageUrl: unit.previewImageUrl,
    guideStopCount: unit.guideStopCount
  }))
))

const syncPageTitle = (title: string) => {
  uni.setNavigationBarTitle({ title })
  if (typeof document !== 'undefined') document.title = title
}

onLoad(async (options: any = {}) => {
  const hallId = Array.isArray(options.hallId) ? options.hallId[0] : options.hallId
  const hallName = Array.isArray(options.hallName) ? options.hallName[0] : options.hallName

  selectedExplainHallId.value = hallId || ''
  selectedExplainHallName.value = hallName || '业务单元'
  syncPageTitle(selectedExplainHallName.value)

  if (!selectedExplainHallId.value) {
    explainError.value = '缺少展厅参数，请返回讲解列表后重试'
    return
  }

  explainLoading.value = true
  try {
    explainBusinessUnits.value = await explainUseCase.loadTemporaryBusinessUnitsByHall(selectedExplainHallId.value)
  } catch (error) {
    explainError.value = '展厅讲解点加载失败，请稍后重试'
  } finally {
    explainLoading.value = false
  }
})

const handleExplainBusinessUnitClick = (unitId: string) => {
  const unit = explainBusinessUnits.value.find((item) => item.id === unitId)
  const params = new URLSearchParams({
    hallId: selectedExplainHallId.value,
    hallName: selectedExplainHallName.value,
    unitId,
    unitName: unit?.name || '讲解点'
  })

  uni.navigateTo({
    url: `/pages/explain/guide-stop-list?${params.toString()}`
  })
}

const goBackToExplainHallList = () => {
  uni.redirectTo({
    url: '/pages/explain/list',
    fail: () => {
      uni.reLaunch({ url: '/pages/explain/list' })
    }
  })
}

const handleBack = () => {
  const pages = getCurrentPages()
  const previousPage = pages.length >= 2 ? pages[pages.length - 2] : null

  if (
    previousPage?.route === 'pages/explain/list'
    || previousPage?.route === 'pages/index/index'
  ) {
    uni.navigateBack({
      delta: 1,
      fail: goBackToExplainHallList
    })
    return
  }

  goBackToExplainHallList()
}

const handleTopTabChange = (tab: GuideTopTab) => {
  navigateToGuideTopTab(tab)
}
</script>

<style scoped lang="scss">
.explain-business-unit-page {
  position: absolute;
  inset: 0;
  background: #edf0ea;
}
</style>
