<template>
  <view class="inspect-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back" @tap="goBack">
        <uni-icons type="left" size="20" color="#222" />
      </view>
      <text class="nav-title">步骤一：数量确认</text>
      <view class="nav-icons">
        <uni-icons type="scan" size="24" color="#222" />
      </view>
    </view>
    <view class="main-content">
      <!-- 左侧分类导航 -->
      <view class="category-nav">
        <view v-for="(cat, idx) in categories" :key="cat.title"
          :class="['category-item', { active: idx === currentCategory }]" @tap="switchCategory(idx)">
          <text>{{ cat.title }}</text>
          <view v-if="cat.badge" class="category-badge">{{ cat.badge }}</view>
        </view>
      </view>
      <!-- 右侧商品卡片区 -->
      <scroll-view class="goods-list" scroll-y @scrolltolower="loadMoreGoods">
        <view v-for="(item, idx) in currentGoods" :key="item.id" class="goods-card">
          <view class="goods-header">
            <view class="goods-img-container">
              <image :src="item.image" class="goods-img" />
              <!-- 品牌标签 -->
              <view class="brand-tag" v-if="item.isPin === 'Y'">品牌</view>
            </view>
            <view class="goods-info">
              <view class="goods-title-row">
                <text class="goods-name">{{ item.name }}</text>
                <text class="goods-price">
                  {{ formatPrice(item) }} 
                  <text class="goods-unit" v-if="item.unit">/{{item.unit}}</text>
                </text>
              </view>
              <text class="goods-desc">{{ item.desc }}</text>
              <!-- 显示已选择的品牌款式信息 -->
              <view v-if="getSelectedBrandStyles(item).length > 0" class="selected-styles">
                <view v-for="style in getSelectedBrandStyles(item)" :key="style.uniqueKey" class="style-item">
                  <text class="style-text">{{ style.brandName }} - {{ style.styleName }} x{{ style.quantity }}</text>
                </view>
              </view>
            </view>
          </view>
          <view class="goods-row">
            <text class="row-label">合格数量</text>
            <view class="num-ctrl">
              <button class="num-btn" @tap="updateQuantity(idx, -1)">-</button>
              <text class="num">{{ getItemTotalQuantity(item) }}</text>
              <button class="num-btn" @tap="updateQuantity(idx, 1)">+</button>
            </view>
          </view>
        </view>
        <view v-if="loadingMore" class="loading-more">加载中...</view>
        <view v-else-if="finished" class="loading-more">没有更多了</view>
      </scroll-view>
    </view>
    <!-- 底部操作按钮 -->
    <view class="footer-btns">
      <button class="btn-outline" @tap="goBack">返回订单详情</button>
      <button class="btn-main" @tap="goNext">下一步</button>
    </view>

    <!-- 品牌选择组件 -->
    <brand-selector ref="brandSelector" @brand-confirm="onBrandConfirm" @reduce-select="onReduceSelect"
      @close="onBrandSelectorClose" @get-existing-quantities="getExistingQuantities"></brand-selector>
  </view>
</template>

