<template>
    <view class="category-page">
        <!-- 椤堕儴鎼滅储鏍?-->
        <view class="search-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
            <view class="search-container">
                <view class="search-box" @click="navigateToSearch" :style="{ height: '30px' }">
                    <!-- 妯℃嫙杈撳叆妗?-->
                    <text class="search-placeholder">璇疯緭鍏ヨ嵂鍝佸悕绉般€佺棁鐘舵垨鍝佺墝</text>
                    
                    <!-- 鎵爜鍥炬爣 -->
                    <view class="nav-icon-btn" @click.stop="onScan">
                        <text class="nav-icon">馃敵</text>
                    </view>

                    <!-- 鐩告満鍥炬爣 -->
                    <view class="nav-camera-btn" @click.stop="onCamera">
                        <text class="nav-camera-icon">馃摲</text>
                    </view>
                    
                    <!-- 鎼滅储鎸夐挳 -->
                    <view class="nav-inner-search-btn" :style="{ height: '22px' }">
                        <text class="nav-inner-search-text">鎼滅储</text>
                    </view>
                </view>
            </view>
        </view>
        
        <!-- 瀵艰埅鏍忓崰浣?- 闇€瑕佸寘鍚玸tatusBarHeight + 鎼滅储妗嗛珮搴?4px -->
        <view class="navbar-placeholder" :style="{ height: (statusBarHeight + 44) + 'px' }"></view>
        
        <!-- 鍒嗙被鍐呭鍖?-->
        <view class="category-content">
            <!-- 宸︿晶涓€绾у垎绫?-->
            <scroll-view :scroll-y="true" class="primary-category">
                <view 
                    v-for="item in primaryCategories" 
                    :key="item.id"
                    :class="['primary-item', { active: activePrimary === item.id }]"
                    @click="selectPrimaryCategory(item.id)"
                    :style="{ backgroundColor: activePrimary === item.id ? item.color : 'transparent' }"
                >
                    <text class="primary-icon">{{ item.icon }}</text>
                    <text class="primary-name">{{ item.name }}</text>
                </view>
            </scroll-view>
            
            <!-- 鍙充晶鍟嗗搧鍒楄〃 -->
            <scroll-view 
                :scroll-y="true" 
                class="product-content"
                @scrolltolower="loadMore"
                :lower-threshold="50"
            >
                <!-- 鍒嗙被鏍囬 -->
                <view class="category-header">
                    <text class="category-title">{{ currentCategoryName }}</text>
                    <text class="category-desc">{{ currentCategoryDesc }}</text>
                </view>
                
                <!-- 鍟嗗搧缃戞牸 -->
                <view v-if="productList.length > 0" class="product-grid">
                    <view 
                        v-for="product in productList" 
                        :key="product.id"
                        class="product-card"
                        @click="navigateToProduct(product)"
                    >
                        <image 
                            class="product-image" 
                            :src="product.main_image_url" 
                            mode="aspectFill"
                        />
                        <text class="product-name" :lines="2">{{ product.name }}</text>
                        <view class="product-bottom">
                            <text class="product-price">楼{{ product.base_price ?? product.price ?? 0 }}</text>
                            <view class="product-add-btn" @click.stop="addToCart(product)">
                                <text class="add-icon">+</text>
                            </view>
                        </view>
                    </view>
                </view>
                
                <!-- 绌虹姸鎬?-->
                <view v-else class="empty-state">
                    <text class="empty-icon">馃拪</text>
                    <text class="empty-text">鏆傛棤鐩稿叧鑽搧</text>
                    <text class="empty-desc">璇ュ垎绫讳笅鏆傛棤鍟嗗搧锛屾暚璇锋湡寰?/text>
                </view>
                
                <!-- 鍔犺浇鏇村鎻愮ず -->
                <view v-if="hasMore" class="load-more">
                    <text class="load-text">涓婃媺鍔犺浇鏇村</text>
                </view>
            </scroll-view>
        </view>
    </view>
</template>

<script setup lang="uts">
import { ref, onMounted } from 'vue'
import supabaseService from '@/utils/supabaseService.uts'
import type { Product } from '@/utils/supabaseService.uts'

type LocalCategory = {
	id: string
	name: string
	icon: string
	description: string
	color: string
}

// 鍝嶅簲寮忔暟鎹?
const statusBarHeight = ref(0)
const headerHeight = ref(44) // 榛樿澶撮儴楂樺害
const primaryCategories = ref<LocalCategory[]>([])
const productList = ref<Product[]>([])
const activePrimary = ref<string>('')
const cartCount = ref(3)
const hasMore = ref(true)
const hasLoadedFromParams = ref(false) // 鏍囪鏄惁宸查€氳繃鍙傛暟鍔犺浇
const currentPage = ref(1)
const loading = ref(false)

// 鑾峰彇褰撳墠鍒嗙被淇℃伅
const currentCategoryName = ref('')
const currentCategoryDesc = ref('')

