<script setup lang="ts">
import { ref, watch } from 'vue'
import { getShopCascade } from '@/api/shop'
import type { ShopCascadeItem } from '@/api/shop'

interface SelectedShop {
  id: number
  shop_name: string
}

interface Props {
  show: boolean
  selectedShop?: SelectedShop | null
  title?: string
}

interface Emits {
  (e: 'update:show', value: boolean): void
  (e: 'confirm', shop: SelectedShop | null): void
  (e: 'cancel'): void
}

const props = withDefaults(defineProps<Props>(), {
  title: '选择店铺',
  selectedShop: null,
})

const emit = defineEmits<Emits>()

const loading = ref(false)
const shopOptions = ref<ShopCascadeItem[]>([])
const breadcrumbs = ref<ShopCascadeItem[]>([])
const selectedShop = ref<SelectedShop | null>(null)

async function loadShopOptions(parentId?: number) {
  loading.value = true
  try {
    const response = await getShopCascade(parentId !== undefined ? { parent_id: parentId } : undefined)
    shopOptions.value = response || []
  }
  catch (error) {
    console.error('加载店铺级联数据失败:', error)
    shopOptions.value = []
  }
  finally {
    loading.value = false
  }
}

async function openPicker() {
  selectedShop.value = props.selectedShop ? { ...props.selectedShop } : null
  breadcrumbs.value = []
  await loadShopOptions()
}

function close() {
  emit('update:show', false)
}

function handleCancel() {
  emit('cancel')
  close()
}

function selectShop(option: ShopCascadeItem) {
  selectedShop.value = {
    id: option.id,
    shop_name: option.shop_name,
  }
}

async function enterChildren(option: ShopCascadeItem) {
  const nextPath = [...breadcrumbs.value, option]
  breadcrumbs.value = nextPath
  await loadShopOptions(option.id)
}

async function goToBreadcrumb(index: number) {
  if (index < 0) {
    breadcrumbs.value = []
    await loadShopOptions()
    return
  }

  const nextPath = breadcrumbs.value.slice(0, index + 1)
  breadcrumbs.value = nextPath
  await loadShopOptions(nextPath[index]?.id)
}

function handleConfirm() {
  emit('confirm', selectedShop.value)
  close()
}

watch(
  () => props.show,
  async (show) => {
    if (show) {
      await openPicker()
    }
  },
)
</script>

<template>
  <view
    v-if="show"
    class="shop-picker-overlay"
    @click="handleCancel"
  >
    <view
      class="shop-picker-content"
      @click.stop
    >
      <view class="shop-picker-header">
        <view class="shop-picker-action" @click="handleCancel">
          <text class="text-sm text-[#666]">取消</text>
        </view>
        <view class="shop-picker-title">
          <text class="text-base font-600 text-[#1e293b]">{{ title }}</text>
        </view>
        <view class="shop-picker-action text-right" @click="handleConfirm">
          <text class="text-sm text-brand font-600">确定</text>
        </view>
      </view>

      <scroll-view
        class="shop-picker-breadcrumb"
        scroll-x
      >
        <view class="shop-picker-breadcrumb-list">
          <text
            class="shop-picker-breadcrumb-item"
            :class="{ 'shop-picker-breadcrumb-item-active': breadcrumbs.length === 0 }"
            @click="goToBreadcrumb(-1)"
          >
            顶级店铺
          </text>
          <template
            v-for="(item, index) in breadcrumbs"
            :key="item.id"
          >
            <text class="shop-picker-breadcrumb-separator">/</text>
            <text
              class="shop-picker-breadcrumb-item"
              :class="{ 'shop-picker-breadcrumb-item-active': index === breadcrumbs.length - 1 }"
              @click="goToBreadcrumb(index)"
            >
              {{ item.shop_name }}
            </text>
          </template>
        </view>
      </scroll-view>

      <view v-if="selectedShop" class="shop-picker-selection">
        <text class="text-12px text-[#666]">
          已选店铺
        </text>
        <text class="text-13px font-600 text-[#212121]">
          {{ selectedShop.shop_name }}
        </text>
      </view>

      <scroll-view
        class="shop-picker-list"
        scroll-y
      >
        <view v-if="loading" class="shop-picker-empty">
          <i class="i-mdi-loading animate-spin text-18px text-brand" />
          <text class="text-13px text-[#64748b]">加载中...</text>
        </view>

        <view v-else-if="shopOptions.length === 0" class="shop-picker-empty">
          <text class="text-13px text-[#94a3b8]">暂无下级店铺</text>
        </view>

        <template v-else>
          <view
            v-for="option in shopOptions"
            :key="option.id"
            class="shop-picker-item"
            :class="{ 'shop-picker-item-active': selectedShop?.id === option.id }"
          >
            <view
              class="shop-picker-item-main"
              @click="selectShop(option)"
            >
              <text class="shop-picker-item-text">{{ option.shop_name }}</text>
              <i
                v-if="selectedShop?.id === option.id"
                class="i-mdi-check text-16px text-brand"
              />
            </view>
            <view
              v-if="option.has_children"
              class="shop-picker-next"
              @click="enterChildren(option)"
            >
              <text class="text-12px text-[#999]">下级</text>
              <i class="i-mdi-chevron-right text-14px text-[#999]" />
            </view>
          </view>
        </template>
      </scroll-view>
    </view>
  </view>
</template>

<style scoped>
.shop-picker-overlay {
  position: fixed;
  inset: 0;
  z-index: 9999;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  background: rgba(0, 0, 0, 0.5);
}

.shop-picker-content {
  display: flex;
  flex-direction: column;
  max-height: 72vh;
  background: #fff;
  border-radius: 16px 16px 0 0;
}

.shop-picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f1f5f9;
}

.shop-picker-action {
  min-width: 60px;
}

.shop-picker-title {
  flex: 1;
  text-align: center;
}

.shop-picker-breadcrumb {
  white-space: nowrap;
  border-bottom: 1px solid #f8fafc;
}

.shop-picker-breadcrumb-list {
  display: inline-flex;
  align-items: center;
  min-width: 100%;
  padding: 12px 16px;
}

.shop-picker-breadcrumb-item {
  font-size: 12px;
  color: #64748b;
}

.shop-picker-breadcrumb-item-active {
  color: var(--brand-primary, #1677ff);
  font-weight: 600;
}

.shop-picker-breadcrumb-separator {
  margin: 0 8px;
  font-size: 12px;
  color: #cbd5e1;
}

.shop-picker-selection {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 12px 16px;
  background: #f8fafc;
}

.shop-picker-list {
  flex: 1;
  max-height: calc(72vh - 114px);
}

.shop-picker-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 24px 16px;
}

.shop-picker-item {
  display: flex;
  align-items: stretch;
  border-bottom: 1px solid #f8fafc;
}

.shop-picker-item-active {
  background: #fef3f2;
}

.shop-picker-item-main {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 14px 16px;
}

.shop-picker-item-text {
  flex: 1;
  font-size: 15px;
  color: #1e293b;
}

.shop-picker-item-active .shop-picker-item-text {
  color: var(--brand-primary, #1677ff);
  font-weight: 600;
}

.shop-picker-next {
  display: flex;
  align-items: center;
  gap: 2px;
  padding: 0 16px 0 8px;
}

.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>