<script>
import brandSelector from '../../compoent/recycle/brand-selector.vue'
export default {
  components: {
    brandSelector
  },
  data() {
    return {
      statusBarHeight: 0,
      currentCategory: 0,
      orderId: '',
      order: null,  // 订单数据
      currentGoods: [], // 当前显示的商品列表
      inspectResult: {}, // 质检结果对象，按照新的数据格式
      allProducts: {},      // { [categoryId]: [商品数组] }
      allProductsPage: {},  // { [categoryId]: 当前已加载页码 }
      allProductsTotal: {}, // { [categoryId]: 总数 }
      pageSize: 10,
      loadingMore: false,
      finished: false,
      // 品牌选择相关
      pendingBrandIndex: null,
      reduceItem: null, // 待减少数量的商品
      brandStyleCache: {}, // 全局品牌款式缓存
      // brandIndexList 改为 computed
    }
  },
  computed: {
    categories() {
      const list = getApp().globalData.pricePreviewList || []
      console.log('categories计算 - pricePreviewList:', list.length)
      
      // 显示所有分类，不再根据订单数据筛选
      const allCategories = list.sort((a, b) => a.sort - b.sort)
    //   const allCategories = list.filter(item => item.pid === '0').sort((a, b) => a.sort - b.sort)
      // 为每个分类计算数量
      const categoriesWithCount = allCategories.map(category => {
        const count = this.getCategoryItemCountDirect(category.id)
        return {
          ...category,
          badge: count > 0 ? count : null
        }
      })
      
      // 新增不可回收和质量问题分类
      const extra = [
        { id: 'unrecyclable', title: '不可回收', badge: this.getUnrecyclableCount() },
        { id: 'quality_issue', title: '质量问题', badge: this.getQualityIssueCount() }
      ]
      
      const result = [...categoriesWithCount, ...extra]
      console.log('categories计算 - 最终结果:', result.map(c => ({ id: c.id, title: c.title, badge: c.badge })))
      return result
    },
  },
  methods: {
    initInspectResult() {
      // 只初始化空的list
      this.inspectResult = {
        id: this.order ? this.order.id : '',
        list: []
      }
    },
    
    // 获取分类商品数量（直接方法，避免递归）
    getCategoryItemCountDirect(categoryId) {
      if (categoryId === 'unrecyclable') {
        return this.getUnrecyclableCount()
      }
      if (categoryId === 'quality_issue') {
        return this.getQualityIssueCount()
      }
      let totalCount = 0
      if (this.inspectResult.list && this.inspectResult.list.length > 0) {
        this.inspectResult.list.forEach(inspectItem => {
          if (inspectItem.categoryId === categoryId) {
            totalCount += inspectItem.qualifiedNum || 0
          }
        })
      }
      return totalCount
    },
    
    // 获取当前分类ID（避免递归）
    getCurrentCategoryId() {
      const list = getApp().globalData.pricePreviewList || []
      const allCategories = list.filter(item => item.pid === '0').sort((a, b) => a.sort - b.sort)
      const extra = [
        { id: 'unrecyclable', title: '不可回收' },
        { id: 'quality_issue', title: '质量问题' }
      ]
      const allCategoriesWithExtra = [...allCategories, ...extra]
      
      return allCategoriesWithExtra[this.currentCategory]?.id
    },
    
    // 获取分类商品数量（保持原有方法名兼容性）
    getCategoryItemCount(categoryId) {
      return this.getCategoryItemCountDirect(categoryId)
    },
    
    // 获取不可回收数量
    getUnrecyclableCount() {
      // 从inspectResult中获取不可回收的数量
      const unrecyclableItem = this.inspectResult.list?.find(item => item.id === 'unrecyclable')
      return unrecyclableItem ? unrecyclableItem.unrecyclable : 0
    },
    
    // 获取质量问题数量
    getQualityIssueCount() {
      // 从inspectResult中获取质量问题的数量
      const qualityIssueItem = this.inspectResult.list?.find(item => item.id === 'quality_issue')
      return qualityIssueItem ? qualityIssueItem.noQualifiedNum : 0
    },
    fetchGoodsList(categoryId, page = 1, callback) {
      this.$api('getClassGoodsList', {
        classId: categoryId,
        pageNo: page,
        pageSize: this.pageSize
      }, res => {
        if (res.code === 200 && res.result && Array.isArray(res.result.records)) {
          const oldList = this.allProducts[categoryId] || []
          const newList = page === 1 ? res.result.records : oldList.concat(res.result.records)
          this.$set(this.allProducts, categoryId, newList)
          this.$set(this.allProductsPage, categoryId, page)
          this.$set(this.allProductsTotal, categoryId, res.result.total)
          this.updateCurrentGoods()
        }
        if (callback) callback()
      })
    },
    updateCurrentGoods() {
      const currentCategoryId = this.categories[this.currentCategory]?.id
      // 不可回收分类内容
      if (currentCategoryId === 'unrecyclable') {
        // 从inspectResult中获取不可回收的数量
        const unrecyclableItem = this.inspectResult.list?.find(item => item.id === 'unrecyclable')
        const unrecyclableCount = unrecyclableItem ? unrecyclableItem.unrecyclable : 0
        
        this.currentGoods = [{
          id: 'unrecyclable-1',
          image: '/static/回收/衣物.png',
          name: '不可回收品类',
          price: '—',
          desc: '允许脏破烂，160码以上',
          qualified: unrecyclableCount,
          amount: '',
          originalNum: 0 // 不设置最大数量限制
        }]
        return
      }
      // 质量问题分类内容
      if (currentCategoryId === 'quality_issue') {
        // 从inspectResult中获取质量问题的数量
        const qualityIssueItem = this.inspectResult.list?.find(item => item.id === 'quality_issue')
        const qualityIssueCount = qualityIssueItem ? qualityIssueItem.noQualifiedNum : 0
        
        this.currentGoods = [{
          id: 'quality-issue-1',
          image: '/static/回收/衣物.png',
          name: '质量问题品类',
          price: '—',
          desc: '存在质量问题，无法正常回收',
          qualified: qualityIssueCount,
          amount: '',
          originalNum: 0 // 不设置最大数量限制
        }]
        return
      }
      // 从API获取的商品数据
      const categoryGoods = this.allProducts[currentCategoryId] || []
      // 将API商品数据转换为质检页面格式，并合并inspectResult.list中已选状态（shopId和id双向查找）
      const goodsList = categoryGoods.map((item, index) => {
        // 从订单数据中查找对应的商品
        const orderItem = this.getOrderItemByProductId(item.id)
        let itemId = item.id
        if (orderItem && orderItem.id) {
          itemId = orderItem.id
        }
        const inspectItem = this.inspectResult.list?.find(listItem =>
          listItem.shopId == item.id || listItem.shopId == itemId || listItem.id == item.id || listItem.id == itemId
        )
        // 恢复品牌款式数据 - 从所有分类的商品中查找
        const brandStyleQuantities = {}
        const styleCache = {}
        let totalQuantity = 0
        
        // 查找所有分类中是否有相同商品的品牌款式数据
        Object.values(this.allProducts).forEach(categoryProducts => {
          const existingProduct = categoryProducts.find(p => p.id === item.id)
          if (existingProduct && this.currentGoods) {
            const existingGoodsItem = this.currentGoods.find(g => g.id === item.id)
            if (existingGoodsItem && existingGoodsItem.brandStyleQuantities) {
              Object.assign(brandStyleQuantities, existingGoodsItem.brandStyleQuantities)
              Object.assign(styleCache, existingGoodsItem.styleCache)
              totalQuantity = Object.values(existingGoodsItem.brandStyleQuantities).reduce((sum, qty) => sum + qty, 0)
            }
          }
        })
        
        // 如果没有找到现有数据，尝试从全局状态中恢复
        if (totalQuantity === 0 && this.brandStyleCache && this.brandStyleCache[item.id]) {
          Object.assign(brandStyleQuantities, this.brandStyleCache[item.id].brandStyleQuantities || {})
          Object.assign(styleCache, this.brandStyleCache[item.id].styleCache || {})
          totalQuantity = Object.values(brandStyleQuantities).reduce((sum, qty) => sum + qty, 0)
        }
        
        // 如果没有品牌款式数据，使用普通数量
        const finalQuantity = totalQuantity > 0 ? 0 : (inspectItem ? inspectItem.qualifiedNum : 0)
        
        return {
          id: item.id,
          image: item.image || '/static/回收/衣物.png',
          name: item.name,
          price: item.price || 0,
          maxPrice: item.maxPrice || 0,
          desc: item.service || '允许脏破烂，160码以上',
          qualified: inspectItem ? inspectItem.qualifiedNum : 0,
          originalNum: 0,
          estimatedPrice: orderItem ? orderItem.estimatedPrice : 0,
          originalId: item.id,
          isPin: item.isPin || 'N',
          orderItem: orderItem,
          unit: item.unit || '件',
          // 品牌款式相关数据
          brandStyleQuantities: brandStyleQuantities,
          styleCache: styleCache,
          quantity: finalQuantity
        }
      })
      this.currentGoods = goodsList
    },
    
    // 根据商品ID从订单数据中查找对应商品
    getOrderItemByProductId(productId) {
      if (!this.order || !this.order.commonOrderList) {
        return null
      }
      // 支持id和shopId双向查找
      return this.order.commonOrderList.find(item => item.id == productId || item.shopId == productId)
    },
    
    goBack() {
      uni.navigateBack()
    },
    goNext() {
      // 检测是否所有商品都已完成质检和填写价格
      const validationResult = this.validateInspectData()
      if (!validationResult.isValid) {
        uni.showToast({
          title: validationResult.message,
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      // 将品牌款式数据转换为独立的质检对象
      const processedInspectResult = this.processInspectResultForBrandStyles()
      
      // 构造传递给步骤二的完整数据
      const resultData = {
        inspectResult: processedInspectResult,
        order: this.order // 同时传递订单信息
      }
      console.log('resultDataStr:', resultData)
      const resultDataStr = encodeURIComponent(JSON.stringify(resultData))
 
      uni.navigateTo({
        url: `/pages/manager/inspect-result?resultData=${resultDataStr}`
      })
    },
    
    // 处理品牌款式数据，将每个品牌款式组合生成独立的质检对象
    processInspectResultForBrandStyles() {
      const processedList = []
      
      // 遍历当前的质检结果
      this.inspectResult.list.forEach(inspectItem => {
        // 不可回收和质量问题直接保留
        if (inspectItem.id === 'unrecyclable' || inspectItem.id === 'quality_issue') {
          processedList.push(inspectItem)
          return
        }
        
        // 从全局缓存中查找品牌款式数据
        const cachedBrandStyleData = this.findBrandStyleDataFromCache(inspectItem.shopId)
        
        if (cachedBrandStyleData && Object.keys(cachedBrandStyleData.brandStyleQuantities).length > 0) {
          // 如果有品牌款式数据，为每个品牌款式创建独立对象
          Object.entries(cachedBrandStyleData.brandStyleQuantities).forEach(([uniqueKey, quantity]) => {
            if (quantity > 0 && cachedBrandStyleData.styleCache && cachedBrandStyleData.styleCache[uniqueKey]) {
              const { brandInfo, styleInfo } = cachedBrandStyleData.styleCache[uniqueKey]
              
              // 为每个品牌款式组合创建独立的质检对象
              const brandStyleInspectItem = {
                ...inspectItem,
                qualifiedNum: quantity,
                shopId: inspectItem.shopId,
                pinId: brandInfo.id,
                styleId: styleInfo.id,
                brandName: brandInfo.name,
                styleName: styleInfo.name,
                brandImage: brandInfo.logo,
                styleImage: styleInfo.image,
                uniqueKey: uniqueKey,
                // 添加款式价格信息
                styleMinPrice: styleInfo.minPrice || 0,
                styleMaxPrice: styleInfo.maxPrice || styleInfo.minPrice || 0,
                commonOrderList: [{
                  testingInstructions: '',
                  testingImages: '',
                  testingStatus: 0
                }]
              }
              processedList.push(brandStyleInspectItem)
            }
          })
        } else {
          // 没有品牌款式数据，保留原始对象并添加商品价格信息
          const productId = this.getProductIdFromShopId(inspectItem.shopId)
          const productInfo = this.findProductInfoById(productId)
          const enhancedInspectItem = {
            ...inspectItem,
            // 添加商品本身的价格信息
            productMinPrice: productInfo ? productInfo.price || 0 : 0,
            productMaxPrice: productInfo ? productInfo.maxPrice || productInfo.price || 0 : 0
          }
          processedList.push(enhancedInspectItem)
        }
      })
      
      return {
        id: this.inspectResult.id,
        list: processedList
      }
    },
    
    // 根据shopId查找当前商品
    findCurrentGoodsByShopId(shopId) {
      return this.currentGoods.find(item => {
        const orderItem = this.getOrderItemByProductId(item.id)
        const itemId = orderItem ? (orderItem.shopId || orderItem.id) : item.id
        return itemId == shopId
      })
    },
    
    // 从全局缓存和所有分类商品中查找品牌款式数据
    findBrandStyleDataFromCache(shopId) {
      // 首先从全局缓存中查找
      const productId = this.getProductIdFromShopId(shopId)
      if (productId && this.brandStyleCache[productId]) {
        return this.brandStyleCache[productId]
      }
      
      // 从所有分类的商品中查找
      for (const categoryId in this.allProducts) {
        const categoryProducts = this.allProducts[categoryId]
        for (const product of categoryProducts) {
          const orderItem = this.getOrderItemByProductId(product.id)
          const itemId = orderItem ? (orderItem.shopId || orderItem.id) : product.id
          
          if (itemId == shopId && this.brandStyleCache[product.id]) {
            return this.brandStyleCache[product.id]
          }
        }
      }
      
      return null
    },
    
    // 根据shopId获取productId
    getProductIdFromShopId(shopId) {
      // 从订单数据中查找
      if (this.order && this.order.commonOrderList) {
        const orderItem = this.order.commonOrderList.find(item => 
          item.shopId == shopId || item.id == shopId
        )
        if (orderItem) {
          return orderItem.shopId || orderItem.id
        }
      }
      
      // 从所有分类商品中查找
      for (const categoryId in this.allProducts) {
        const categoryProducts = this.allProducts[categoryId]
        const product = categoryProducts.find(p => {
          const orderItem = this.getOrderItemByProductId(p.id)
          const itemId = orderItem ? (orderItem.shopId || orderItem.id) : p.id
          return itemId == shopId
        })
        if (product) {
          return product.id
        }
      }
      
      return shopId
    },
    
    // 根据商品ID查找商品信息
    findProductInfoById(productId) {
      // 从所有分类商品中查找
      for (const categoryId in this.allProducts) {
        const categoryProducts = this.allProducts[categoryId]
        const product = categoryProducts.find(p => p.id == productId)
        if (product) {
          return product
        }
      }
      return null
    },
    
    validateInspectData() {
      if (!this.inspectResult.list || this.inspectResult.list.length === 0) {
        return {
          isValid: false,
          message: '没有质检数据'
        }
      }
      for (const item of this.inspectResult.list) {
        // 不可回收和质量问题不需要校验金额
        if (item.id === 'unrecyclable' || item.id === 'quality_issue') {
          continue
        }
        // 只判断是否填写了commonOrderList（即有质检结果）
        if (!item.commonOrderList || item.commonOrderList.length === 0) {
          return {
            isValid: false,
            message: '有商品未完成质检选择'
          }
        }
        // 检查是否有空的testingStatus
        const hasEmptyStatus = item.commonOrderList.some(commonItem => 
          commonItem.testingStatus === '' || commonItem.testingStatus === null || commonItem.testingStatus === undefined
        )
        if (hasEmptyStatus) {
          return {
            isValid: false,
            message: '有商品未完成质检选择'
          }
        }
        // 不再校验价格，价格将在下一步填写
      }
      return {
        isValid: true,
        message: ''
      }
    },
    switchCategory(idx) {
      this.currentCategory = idx
      this.loadingMore = false
      this.finished = false
      const categoryId = this.categories[idx]?.id
      
      if (categoryId === 'unrecyclable' || categoryId === 'quality_issue') {
        // 不可回收和质量问题分类直接更新商品列表
      this.updateCurrentGoods()
        return
      }
      
      // 如果该分类的商品还没有加载，调用API获取
      if (!this.allProducts[categoryId]) {
        this.fetchGoodsList(categoryId, 1)
      } else {
        // 已有数据，直接更新显示
        this.updateCurrentGoods()
      }
    },
    // 更新商品数量
    updateQuantity(index, delta) {
      const categoryId = this.categories[this.currentCategory]?.id
      const item = this.currentGoods[index]
      if (!item) return

      // 处理不可回收和质量问题
      if (item.id === 'unrecyclable-1' || item.id === 'quality-issue-1') {
        const newQualified = Math.max(0, (item.qualified || 0) + delta)
        this.$set(item, 'qualified', newQualified)
        this.updateInspectResult(item, 'qualified', delta, categoryId)
        // 更新商品列表以同步显示
        this.updateCurrentGoods()
        this.$forceUpdate()
        return
      }

      // 如果是减少数量且delta为负数
      if (delta < 0) {
        // 检查是否有多个品牌款式
        if (item.brandStyleQuantities && Object.keys(item.brandStyleQuantities).length > 1) {
          // 有多个品牌款式，显示选择弹窗
          this.reduceItem = { item, index, delta }
          const reduceStyleList = Object.entries(item.brandStyleQuantities)
            .filter(([uniqueKey, quantity]) => quantity > 0)
            .map(([uniqueKey, quantity]) => {
              const cacheInfo = item.styleCache[uniqueKey]
              return {
                uniqueKey,
                quantity,
                name: cacheInfo ? `${cacheInfo.brandInfo.name} - ${cacheInfo.styleInfo.name}` : '未知款式',
                logo: cacheInfo ? cacheInfo.brandInfo.logo : ''
              }
            })
          this.$refs.brandSelector.openReducePopup(reduceStyleList)
          return
        } else if (item.brandStyleQuantities && Object.keys(item.brandStyleQuantities).length === 1) {
          // 只有一个品牌款式，直接减少
          const uniqueKey = Object.keys(item.brandStyleQuantities)[0]
          const currentQty = item.brandStyleQuantities[uniqueKey] || 0
          const newQty = Math.max(0, currentQty + delta)
          this.$set(item.brandStyleQuantities, uniqueKey, newQty)

          // 如果数量为0，删除该品牌款式
          if (newQty === 0) {
            delete item.brandStyleQuantities[uniqueKey]
            if (item.styleCache && item.styleCache[uniqueKey]) {
              delete item.styleCache[uniqueKey]
            }
          }
          this.updateInspectResultFromBrandStyle(item)
          return
        } else {
          // 没有品牌数量，使用原来的逻辑
          let newQuantity = (item.quantity || 0) + delta
          if (newQuantity < 0) newQuantity = 0
          this.$set(item, 'quantity', newQuantity)
          this.updateInspectResultFromQuantity(item)
          return
        }
      }

      // 品牌商品且加一时，每次都重新选择品牌款式
      if (item.isPin === 'Y' && delta > 0) {
        this.pendingBrandIndex = index
        this.$refs.brandSelector.open(item.id)
        return
      }
      
      // 无品牌商品，直接加减数量
      if (item.isPin !== 'Y') {
        let newQuantity = (item.quantity || 0) + delta
        if (newQuantity < 0) newQuantity = 0
        this.$set(item, 'quantity', newQuantity)
        this.updateInspectResultFromQuantity(item)
        return
      }
    },
    
    // 获取商品的总数量（所有品牌款式）
    getItemTotalQuantity(item) {
      // 特殊处理不可回收和质量问题
      if (item.id === 'unrecyclable-1' || item.id === 'quality-issue-1') {
        return item.qualified || 0
      }
      
      if (item.brandStyleQuantities && Object.keys(item.brandStyleQuantities).length > 0) {
        return Object.values(item.brandStyleQuantities).reduce((sum, qty) => sum + qty, 0)
      }
      return item.quantity || 0
    },
    
    // 获取已选择的品牌款式信息
    getSelectedBrandStyles(item) {
      const styles = []
      if (item.brandStyleQuantities && item.styleCache) {
        Object.entries(item.brandStyleQuantities).forEach(([uniqueKey, quantity]) => {
          if (quantity > 0 && item.styleCache[uniqueKey]) {
            const { brandInfo, styleInfo } = item.styleCache[uniqueKey]
            styles.push({
              uniqueKey,
              quantity,
              brandName: brandInfo.name,
              styleName: styleInfo.name
            })
          }
        })
      }
      return styles
    },
    
    // 处理品牌确认事件
    onBrandConfirm(data) {
      if (this.pendingBrandIndex !== null) {
        const item = this.currentGoods[this.pendingBrandIndex]
        if (item && data.selectedStyles && data.selectedStyles.length > 0) {
          // 初始化品牌款式数量对象
          if (!item.brandStyleQuantities) {
            this.$set(item, 'brandStyleQuantities', {})
          }

          // 为每个选中的款式累加数量（不清理现有数据，而是累加）
          data.selectedStyles.forEach(style => {
            if (style.quantity > 0) {
              const uniqueKey = `${data.brandInfo.id}_${style.id}`
              const existingQty = item.brandStyleQuantities[uniqueKey] || 0
              this.$set(item.brandStyleQuantities, uniqueKey, existingQty + style.quantity)
              
              // 缓存款式信息用于后续显示
              if (!item.styleCache) {
                this.$set(item, 'styleCache', {})
              }
              this.$set(item.styleCache, uniqueKey, {
                brandInfo: data.brandInfo,
                styleInfo: style
              })
            }
          })

          // 清除原来的quantity
          if (item.quantity) {
            this.$set(item, 'quantity', 0)
          }
          
          // 更新质检结果
          this.updateInspectResultFromBrandStyle(item)
          
          // 保存到全局缓存
          this.$set(this.brandStyleCache, item.id, {
            brandStyleQuantities: { ...item.brandStyleQuantities },
            styleCache: { ...item.styleCache }
          })
        }
        this.pendingBrandIndex = null
      }
    },
    
    // 处理减少品牌选择事件
    onReduceSelect(selectInfo) {
      const { item, index, delta } = this.reduceItem
      
      if (selectInfo.uniqueKey) {
        // 品牌款式减少逻辑
        const currentQty = item.brandStyleQuantities[selectInfo.uniqueKey] || 0
        const newQty = Math.max(0, currentQty + delta)

        this.$set(item.brandStyleQuantities, selectInfo.uniqueKey, newQty)

        // 如果数量为0，删除该品牌款式
        if (newQty === 0) {
          delete item.brandStyleQuantities[selectInfo.uniqueKey]
          if (item.styleCache && item.styleCache[selectInfo.uniqueKey]) {
            delete item.styleCache[selectInfo.uniqueKey]
          }
        }
        
        this.updateInspectResultFromBrandStyle(item)
        
        // 更新全局缓存
        this.$set(this.brandStyleCache, item.id, {
          brandStyleQuantities: { ...item.brandStyleQuantities },
          styleCache: { ...item.styleCache }
        })
      }

      this.reduceItem = null
    },
    
    // 处理品牌选择器关闭事件
    onBrandSelectorClose() {
      this.pendingBrandIndex = null
    },
    
    // 获取已有的款式数量
    getExistingQuantities(brandId, callback) {
      if (this.pendingBrandIndex !== null) {
        const item = this.currentGoods[this.pendingBrandIndex]
        if (item && item.brandStyleQuantities) {
          // 过滤出当前品牌的款式数量
          const existingQuantities = {}
          Object.entries(item.brandStyleQuantities).forEach(([uniqueKey, quantity]) => {
            if (uniqueKey.startsWith(`${brandId}_`)) {
              existingQuantities[uniqueKey] = quantity
            }
          })
          callback(existingQuantities)
        } else {
          callback({})
        }
      } else {
        callback({})
      }
    },
    
    // 从品牌款式数据更新质检结果
    updateInspectResultFromBrandStyle(item) {
      const totalQuantity = this.getItemTotalQuantity(item)
      
      // 如果总数量为0，移除质检结果
      if (totalQuantity === 0) {
        this.removeInspectItem(item)
        return
      }
      
      // 更新或创建质检结果项
      const categoryId = this.categories[this.currentCategory]?.id
      const orderItem = this.getOrderItemByProductId(item.id)
      const itemId = orderItem ? (orderItem.shopId || orderItem.id) : item.id
      
      let inspectItem = this.inspectResult.list?.find(listItem => listItem.shopId == itemId)
      if (!inspectItem) {
        inspectItem = {
          price: 0,
          qualifiedNum: totalQuantity,
          noQualifiedNum: 0,
          unrecyclable: 0,
          shopId: itemId,
          pinId: '',
          categoryId: categoryId || '',
          commonOrderList: [{
            testingInstructions: '',
            testingImages: '',
            testingStatus: 0
          }]
        }
        this.inspectResult.list.push(inspectItem)
      } else {
        inspectItem.qualifiedNum = totalQuantity
      }
    },
    
    // 从普通数量更新质检结果
    updateInspectResultFromQuantity(item) {
      const quantity = item.quantity || 0
      
      // 如果数量为0，移除质检结果
      if (quantity === 0) {
        this.removeInspectItem(item)
        return
      }
      
      // 更新或创建质检结果项
      const categoryId = this.categories[this.currentCategory]?.id
      const orderItem = this.getOrderItemByProductId(item.id)
      const itemId = orderItem ? (orderItem.shopId || orderItem.id) : item.id
      
      let inspectItem = this.inspectResult.list?.find(listItem => listItem.shopId == itemId)
      if (!inspectItem) {
        inspectItem = {
          price: 0,
          qualifiedNum: quantity,
          noQualifiedNum: 0,
          unrecyclable: 0,
          shopId: itemId,
          pinId: '',
          categoryId: categoryId || '',
          commonOrderList: [{
            testingInstructions: '',
            testingImages: '',
            testingStatus: 0
          }]
        }
        this.inspectResult.list.push(inspectItem)
      } else {
        inspectItem.qualifiedNum = quantity
      }
    },
    
    // 修改：移除商品对象方法，支持不可回收和质量问题
    removeInspectItem(item) {
      // 判断不可回收和质量问题
      if (item.id === 'unrecyclable-1' || item.id === 'unrecyclable') {
        const idx = this.inspectResult.list.findIndex(listItem => listItem.id === 'unrecyclable')
        if (idx !== -1) {
          this.inspectResult.list.splice(idx, 1)
        }
        return
      }
      if (item.id === 'quality-issue-1' || item.id === 'quality_issue') {
        const idx = this.inspectResult.list.findIndex(listItem => listItem.id === 'quality_issue')
        if (idx !== -1) {
          this.inspectResult.list.splice(idx, 1)
        }
        return
      }
      let itemId = item.originalId || item.id
      const orderItem = this.getOrderItemByProductId(itemId)
      if (orderItem && orderItem.id) {
        itemId = orderItem.id
      }
      // shopId 匹配
      const idx = this.inspectResult.list.findIndex(listItem => listItem.shopId == (orderItem ? (orderItem.shopId || orderItem.id) : itemId))
      if (idx !== -1) {
        this.inspectResult.list.splice(idx, 1)
      }
    },
    updateInspectResult(item, type, delta, currentCategoryId) {
      // 处理不可回收分类
      if (item.id === 'unrecyclable-1') {
        let inspectItem = this.inspectResult.list.find(listItem => listItem.id === 'unrecyclable')
        if (!inspectItem && delta > 0) {
          inspectItem = {
            id: 'unrecyclable',
            price: 0,
            qualifiedNum: 0,
            noQualifiedNum: 0,
            unrecyclable: 0, // 初始值为0
            shopId: '',
            pinId: '',
            categoryId: '',
            commonOrderList: [] // 初始为空数组
          }
          this.inspectResult.list.push(inspectItem)
        }
        if (!inspectItem) return
        if (type === 'qualified' && delta > 0) {
          inspectItem.unrecyclable++
          // 增加一个commonOrderList对象
          inspectItem.commonOrderList.push({
            testingInstructions: '',
            testingImages: '',
            testingStatus: 2
          })
        } else if (type === 'qualified' && delta < 0) {
          inspectItem.unrecyclable = Math.max(0, inspectItem.unrecyclable - 1)
          // 减少一个commonOrderList对象
          if (inspectItem.commonOrderList.length > 0) {
            inspectItem.commonOrderList.pop()
          }
          // 新增：如果减到0，移除该对象
          if (inspectItem.unrecyclable === 0) {
            const idx = this.inspectResult.list.findIndex(listItem => listItem === inspectItem)
            if (idx !== -1) {
              this.inspectResult.list.splice(idx, 1)
            }
            return
          }
        }
        console.log('不可回收对象:', inspectItem)
        return
      }
      if (item.id === 'quality-issue-1') {
        let inspectItem = this.inspectResult.list.find(listItem => listItem.id === 'quality_issue')
        if (!inspectItem && delta > 0) {
          inspectItem = {
            id: 'quality_issue',
            price: 0,
            qualifiedNum: 0,
            noQualifiedNum: 0, // 初始值为0
            unrecyclable: 0,
            shopId: '',
            pinId: '',
            categoryId: '',
            commonOrderList: [] // 初始为空数组
          }
          this.inspectResult.list.push(inspectItem)
        }
        if (!inspectItem) return
        if (type === 'qualified' && delta > 0) {
          inspectItem.noQualifiedNum++
          // 增加一个commonOrderList对象
          inspectItem.commonOrderList.push({
            testingInstructions: '',
            testingImages: '',
            testingStatus: 1
          })
        } else if (type === 'qualified' && delta < 0) {
          inspectItem.noQualifiedNum = Math.max(0, inspectItem.noQualifiedNum - 1)
          // 减少一个commonOrderList对象
          if (inspectItem.commonOrderList.length > 0) {
            inspectItem.commonOrderList.pop()
          }
          // 新增：如果减到0，移除该对象
          if (inspectItem.noQualifiedNum === 0) {
            const idx = this.inspectResult.list.findIndex(listItem => listItem === inspectItem)
            if (idx !== -1) {
              this.inspectResult.list.splice(idx, 1)
            }
            return
          }
        }
        console.log('质量问题对象:', inspectItem)
        return
      }
      let itemId = item.originalId || item.id
      const orderItem = this.getOrderItemByProductId(itemId)
      if (orderItem && orderItem.id) {
        itemId = orderItem.id
      }
      let inspectItem = this.inspectResult.list.find(listItem => listItem.shopId == (orderItem ? (orderItem.shopId || orderItem.id) : itemId))
      if (!inspectItem && delta > 0) {
        inspectItem = {
          price: 0,
          qualifiedNum: 0,
          noQualifiedNum: 0,
          unrecyclable: 0,
          shopId: orderItem ? (orderItem.shopId || orderItem.id) : itemId,
          pinId: '',
          categoryId: currentCategoryId || '', // 直接用当前分类id
          commonOrderList: [{
            testingInstructions: '',
            testingImages: '',
            testingStatus: 0
          }] // 合格产品固定一个commonOrderList项
        }
        this.inspectResult.list.push(inspectItem)
      }
      if (!inspectItem) return
      if (type === 'qualified' && delta > 0) {
        inspectItem.qualifiedNum++
        // 合格产品不需要动态增加commonOrderList，保持固定一个
      } else if (type === 'qualified' && delta < 0) {
        inspectItem.qualifiedNum = Math.max(0, inspectItem.qualifiedNum - 1)
        // 合格产品不需要动态减少commonOrderList
        // 新增：如果减到0，移除该商品对象
        if (inspectItem.qualifiedNum === 0) {
          const idx = this.inspectResult.list.findIndex(listItem => listItem === inspectItem)
          if (idx !== -1) {
            this.inspectResult.list.splice(idx, 1)
          }
          return
        }
      }
      
      console.log('更新后的inspectResult:', JSON.stringify(this.inspectResult, null, 2))
    },
    
    loadMoreGoods() {
      const categoryId = this.categories[this.currentCategory]?.id
      
      // 不可回收和质量问题分类不支持加载更多
      if (categoryId === 'unrecyclable' || categoryId === 'quality_issue') {
        return
      }
      
      const page = (this.allProductsPage[categoryId] || 1) + 1
      const total = this.allProductsTotal[categoryId] || 0
      const loaded = (this.allProducts[categoryId] || []).length

      if (this.loadingMore || this.finished) return

      if (loaded < total) {
        this.loadingMore = true
        this.fetchGoodsList(categoryId, page, () => {
          this.loadingMore = false
          // 判断是否加载完
          const newLoaded = (this.allProducts[categoryId] || []).length
          this.finished = newLoaded >= (this.allProductsTotal[categoryId] || 0)
        })
      } else {
        this.finished = true
      }
    },
    


    
    // 格式化价格显示
    formatPrice(item) {
      const price = item.price
      const maxPrice = item.maxPrice
      
      // 如果两个价格都没有或都为0，显示占位符
      if ((!price || price === 0) && (!maxPrice || maxPrice === 0)) {
        return '¥ —'
      }
      
      // 如果只有一个价格有值
      if (price && (!maxPrice || maxPrice === 0)) {
        return `¥ ${price}`
      }
      
      if (maxPrice && (!price || price === 0)) {
        return `¥ ${maxPrice}`
      }
      
      // 如果两个价格都有值且不相等，显示价格范围
      if (price && maxPrice && price !== maxPrice) {
        const minPrice = Math.min(price, maxPrice)
        const maxPriceValue = Math.max(price, maxPrice)
        return `¥ ${minPrice} - ${maxPriceValue}`
      }
      
      // 如果两个价格相等，只显示一个
      return `¥ ${price || maxPrice}`
    },
  },
  created() {
    this.currentCategory = 0
  },
  onLoad(options) {
    
    // 接收订单数据
    if (options && options.orderData) {
      try {
        this.order = JSON.parse(decodeURIComponent(options.orderData))
        console.log('接收到的订单数据:', this.order)
        // 订单数据加载完成后初始化质检结果
        this.$nextTick(() => {
          this.initInspectResult()
        })
      } catch (error) {
        console.error('解析订单数据失败:', error)
      }
    }
    
    if (options && options.orderId) {
      this.orderId = options.orderId
    }
    
    // 初始化加载第一个分类的商品
    this.$nextTick(() => {
      // 确保categories已经计算完成
      if (this.categories.length > 0) {
        const firstCategoryId = this.categories[0]?.id
        console.log('第一个分类ID:', firstCategoryId, '所有分类:', this.categories.map(c => c.id))
        
        if (firstCategoryId && firstCategoryId !== 'unrecyclable' && firstCategoryId !== 'quality_issue') {
          this.fetchGoodsList(firstCategoryId, 1)
        } else if (firstCategoryId === 'unrecyclable' || firstCategoryId === 'quality_issue') {
          this.updateCurrentGoods()
        }
      } else {
        console.log('categories为空，等待数据加载')
        // 如果categories为空，等待一下再尝试
        setTimeout(() => {
          if (this.categories.length > 0) {
            const firstCategoryId = this.categories[0]?.id
            if (firstCategoryId && firstCategoryId !== 'unrecyclable' && firstCategoryId !== 'quality_issue') {
              this.fetchGoodsList(firstCategoryId, 1)
            } else if (firstCategoryId === 'unrecyclable' || firstCategoryId === 'quality_issue') {
              this.updateCurrentGoods()
            }
          }
        }, 500)
      }
    })
    
    console.log(this.orderId, 'orderId')
  },
  
  onShow() {
    // 确保在页面显示时categories已经正确计算
    console.log('onShow - categories:', this.categories.map(c => ({ id: c.id, title: c.title, badge: c.badge })))
    
    // 强制更新视图，确保所有分类都显示
    this.$nextTick(() => {
      console.log('分类导航应该显示的分类数量:', this.categories.length)
      this.categories.forEach((cat, index) => {
        console.log(`分类 ${index}: ${cat.title} (${cat.id})`)
      })
    })
  },

}
</script>

<style lang="scss" scoped>
.inspect-container {
  min-height: 100vh;
  background: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.nav-bar {
  display: flex;
  align-items: center;
  height: calc(150rpx + var(--status-bar-height));
  padding: 0 32rpx;
  padding-top: var(--status-bar-height);
  background: #fff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  box-sizing: border-box;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);

  .back {
    padding: 20rpx;
    margin-left: -20rpx;
  }

  .nav-title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: 500;
    color: #222;
  }

  .nav-icons {
    display: flex;
    align-items: center;
    gap: 12px;
  }
}

.main-content {
  margin-top: calc(200rpx + var(--status-bar-height));
  display: flex;
  background: none;
  height: calc(100vh - 200rpx - var(--status-bar-height));
  min-height: calc(100vh - 200rpx - var(--status-bar-height));
}

.category-nav {
  width: 160rpx;
  background: #fff;
  border-radius: 48rpx 0 0 48rpx;
  // padding: 48rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.03);
  height: calc(100vh - 200rpx - var(--status-bar-height) - 160rpx);
  max-height: calc(100vh - 200rpx - var(--status-bar-height) - 160rpx);
  overflow-y: scroll;
  overflow-x: hidden;
  position: relative;
  z-index: 2;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: thin;
  scrollbar-color: #ddd transparent;
  
  &::-webkit-scrollbar {
    width: 8rpx;
  }
  
  &::-webkit-scrollbar-track {
    background: transparent;
  }
  
  &::-webkit-scrollbar-thumb {
    background: #ddd;
    border-radius: 4rpx;
  }
  
  &::-webkit-scrollbar-thumb:hover {
    background: #ccc;
  }

  .category-item {
    width: 128rpx;
    height: 88rpx;
    border-radius: 32rpx 0 0 32rpx;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    font-size: 32rpx;
    color: #222;
    margin-bottom: 24rpx;
    background: #fff;
    position: relative;
    transition: background 0.2s, color 0.2s, font-weight 0.2s;
    padding-left: 24rpx;

    &.active {
      background: linear-gradient(90deg, #fff7e6 80%, #fff 100%);
      color: #ffb400;
      font-weight: bold;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 30%;
        height: 40%;
        width: 4rpx;
        border-radius: 8rpx;
        background: #ffb400;
        bottom: auto;
      }
    }

    .category-badge {
      position: absolute;
      top: 12rpx;
      right: 20rpx;
      background: #ff4d4f;
      color: #fff;
      font-size: 24rpx;
      border-radius: 50%;
      width: 36rpx;
      height: 36rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.goods-list {
  flex: 1;
  height: calc(100vh - 200rpx - var(--status-bar-height) - 160rpx);
  padding: 0 0 0 32rpx;
  overflow-y: auto;
  background: none;
}

.goods-card {
  background: #fff;
  border-radius: 48rpx;
  box-shadow: 0 8rpx 48rpx rgba(0, 0, 0, 0.06);
  margin-bottom: 36rpx;
  padding: 36rpx 36rpx 18rpx 36rpx;


}

.goods-header {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;

  .goods-img-container {
    position: relative;
    width: 112rpx;
    height: 112rpx;
    margin-right: 24rpx;
    flex-shrink: 0;
  }

  .goods-img {
    width: 100%;
    height: 100%;
    border-radius: 32rpx;
    background: #f8f8f8;
    object-fit: contain;
  }

  .brand-tag {
    position: absolute;
    top: 0rpx;
    left: 0rpx;
    background: rgba(0, 0, 0, 0.8);
    color: #fff;
    font-size: 20rpx;
    padding: 4rpx 8rpx;
    border-radius: 8rpx;
    z-index: 2;
  }

  .goods-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    min-width: 0;

    .goods-title-row {
      display: flex;
      align-items: baseline;
      justify-content: space-between;

      .goods-name {
        font-size: 28rpx;
        font-weight: bold;
        color: #222;
        margin-right: 16rpx;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .goods-price {
        font-size: 30rpx;
        color: #ffb400;
        font-weight: bold;
        white-space: nowrap;
        flex-shrink: 0;

        .goods-unit {
          font-size: 26rpx;
          color: #bbb;
        }
      }
    }

    .goods-desc {
      font-size: 26rpx;
      color: #999;
      margin-top: 8rpx;
    }
  }
}

.goods-row {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;

  .row-label {
    font-size: 28rpx;
    color: #888;
    width: 160rpx;
    flex-shrink: 0;
  }

  .num-ctrl {
    display: flex;
    align-items: center;

    .num-btn {
      width: 60rpx;
      height: 60rpx;
      padding: 0;
      margin: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      color: #666;
      background: #ffffff;
      border: none;
      border-radius: 50%;

      &::after {
        border: none;
      }

      &:active {
        opacity: 0.8;
      }
    }

    .num {
      width: 80rpx;
      text-align: center;
      font-size: 32rpx;
      color: #333;
    }
  }

  .amount-input {
    flex: 1;
    height: 64rpx;
    border-radius: 24rpx;
    background: #f6f6f6;
    border: none;
    font-size: 30rpx;
    color: #222;
    padding-left: 20rpx;
    margin-left: 16rpx;
  }
}

.footer-btns {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  display: flex;
  gap: 32rpx;
  padding: 24rpx 32rpx 48rpx 32rpx;
  z-index: 101;

  .btn-outline {
    flex: 1;
    height: 80rpx;
    border-radius: 32rpx;
    border: 2rpx solid #ffe09a;
    color: #ffb400;
    background: #fff0d2;
    font-size: 30rpx;
    font-weight: 500;
    box-shadow: none;
    padding: 0 36rpx;
  }

  .btn-main {
    flex: 1;
    height: 80rpx;
    border-radius: 32rpx;
    background: linear-gradient(90deg, #ffd01e 0%, #ffac04 100%);
    color: #fff;
    border: none;
    font-size: 30rpx;
    font-weight: 500;
    box-shadow: none;
    padding: 0 36rpx;
  }
}





.loading-more {
  text-align: center;
  color: #999;
  padding: 20rpx 0;
  font-size: 26rpx;
}

// 品牌款式显示样式
.selected-styles {
  margin-top: 8rpx;
  
  .style-item {
    margin-bottom: 4rpx;
    
    .style-text {
      font-size: 22rpx;
      color: #ff9c00;
      background: #fff7e6;
      padding: 2rpx 8rpx;
      border-radius: 8rpx;
      display: inline-block;
    }
  }
}


</style>