// 椤甸潰鍙傛暟
const pageParams = ref<any>({})

// 鍔犺浇鍟嗗搧鏁版嵁
async function loadProducts(): Promise<void> {
  if (loading.value) return
  if (activePrimary.value == '') {
    console.warn('activePrimary涓虹┖锛屾棤娉曞姞杞藉晢鍝?)
    return
  }

  loading.value = true
  try {
      console.log('寮€濮嬪姞杞藉晢鍝侊紝鍒嗙被ID:', activePrimary.value, '椤电爜:', currentPage.value)
      const response = await supabaseService.getProductsByCategory(activePrimary.value, currentPage.value)
      console.log('鍟嗗搧鍔犺浇缁撴灉:', {
        dataCount: response.data.length,
        total: response.total,
        hasmore: response.hasmore,
        page: currentPage.value
      })
      
      if (currentPage.value === 1) {
          productList.value = response.data
      } else {
          productList.value.push(...response.data)
      }
      
      hasMore.value = response.hasmore
      
      // 鏇存柊褰撳墠鍒嗙被淇℃伅
      const category = primaryCategories.value.find((cat: LocalCategory): boolean => cat.id === activePrimary.value)
      if (category != null) {
        currentCategoryName.value = category.name
        currentCategoryDesc.value = category.description
      }
      
      console.log('鍟嗗搧鍒楄〃鍔犺浇瀹屾垚锛屽綋鍓嶆€绘暟閲?', productList.value.length)
  } catch (error) {
    console.error('鍔犺浇鍟嗗搧鏁版嵁澶辫触:', error)
    if (currentPage.value === 1) {
        productList.value = []
    }
  } finally {
      loading.value = false
  }
}

async function loadCategories(): Promise<void> {
  try {
    const categoriesData = await supabaseService.getCategories()
    console.log('鍔犺浇鍒嗙被鏁版嵁鎴愬姛锛屾暟閲?', categoriesData.length)
    
    // 鏄犲皠鏁版嵁骞舵坊鍔犻粯璁ら鑹诧紝闃叉閫変腑鏃惰儗鏅€忔槑瀵艰嚧鏂囧瓧鐪嬩笉娓?
    // 杩囨护鎺夊尰鑽仴搴风浉鍏冲垎绫?
    const categories: LocalCategory[] = []
    const rawList = categoriesData as any[]
    for (let i = 0; i < rawList.length; i++) {
      const raw = rawList[i]
      const catObj = (raw instanceof UTSJSONObject) ? (raw as UTSJSONObject) : (JSON.parse(JSON.stringify(raw)) as UTSJSONObject)
      const name = catObj.getString('name') ?? ''
      if (name.includes('鍖昏嵂') || name.includes('鍋ュ悍')) {
        continue
      }
      const id = catObj.getString('id') ?? ''
      const description = catObj.getString('description') ?? ''
      const icon = catObj.getString('icon') ?? catObj.getString('icon_url') ?? '馃摝'
      const color = catObj.getString('color') ?? '#4CAF50'
      categories.push({
        id,
        name,
        icon,
        description,
        color
      })
    }

    if (categories.length > 0) {
      primaryCategories.value = categories
      // 濡傛灉娌℃湁閫氳繃鍙傛暟璁剧疆鍒嗙被锛屽垯璁剧疆榛樿閫変腑涓€涓垎绫?
      if (activePrimary.value == '') {
        // 浼樺厛鏌ユ壘"鍘ㄥ叿"鐩稿叧鐨勫垎绫讳綔涓洪粯璁?
        const defaultCategory = categories.find((c: LocalCategory): boolean => c.name.includes('鍘ㄥ叿')) ?? categories[0]
        
        activePrimary.value = defaultCategory.id
        console.log('璁剧疆榛樿鍒嗙被涓?', defaultCategory.name, 'ID:', defaultCategory.id)
        currentCategoryName.value = defaultCategory.name
        currentCategoryDesc.value = defaultCategory.description
      } else {
         // 濡傛灉宸茬粡閫変腑浜嗗垎绫伙紙鍙兘鏉ヨ嚜Storage锛夛紝鏇存柊鏄剧ず淇℃伅
         const current = categories.find((c: LocalCategory): boolean => c.id == activePrimary.value)
         if (current != null) {
             currentCategoryName.value = current.name
             currentCategoryDesc.value = current.description
             // 濡傛灉姝ゆ椂娌℃湁鍟嗗搧鍒楄〃锛堜笖娌℃湁姝ｅ湪鍔犺浇锛夛紝鍙兘闇€瑕佸姞杞?
             if (productList.value.length === 0 && !loading.value) {
                 loadProducts()
             }
         }
      }
    } else {
      console.warn('浠嶴upabase鑾峰彇鐨勫垎绫绘暟鎹负绌?)
    }
  } catch (error) {
    console.error('鍔犺浇鍒嗙被鏁版嵁澶辫触:', error)
  }
}

// 鍔犺浇鏇村
function loadMore(): void {
    if (hasMore.value && !loading.value) {
        currentPage.value++
        loadProducts()
    }
}

// 閫夋嫨涓€绾у垎绫?
async function selectPrimaryCategory(categoryId: string): Promise<void> {
    console.log('=== selectPrimaryCategory鍑芥暟寮€濮嬫墽琛?===')
    console.log('浼犲叆鐨刢ategoryId:', categoryId)
    console.log('褰撳墠鏃堕棿:', Date.now())
    
    // 楠岃瘉categoryId鏄惁鏈夋晥
    if (categoryId == '') {
        console.error('categoryId涓虹┖锛屽皾璇曚娇鐢ㄧ涓€涓垎绫?)
        if (primaryCategories.value.length > 0) {
            categoryId = primaryCategories.value[0].id
        } else {
            console.error('娌℃湁鍙敤鐨勫垎绫?)
            return
        }
    }
    
    console.log('楠岃瘉鍚庣殑categoryId:', categoryId)
    console.log('褰撳墠activePrimary鐨勫€?', activePrimary.value)
    
    // 鏇存柊娲诲姩鍒嗙被
    activePrimary.value = categoryId
    console.log('鏇存柊鍚庣殑activePrimary:', activePrimary.value)
    
    // 鏇存柊褰撳墠鍒嗙被淇℃伅
    const category = primaryCategories.value.find((cat: LocalCategory): boolean => cat.id === categoryId)
    if (category != null) {
        currentCategoryName.value = category.name
        currentCategoryDesc.value = category.description
        console.log('鉁?鎵惧埌鍒嗙被:', category.name, '鎻忚堪:', category.description)
    } else {
        console.error('鉂?鏈壘鍒板垎绫籌D:', categoryId, '锛屼娇鐢ㄧ涓€涓垎绫?)
        // 濡傛灉鎵句笉鍒板搴旂殑鍒嗙被锛屼娇鐢ㄧ涓€涓垎绫?
        if (primaryCategories.value.length > 0) {
            const firstCategory = primaryCategories.value[0]
            currentCategoryName.value = firstCategory.name
            currentCategoryDesc.value = firstCategory.description
            activePrimary.value = firstCategory.id
            categoryId = firstCategory.id
            console.log('浣跨敤榛樿鍒嗙被:', firstCategory.name)
        }
    }
    
    console.log('鍑嗗鍔犺浇鍟嗗搧鏁版嵁...')
    
    // 閲嶇疆鍒嗛〉骞跺姞杞?
    currentPage.value = 1
    hasMore.value = true
    await loadProducts()
    
    console.log('鉁?鍔犺浇鍟嗗搧鏁版嵁鎴愬姛')
    console.log('鍒嗙被:', categoryId)
    console.log('鍟嗗搧鏁伴噺:', productList.value.length)
    console.log('鍟嗗搧鍒楄〃:', productList.value)
    
    // 楠岃瘉鏁版嵁鏄惁宸叉纭洿鏂?
    console.log('鏁版嵁鏇存柊楠岃瘉:')
    console.log('activePrimary:', activePrimary.value)
    console.log('currentCategoryName:', currentCategoryName.value)
    console.log('currentCategoryDesc:', currentCategoryDesc.value)
    console.log('productList闀垮害:', productList.value.length)
    
    console.log('=== selectPrimaryCategory鍑芥暟鎵ц瀹屾垚 ===')
}

// 鐢熷懡鍛ㄦ湡
onMounted(() => {
	loadCategories().then(() => {
		setTimeout(() => {
			if (!hasLoadedFromParams.value && activePrimary.value != '') {
				loadProducts()
			}
		}, 300)
	})
})

// 椤甸潰鍔犺浇鏃跺鐞嗗弬鏁?- 杩欐槸澶勭悊鍒嗙被鍒囨崲鐨勪富瑕佸叆鍙?
onLoad((options: any) => {
    // 鑾峰彇绯荤粺鐘舵€佹爮楂樺害
    const systemInfo = uni.getSystemInfoSync()
    statusBarHeight.value = systemInfo.statusBarHeight
    console.log('=== category椤甸潰onLoad琚皟鐢?===')
	console.log('椤甸潰鍔犺浇鏃堕棿:', Date.now())
	console.log('浼犲叆鐨刼ptions鍙傛暟:', options)
	console.log('褰撳墠娲诲姩鍒嗙被:', activePrimary.value)
	
	let categoryId = ''
	let categoryName = ''
	
	// 棣栧厛妫€鏌ヤ紶鍏ョ殑options鍙傛暟
	const optObj = (options instanceof UTSJSONObject) ? (options as UTSJSONObject) : (JSON.parse(JSON.stringify(options ?? {})) as UTSJSONObject)
	const optCategoryId = optObj.getString('categoryId') ?? ''
	if (optCategoryId !== '') {
		categoryId = optCategoryId
		categoryName = optObj.getString('name') ?? ''
		console.log('鉁?onLoad涓壘鍒板垎绫诲弬鏁?', categoryId, categoryName)
	}
	
	// 濡傛灉options涓病鏈夛紝灏濊瘯浠巊etCurrentPages()鑾峰彇
	if (categoryId == '') {
		const pages = getCurrentPages()
		if (pages.length > 0) {
			const currentPage = pages[pages.length - 1]
			const rawPageOptions = currentPage.options ?? {}
			console.log('浠巊etCurrentPages()鑾峰彇鍙傛暟:', rawPageOptions)
			const pageOptObj = (rawPageOptions instanceof UTSJSONObject) ? (rawPageOptions as UTSJSONObject) : (JSON.parse(JSON.stringify(rawPageOptions)) as UTSJSONObject)
			const pageCategoryId = pageOptObj.getString('categoryId') ?? ''
			if (pageCategoryId !== '') {
				categoryId = pageCategoryId
				categoryName = pageOptObj.getString('name') ?? ''
				console.log('鉁?浠巊etCurrentPages()鎵惧埌鍒嗙被鍙傛暟:', categoryId, categoryName)
			}
		}
	}
	
	// 濡傛灉鏈夋壘鍒板垎绫籌D锛屽垯閫変腑瀵瑰簲鐨勫垎绫?
	if (categoryId != '') {
		hasLoadedFromParams.value = true
		console.log('鉁?鍑嗗閫変腑鍒嗙被:', categoryId)
		console.log('鍒嗙被鍚嶇О:', categoryName ?? '鏈寚瀹?)
		
		// 妫€鏌ユ槸鍚﹂渶瑕佹洿鏂板垎绫?
		if (activePrimary.value !== categoryId) {
			console.log('褰撳墠鍒嗙被:', activePrimary.value, '涓庣洰鏍囧垎绫?', categoryId, '涓嶅悓锛岄渶瑕佹洿鏂?)
			console.log('鍑嗗璋冪敤selectPrimaryCategory鍑芥暟...')
			selectPrimaryCategory(categoryId)
		} else {
			console.log('褰撳墠鍒嗙被宸茬粡鏄洰鏍囧垎绫伙紝浣嗗彲鑳界敤鎴锋兂瑕佸埛鏂伴〉闈?)
			console.log('褰撳墠鍒嗙被:', activePrimary.value, '鐩爣鍒嗙被:', categoryId)
			// 鍗充娇鍒嗙被鐩稿悓锛屼篃閲嶆柊鍔犺浇鏁版嵁锛岀‘淇濇暟鎹槸鏈€鏂扮殑
			// 娣诲姞涓€涓皬鐨勫欢杩燂紝纭繚椤甸潰瀹屽叏鏄剧ず鍚庡啀鏇存柊鏁版嵁
			setTimeout(() => {
				selectPrimaryCategory(categoryId)
			}, 100)
		}
	} else {
		console.log('鈿狅笍 onLoad涓湭鎵惧埌鍒嗙被鍙傛暟锛屽皢浣跨敤浠庢暟鎹簱鍔犺浇鐨勭涓€涓垎绫?)
		// 涓嶅啀浣跨敤纭紪鐮佺殑榛樿鍒嗙被锛宭oadCategories 浼氳缃涓€涓垎绫?
	}
	
	console.log('=== category椤甸潰onLoad鎵ц瀹屾垚 ===')
})

// 椤甸潰鏄剧ず鏃朵篃妫€鏌ュ弬鏁帮紝纭繚浠庡叾浠栭〉闈㈣繑鍥炴椂鑳芥纭樉绀?
onShow(() => {
	console.log('=== category椤甸潰onShow琚皟鐢?===')
	console.log('椤甸潰鏄剧ず鏃堕棿:', Date.now())
	console.log('褰撳墠娲诲姩鍒嗙被:', activePrimary.value)
	
	// 1. 浼樺厛妫€鏌?Storage 涓殑鍙傛暟 (鐢遍椤典紶鍏?
	const storageCategoryId = (uni.getStorageSync('selectedCategory') as string) ?? ''
	if (storageCategoryId !== '') {
		console.log('鉁?onShow涓壘鍒癝torage鍒嗙被鍙傛暟:', storageCategoryId)
		hasLoadedFromParams.value = true
		// 娓呴櫎Storage锛岄槻姝笅娆¤璇?
		uni.removeStorageSync('selectedCategory')
		
		if (activePrimary.value !== storageCategoryId) {
			selectPrimaryCategory(storageCategoryId)
		}
		// 濡傛灉鍒嗙被杩樻病鍔犺浇瀹岋紝杩欓噷璁剧疆浜咺D锛岀瓑loadCategories瀹屾垚鍚庝細鑷姩鍖归厤淇℃伅
		return
	}

	// 鍦╫nShow涓紝鎴戜滑涔熼渶瑕佹鏌ユ槸鍚︽湁鏂扮殑鍙傛暟
	// 鍥犱负褰撲粠涓婚〉鍐嶆鐐瑰嚮鍒嗙被璺宠浆杩囨潵鏃讹紝鍙兘涓嶄細瑙﹀彂onLoad
	// 鑰屾槸瑙﹀彂onShow
	
	// 鑾峰彇褰撳墠椤甸潰瀹炰緥鍜屽弬鏁?
	const pages = getCurrentPages()
	if (pages.length > 0) {
		const currentPage = pages[pages.length - 1]
		const rawPageOptions = currentPage.options ?? {}
		console.log('onShow涓幏鍙栧弬鏁?', rawPageOptions)
		const pageOptObj = (rawPageOptions instanceof UTSJSONObject) ? (rawPageOptions as UTSJSONObject) : (JSON.parse(JSON.stringify(rawPageOptions)) as UTSJSONObject)
		
		// 妫€鏌ユ槸鍚︽湁鍒嗙被鍙傛暟
		const pageCategoryId = pageOptObj.getString('categoryId') ?? ''
		if (pageCategoryId !== '') {
			hasLoadedFromParams.value = true
			const categoryId = pageCategoryId
			const categoryName = pageOptObj.getString('name') ?? ''
			
			console.log('鉁?onShow涓壘鍒板垎绫诲弬鏁?', categoryId, categoryName)
			console.log('URL涓殑鏃堕棿鎴冲弬鏁?', pageOptObj.getString('timestamp') ?? '')
			console.log('URL涓殑闅忔満鍙傛暟:', pageOptObj.getString('random') ?? '')
			
			// 妫€鏌ユ槸鍚﹂渶瑕佹洿鏂板垎绫?
			if (activePrimary.value !== categoryId) {
				console.log('褰撳墠鍒嗙被:', activePrimary.value, '涓庣洰鏍囧垎绫?', categoryId, '涓嶅悓锛岄渶瑕佹洿鏂?)
				console.log('鍑嗗璋冪敤selectPrimaryCategory鍑芥暟...')
				selectPrimaryCategory(categoryId)
			} else {
				console.log('褰撳墠鍒嗙被宸茬粡鏄洰鏍囧垎绫伙紝浣嗗彲鑳界敤鎴锋兂瑕佸埛鏂伴〉闈?)
				console.log('褰撳墠鍒嗙被:', activePrimary.value, '鐩爣鍒嗙被:', categoryId)
				// 鍗充娇鍒嗙被鐩稿悓锛屼篃閲嶆柊鍔犺浇鏁版嵁锛岀‘淇濇暟鎹槸鏈€鏂扮殑
				// 娣诲姞涓€涓皬鐨勫欢杩燂紝纭繚椤甸潰瀹屽叏鏄剧ず鍚庡啀鏇存柊鏁版嵁
				setTimeout(() => {
					selectPrimaryCategory(categoryId)
				}, 100)
			}
		} else {
			console.log('鈿狅笍 onShow涓湭鎵惧埌鍒嗙被鍙傛暟')
		}
	}
	
	console.log('=== category椤甸潰onShow鎵ц瀹屾垚 ===')
})


// 娣诲姞鍒拌喘鐗╄溅
async function addToCart(product: Product): Promise<void> {
    uni.showLoading({ title: '妫€鏌ュ晢鍝?..' })
    try {
        const pid = (product.id ?? '').toString()
        const merchantId = product.merchant_id ?? ''
        if (pid === '') {
            uni.hideLoading()
            uni.showToast({ title: '鍟嗗搧鏃犳晥', icon: 'none' })
            return
        }
        
        // 妫€鏌ュ晢鍝佹槸鍚︽湁SKU
        const skus = await supabaseService.getProductSkus(pid)
        uni.hideLoading()
        
        if (skus.length > 0) {
            // 鏈夎鏍硷紝鎻愮ず骞惰烦杞埌鍟嗗搧璇︽儏椤甸€夋嫨瑙勬牸
            uni.showToast({
                title: '璇烽€夋嫨瑙勬牸',
                icon: 'none'
            })
            setTimeout(() => {
                uni.navigateTo({
                    url: '/pages/mall/consumer/product-detail?id=' + pid
                })
            }, 500)
        } else {
            // 鏃犺鏍硷紝鐩存帴鍔犲叆璐墿杞?
            uni.showLoading({ title: '娣诲姞涓?..' })
            const success = await supabaseService.addToCart(pid, 1, '', merchantId)
            uni.hideLoading()
            if (success) {
                uni.showToast({
                    title: '宸叉坊鍔犲埌璐墿杞?,
                    icon: 'success'
                })
                cartCount.value++
            } else {
                uni.showToast({
                    title: '娣诲姞澶辫触锛岃鍏堢櫥褰?,
                    icon: 'none'
                })
            }
        }
    } catch (e) {
        console.error('娣诲姞鍒拌喘鐗╄溅寮傚父', e)
        uni.hideLoading()
        uni.showToast({ title: '鎿嶄綔澶辫触', icon: 'none' })
    }
}

// 瀵艰埅鍑芥暟
function navigateToSearch(): void { uni.navigateTo({ url: '/pages/mall/consumer/search' }) }
function navigateToCart(): void { uni.navigateTo({ url: '/pages/mall/consumer/cart' }) }
function navigateToProduct(product: Product): void {
    const id = (product.id ?? '').toString()
    if (id === '') return
    const price = (product.base_price ?? 0).toString()
    const originalPrice = (product.market_price ?? '').toString()
    const name = encodeURIComponent(product.name ?? '')
    const image = encodeURIComponent(product.main_image_url ?? '')
    
    uni.navigateTo({
        url: `/pages/mall/consumer/product-detail?id=${id}&productId=${id}&price=${price}&originalPrice=${originalPrice}&name=${name}&image=${image}`
    })
}

// 鐩告満鍔熻兘
function onCamera(): void {
    uni.chooseImage({
        count: 1,
        sourceType: ['camera'],
        success: (res) => {
            console.log('鐩告満鎷嶆憚鎴愬姛:', res.tempFilePaths[0])
            uni.showToast({
                title: '宸叉媿鎽勶紝姝ｅ湪璇嗗埆...',
                icon: 'loading'
            })
            // 杩欓噷鍙互娣诲姞鍚庣画鐨勮瘑鍒€昏緫
            setTimeout(() => {
                 uni.showToast({
                    title: '璇嗗埆鎴愬姛',
                    icon: 'success'
                })
            }, 1000)
        },
        fail: (err) => {
            console.error('鐩告満璋冪敤澶辫触:', err)
        }
    })
}

// 鎵爜鍔熻兘
function onScan(): void {
    uni.scanCode({
        success: (res) => {
            console.log('鎵爜鎴愬姛:', res)
            uni.showToast({
                title: '鎵爜鎴愬姛: ' + res.result,
                icon: 'none'
            })
        },
        fail: (err) => {
            console.error('鎵爜澶辫触:', err)
        }
    })
}
</script>

<style>
.category-page {
    width: 100%;
    height: 100%;
    overflow: hidden;
    background-color: #f8fafc;
    display: flex;
    flex-direction: column;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', sans-serif;
}
/* 鎼滅储鏍?*/
.search-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    background: linear-gradient(135deg, #4CAF50 0%, #2E7D32 100%);
    z-index: 1000;
    box-shadow: 0 2px 12px rgba(76, 175, 80, 0.15);
}

/* 瀵艰埅鏍忓崰浣?*/
.navbar-placeholder {
    flex-shrink: 0;
}

/* 鎼滅储鏍?*/
/* 瀵艰埅鏍忔悳绱㈡瀹瑰櫒鍐呰竟璺濊皟鏁?*/
.search-container {
    height: 44px;
    padding: 0 16px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    max-width: 1400px;
    margin: 0 auto;
    width: 100%;
}

/* 鎼滅储妗?hover 鏁堟灉 */
.search-box:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 瀵艰埅鏍忔悳绱㈡瀹瑰櫒鍐呰竟璺濊皟鏁?*/
.search-box {
    flex: 1;
    max-width: 600px;
    background: #f0f0f0;
    border-radius: 20px;
    padding: 0 4px 0 12px;
    display: flex;
    flex-direction: row;
    align-items: center;
    transition: all 0.3s ease;
    width: 100%;
    height: 32px;
}

.search-placeholder {
    font-size: 14px;
    color: #999;
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.nav-inner-search-text {
    font-size: 12px; /* 瀛椾綋绋嶅井鍙樺皬 */
    color: #ffffff;
    font-weight: normal;
}

.icon {
    font-size: 22px;
    color: white;
}

.nav-icon-btn {
    padding: 4px 8px 4px 4px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    border-right: 1px solid #ddd;
    margin-right: 8px;
}

.nav-icon {
    font-size: 18px;
}

.nav-camera-btn {
    padding: 4px 8px 4px 4px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    border-right-width: 1px;
    border-right-style: solid;
    border-right-color: #ddd;
    border-right: 1px solid #ddd; /* 淇UVUE鏍峰紡 */
    margin-right: 8px;
}

.nav-camera-icon {
    font-size: 20px;
}

/* 鎼滅储鎸夐挳楂樺害寰皟 */
.nav-inner-search-btn {
    padding: 0 12px; /* 鍑忓皬鍐呰竟璺?*/
    background-color: #87CEEB; /* 澶╃┖钃?*/
    border-radius: 16px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    height: 24px; /* 闅忔悳绱㈡楂樺害鍑忓皬鑰屽噺灏?*/
}

.cart-badge {
    position: absolute;
    top: -5px;
    right: -5px;
    background: #ff5000;
    color: white;
    font-size: 10px;
    min-width: 18px;
    height: 18px;
    border-radius: 9px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 4px;
    border: 2px solid #4CAF50;
}

/* 鍒嗙被鍐呭鍖?*/
.category-content {
    flex: 1;
    display: flex;
    flex-direction: row;
    padding: 0 16px;
    max-width: 1400px;
    margin-left: auto;
    margin-right: auto;
    width: 100%;
    overflow: hidden;
}

/* 宸︿晶涓€绾у垎绫?*/
.primary-category {
    width: 100px;
    flex: 0 0 100px;
    margin-right: 16px;
    background: white;
    border-radius: 12px;
    padding: 12px 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.primary-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 12px 4px;
    margin: 6px 4px;
    border-radius: 12px;
    transition: all 0.2s ease;
    color: #666;
    text-align: center;
    width: 84px;
    height: 84px;
}

.primary-item:hover {
    transform: translateY(-2px); /* 鎮仠鏃跺悜涓婃诞鍔?*/
}

.primary-item.active {
    color: white !important;
    font-weight: bold;
}

.primary-icon {
    font-size: 24px;
    margin-bottom: 6px;
    margin-right: 0; /* 绉婚櫎鍙宠竟璺?*/
    text-align: center;
    /* display: block; removed for uniapp-x support */
}

.primary-name {
    font-size: 13px;
    line-height: 1.4;
    /* display: block; removed for uniapp-x support */
}

/* 鍙充晶鍐呭鍖?*/
.product-content {
    flex: 1;
    padding: 0;
}

.category-header {
    margin-bottom: 16px;
    padding: 16px 8px 0 8px;
    /* position: sticky; REMOVED for uniapp-x support */
    /* top: 0; */
    background-color: #f8fafc;
    z-index: 10;
}

.category-title {
    font-size: 20px;
    font-weight: bold;
    color: #333;
    margin-bottom: 4px;
}

.category-desc {
    font-size: 14px;
    color: #666;
}

/* 鍟嗗搧缃戞牸 */
.product-grid {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    /* grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); REMOVED for uniapp-x support */
    /* gap: 20px; removed for compatibility */
    padding: 10px; /* add padding to compensate */
    width: 100%;
}

.product-card {
    display: flex;
    flex-direction: column;
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    width: 48%;
    margin-bottom: 12px;
}

.product-image {
    width: 100%;
    height: 170px;
    border-radius: 8px;
    margin-bottom: 8px;
    background: #f5f5f5;
}

.product-name {
    font-size: 13px;
    color: #333;
    margin-bottom: 5px;
    line-height: 1.4;
    height: 36px;
    overflow: hidden;
    text-overflow: ellipsis;
    padding: 0 8px;
}

.product-bottom {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 0 8px 8px;
}

.product-price {
    font-size: 15px;
    color: #ff5000;
    font-weight: bold;
}

.product-add-btn {
    width: 24px;
    height: 24px;
    background-color: #ff5000;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.add-icon {
    color: #fff;
    font-size: 16px;
    font-weight: bold;
}

.product-grid {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 8px;
}

.product-action {
    margin-top: 12px;
}

.cart-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    /* gap: 6px; */
    background: #4CAF50;
    color: white;
    padding: 8px 12px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: bold;
    /* cursor: pointer; removed for uniapp-x support */
    transition: all 0.2s ease;
}

.cart-btn:hover {
    background: #388E3C;
}

.cart-icon {
    font-size: 14px;
    margin-right: 6px; /* gap replacement */
}

/* 绌虹姸鎬?*/
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    text-align: center;
}

.empty-icon {
    font-size: 60px;
    color: #4CAF50;
    margin-bottom: 15px;
}

.empty-text {
    font-size: 18px;
    color: #333;
    font-weight: bold;
    margin-bottom: 8px;
}

.empty-desc {
    font-size: 14px;
    color: #666;
}

/* 鍔犺浇鏇村 */
.load-more {
    text-align: center;
    padding: 20px 0;
    color: #999;
    font-size: 14px;
}

.load-text {
    /* display: inline-block; REMOVED for uniapp-x support */
    padding: 8px 16px;
    background: #f5f5f5;
    border-radius: 20px;
}

/* ===== 鍝嶅簲寮忚璁?===== */

/* 灏忓睆鎵嬫満 (灏忎簬414px) */
@media screen and (max-width: 414px) {
    .search-container {
        padding: 0 12px;
        height: 44px;
    }
    
    .search-box {
        padding: 0 4px 0 12px;
        margin: 0;
        height: 30px;
    }
    
    .category-content {
        padding: 0 6px;
    }
    
    .primary-category {
        width: 70px;
        flex: 0 0 70px;
        padding: 8px 4px;
        margin-right: 8px;
    }
    
    .primary-item {
        margin: 3px auto;
        padding: 6px 2px;
        width: 60px;
        height: 60px;
    }
    
    .primary-icon {
        margin-right: 0;
        margin-bottom: 4px;
        font-size: 18px;
    }
    
    .primary-name {
        font-size: 10px;
        line-height: 1.2;
    }
    
    .product-grid {
        padding: 0 4px 20px 4px;
    }

    .product-card {
        width: 48%;
        margin: 1%;
    }
    
    .product-spec,
    .manufacturer,
    .original-price,
    .sales-info,
    .product-badge {
        display: none;
    }
    
    .product-info {
        padding: 6px;
    }
    
    .product-image {
        height: 100px;
    }
    
    .product-name {
        font-size: 12px;
        height: 32px;
        line-height: 1.3;
        margin-bottom: 2px;
        overflow: hidden;
        text-overflow: ellipsis;
        lines: 2;
    }
    
    .price-section {
        margin-bottom: 0;
        margin-top: 4px;
        justify-content: space-between;
        width: 100%;
    }
    
    .price-symbol {
        font-size: 10px;
    }
    
    .price-value {
        font-size: 14px;
    }
    
    .product-meta {
        display: none;
    }
    
    .search-container {
        padding: 0 12px;
        height: 44px;
    }
    
    .search-box {
        padding: 8px 16px;
    }
    
    .category-header {
        padding: 12px 4px 0 4px;
    }
}

/* 涓睆鎵嬫満/灏忓钩鏉?(415px-768px) */
@media screen and (min-width: 415px) and (max-width: 768px) {
    .search-container {
        padding: 0 16px;
        height: 44px;
    }
    
    .primary-category {
        width: 80px;
        flex: 0 0 80px;
    }
    
    .primary-item {
        width: 68px;
        height: 68px;
        margin: 4px auto;
    }
    
    .product-card {
        width: 46%;
        margin: 2%;
    }
}

/* 骞虫澘璁惧 (769px-1024px) */
@media screen and (min-width: 769px) and (max-width: 1024px) {
    .search-container {
        padding: 0 16px;
        height: 44px;
    }
    
    .primary-category {
        width: 100px;
        flex: 0 0 100px;
    }
    
    .primary-item {
        width: 86px;
        height: 86px;
        margin: 5px auto;
        padding: 10px 4px;
    }
    
    .primary-icon {
        font-size: 28px;
        margin-bottom: 6px;
    }
    
    .primary-name {
        font-size: 13px;
    }
    
    .product-card {
        width: 30%;
        margin: 1.5%;
    }
}

/* 妗岄潰绔?(1025px浠ヤ笂) */
@media screen and (min-width: 1025px) {
    .search-container {
        padding: 0 16px;
        height: 44px;
    }
    
    .category-content {
        padding: 0 24px;
    }
    
    .primary-category {
        width: 120px;
        flex: 0 0 120px;
        padding: 12px 8px;
        margin-right: 24px;
    }
    
    .primary-item {
        width: 100px;
        height: 100px;
        margin: 6px auto;
        padding: 12px 6px;
    }
    
    .primary-icon {
        font-size: 32px;
        margin-bottom: 8px;
    }
    
    .primary-name {
        font-size: 13px;
    }
    
    .product-content {
        padding: 20px 0;
    }
    
    .category-header {
        margin-bottom: 24px;
        padding: 0 12px;
    }
    
    .category-title {
        font-size: 24px;
    }
    
    .category-desc {
        font-size: 15px;
    }
    
    .product-grid {
        /* grid-template-columns: repeat(4, 1fr); REMOVED */
        /* gap: 24px; REMOVED */
    }
    
    .product-card {
        border-radius: 14px;
        width: 22%; /* 4 columns */
        margin: 1.5%;
    }
    
    .product-info {
        padding: 20px;
    }
    
    .product-name {
        font-size: 16px;
    }
    
    .product-spec {
        font-size: 14px;
    }
    
    .price-value {
        font-size: 22px;
    }
}

/* 澶ф闈㈢ (1400px浠ヤ笂) */
@media screen and (min-width: 1400px) {
    .category-content {
        max-width: 1600px;
        padding: 0 32px;
    }
    
    .primary-category {
        width: 140px;
        flex: 0 0 140px;
        padding: 16px 10px;
        margin-right: 30px;
    }
    
    .primary-item {
        width: 118px;
        height: 118px;
        margin: 8px auto;
        padding: 14px 8px;
    }
    
    .primary-icon {
        font-size: 38px;
        margin-bottom: 10px;
    }
    
    .primary-name {
        font-size: 14px;
    }
    
    .product-content {
        padding: 24px 0;
    }
    
    .category-header {
        margin-bottom: 28px;
        padding: 0 16px;
    }
    
    .category-title {
        font-size: 26px;
    }
    
    .category-desc {
        font-size: 16px;
    }
    
    .product-grid {
        /* grid-template-columns: repeat(5, 1fr); REMOVED */
        /* gap: 28px; REMOVED */
    }
    
    .product-card {
        border-radius: 16px;
        width: 17%; /* 5 columns */
        margin: 1.5%;
    }
    
    .product-image {
        height: 180px;
    }
    
    .product-info {
        padding: 24px;
    }
    
    .product-name {
        font-size: 17px;
    }
    
    .product-spec {
        font-size: 15px;
    }
    
    .price-value {
        font-size: 24px;
    }
}
</style>


