<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>
      <!-- 右侧商品卡片区 -->
      <view class="goods-list">
        <view v-for="(item, idx) in currentGoods" :key="item.id" class="goods-card">
          <view class="goods-header">
            <image :src="item.image" class="goods-img" />
            <view class="goods-info">
              <view class="goods-title-row">
                <text class="goods-name">{{ item.name }}</text>
                <text class="goods-price">¥ {{ item.price }} <text class="goods-unit">/件</text></text>
              </view>
              <text class="goods-desc">{{ item.desc }}</text>
              <text v-if="item.brand" class="goods-brand">品牌：{{ item.brand }}</text>
              <text v-if="item.originalNum" class="goods-limit">总数量：{{ item.originalNum }}件</text>
            </view>
          </view>
          <view class="goods-row">
            <text class="row-label">合格数量</text>
            <view class="num-ctrl">
              <button class="num-btn" @tap="changeNum(item, 'qualified', -1)">-</button>
              <text class="num">{{ item.qualified }}</text>
              <button class="num-btn" @tap="changeNum(item, 'qualified', 1)">+</button>
            </view>
          </view>
          <view class="goods-row">
            <text class="row-label">不合格数量</text>
            <view class="num-ctrl">
              <button class="num-btn" @tap="changeNum(item, 'unqualified', -1)">-</button>
              <text class="num">{{ item.unqualified }}</text>
              <button class="num-btn" @tap="changeNum(item, 'unqualified', 1)">+</button>
            </view>
          </view>

          <view class="goods-row">
            <text class="row-label">总金额</text>
            <input class="amount-input" :value="getInspectPrice(item)" @input="updateInspectPrice(item, $event)" placeholder="请输入金额" />
          </view>
        </view>
      </view>
    </view>
    <!-- 底部操作按钮 -->
    <view class="footer-btns">
      <button class="btn-outline" @tap="goBack">返回订单详情</button>
      <button class="btn-main" @tap="goNext">下一步</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      statusBarHeight: 0,
      currentCategory: 0,
      orderId: '',
      order: null,  // 订单数据
      currentGoods: [], // 当前显示的商品列表
      inspectResult: {}, // 质检结果对象，按照新的数据格式
    }
  },
  computed: {
    categories() {
      const list = getApp().globalData.pricePreviewList || []
      let filteredCategories = []
      
      // 如果有订单数据，根据订单商品过滤分类
      if (this.order && this.order.commonOrderList) {
        // 获取订单中所有商品的分类ID（去重）
        const orderCategoryIds = new Set()
        this.order.commonOrderList.forEach(item => {
          // 如果有shopClass字段直接使用
          if (item.shopClass) {
            orderCategoryIds.add(item.shopClass)
          } else {
            // 如果没有shopClass，通过商品标题匹配分类
            const matchedCategory = list.find(cat => 
              cat.pid === '0' && item.title && item.title.includes(cat.title)
            )
            if (matchedCategory) {
              orderCategoryIds.add(matchedCategory.id)
            }
          }
        })
        
        // 过滤出订单中包含的分类
        filteredCategories = list.filter(item => 
          item.pid === '0' && orderCategoryIds.has(item.id)
        ).sort((a, b) => a.sort - b.sort)
        
        // 如果没有匹配到任何分类，显示所有分类
        if (filteredCategories.length === 0) {
          filteredCategories = list.filter(item => item.pid === '0').sort((a, b) => a.sort - b.sort)
        }
      } else {
        // 没有订单数据时显示所有分类
        filteredCategories = list.filter(item => item.pid === '0').sort((a, b) => a.sort - b.sort)
      }
      
      // 新增不可回收分类
      const extra = [{ id: 'unrecyclable', title: '不可回收' }]
      return [...filteredCategories, ...extra]
    }
  },
  methods: {
    initInspectResult() {
      if (!this.order || !this.order.commonOrderList) return
      
      this.inspectResult = {
        id: this.order.id,
        list: []
      }
      
      // 按照订单商品分组（按originalId分组）
      const groupedGoods = {}
      this.order.commonOrderList.forEach(item => {
        if (!groupedGoods[item.id]) {
          groupedGoods[item.id] = {
            id: item.id,
            price: '', // 初始为空字符串
            qualifiedNum: 0,
            noQualifiedNum: 0,
            unrecyclable: 0,
            commonOrderList: []
          }
        }
        console.log('groupedGoods', groupedGoods)
        // 为每个数量创建对应的质检项
        for (let i = 0; i < (item.num || 0); i++) {
          // console.log('groupedGoods[item.id]', groupedGoods[item.id])
          groupedGoods[item.id].commonOrderList.push({
            id: `${item.commonOrderList[i].id}`, // 生成唯一ID
            testingInstructions: '',
            testingImages: '',
            testingStatus: '' // 默认为空
          })
        }
      })
      
      // 添加不可回收分类 - 暂时注释掉
      // const totalOrderNum = this.order.commonOrderList.reduce((sum, item) => sum + (item.num || 0), 0)
      // groupedGoods['unrecyclable'] = {
      //   id: 'unrecyclable',
      //   price: '',
      //   qualifiedNum: 0,
      //   noQualifiedNum: 0,
      //   unrecyclable: totalOrderNum, // 初始化时全部为不可回收状态
      //   commonOrderList: []
      // }
      
      // // 为不可回收创建对应数量的质检项
      // for (let i = 0; i < totalOrderNum; i++) {
      //   groupedGoods['unrecyclable'].commonOrderList.push({
      //     id: `unrecyclable-${i}`,
      //     testingInstructions: '',
      //     testingImages: '',
      //     testingStatus: 2 // 不可回收状态
      //   })
      // }
      
      this.inspectResult.list = Object.values(groupedGoods)
    },
    updateCurrentGoods() {
      const currentCategoryId = this.categories[this.currentCategory]?.id
      const currentCategoryTitle = this.categories[this.currentCategory]?.title
      
      // 不可回收分类内容
      if (currentCategoryId === 'unrecyclable') {
        // 计算订单中所有商品的总数量作为不可回收的最大限制
        let totalOrderNum = 0
        if (this.order && this.order.commonOrderList) {
          totalOrderNum = this.order.commonOrderList.reduce((sum, item) => sum + (item.num || 0), 0)
        }
        
        this.currentGoods = [{
          id: 'unrecyclable-1',
          image: '/static/回收/衣物.png',
          name: '不可回收品类',
          price: '—',
          desc: '允许脏破烂，160码以上',
          qualified: 0,
          unqualified: 0,
          amount: '',
          originalNum: totalOrderNum // 设置最大数量为订单总数
        }]
        return
      }
      
      // 如果有订单数据，根据订单商品过滤当前分类的商品
      if (this.order && this.order.commonOrderList) {
        const orderGoods = this.order.commonOrderList.filter(item => {
          // 如果有shopClass字段，直接匹配
          if (item.shopClass) {
            return item.shopClass === currentCategoryId
          }
          // 如果没有shopClass，通过商品标题匹配分类
          return item.title && currentCategoryTitle && item.title.includes(currentCategoryTitle)
        })
        
        // 根据pinName展示不同品牌的商品，不进行去重
        const goodsList = orderGoods.map((item, index) => ({
          id: `${item.id}`, 
          image: item.image || '/static/回收/衣物.png',
          name: item.title,
          brand: item.pinName || '未知品牌',
          price: item.onePrice || 0,
          desc: item.details || '',
          qualified: 0,
          unqualified: 0,
          amount: '',
          originalNum: item.num || 0,
          estimatedPrice: item.price || 0,
          originalId: item.id // 保存原始ID
        }))
        
        this.currentGoods = goodsList
        return
      }
      
      // 没有订单数据时返回空数组
      this.currentGoods = []
    },

    goBack() {
      uni.navigateBack()
    },
    goNext() {
      // 检测是否所有商品都已完成质检和填写价格
      const validationResult = this.validateInspectData()
      if (!validationResult.isValid) {
        uni.showToast({
          title: validationResult.message,
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      // 构造传递给步骤二的完整数据
      const resultData = {
        inspectResult: this.inspectResult,
        order: this.order // 同时传递订单信息
      }
      
      const resultDataStr = encodeURIComponent(JSON.stringify(resultData))
      uni.navigateTo({
        url: `/pages/manager/inspect-result?resultData=${resultDataStr}`
      })
    },
    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') {
          continue
        }
        
        // 获取商品信息用于显示错误消息
        const orderItem = this.order.commonOrderList.find(orderGoods => orderGoods.id == item.id)
        const brandName = orderItem ? (orderItem.title+' '+orderItem.pinName || orderItem.title || '未知商品') : '未知商品'
        
        // 检查是否有空的testingStatus
        const hasEmptyStatus = item.commonOrderList.some(commonItem => 
          commonItem.testingStatus === '' || commonItem.testingStatus === null || commonItem.testingStatus === undefined
        )
        
        if (hasEmptyStatus) {
          return {
            isValid: false,
            message: `${brandName} 还未完成质检选择`
          }
        }
        
        // 检查价格是否为空
        if (!item.price || item.price === 0 || item.price === '') {
          return {
            isValid: false,
            message: `${brandName} 还未填写总金额`
          }
        }
      }
      
      return {
        isValid: true,
        message: ''
      }
    },
    switchCategory(idx) {
      this.currentCategory = idx
      this.updateCurrentGoods()
    },
    changeNum(item, key, delta) {
      const currentQualified = item.qualified || 0
      const currentUnqualified = item.unqualified || 0
      const maxNum = item.originalNum || 0
      
      if (key === 'qualified') {
        const newQualified = Math.max(0, currentQualified + delta)
        const totalAfterChange = newQualified + currentUnqualified
        
        // 检查总数是否超过原始数量
        if (totalAfterChange <= maxNum) {
          this.$set(item, 'qualified', newQualified)
          // 更新inspectResult对象
          this.updateInspectResult(item, 'qualified', delta)
          console.log('更新后的inspectResult:', JSON.stringify(this.inspectResult, null, 2))
        } else {
          uni.showToast({
            title: `总数不能超过${maxNum}件`,
            icon: 'none',
            duration: 1500
          })
        }
      } else if (key === 'unqualified') {
        const newUnqualified = Math.max(0, currentUnqualified + delta)
        const totalAfterChange = currentQualified + newUnqualified
        
        // 检查总数是否超过原始数量
        if (totalAfterChange <= maxNum) {
          this.$set(item, 'unqualified', newUnqualified)
          // 更新inspectResult对象
          this.updateInspectResult(item, 'unqualified', delta)
        } else {
          uni.showToast({
            title: `总数不能超过${maxNum}件`,
            icon: 'none',
            duration: 1500
          })
        }
      }
    },
    updateInspectResult(item, type, delta) {
      // 处理不可回收分类 - 暂时注释掉
      // if (item.id === 'unrecyclable-1') {
      //   const unrecyclableItem = this.inspectResult.list.find(listItem => listItem.id === 'unrecyclable')
      //   if (!unrecyclableItem) return
        
      //   if (type === 'qualified' && delta > 0) {
      //     // 增加合格数量：找到第一个不可回收状态的项改为合格
      //     const targetItem = unrecyclableItem.commonOrderList.find(commonItem => commonItem.testingStatus === 2)
      //     if (targetItem) {
      //       targetItem.testingStatus = 0
      //       unrecyclableItem.unrecyclable--
      //       unrecyclableItem.qualifiedNum++
      //     }
      //   } else if (type === 'qualified' && delta < 0) {
      //     // 减少合格数量：找到第一个合格状态的项改为不可回收
      //     const targetItem = unrecyclableItem.commonOrderList.find(commonItem => commonItem.testingStatus === 0)
      //     if (targetItem) {
      //       targetItem.testingStatus = 2
      //       unrecyclableItem.qualifiedNum--
      //       unrecyclableItem.unrecyclable++
      //     }
      //   } else if (type === 'unqualified' && delta > 0) {
      //     // 增加不合格数量：找到第一个不可回收状态的项改为质量问题
      //     const targetItem = unrecyclableItem.commonOrderList.find(commonItem => commonItem.testingStatus === 2)
      //     if (targetItem) {
      //       targetItem.testingStatus = 1
      //       unrecyclableItem.unrecyclable--
      //       unrecyclableItem.noQualifiedNum++
      //     }
      //   } else if (type === 'unqualified' && delta < 0) {
      //     // 减少不合格数量：找到第一个质量问题状态的项改为不可回收
      //     const targetItem = unrecyclableItem.commonOrderList.find(commonItem => commonItem.testingStatus === 1)
      //     if (targetItem) {
      //       targetItem.testingStatus = 2
      //       unrecyclableItem.noQualifiedNum--
      //       unrecyclableItem.unrecyclable++
      //     }
      //   }
        
      //   console.log('更新后的不可回收inspectResult:', JSON.stringify(unrecyclableItem, null, 2))
      //   return
      // }
      
      // 找到对应的inspectResult项
      const originalId = item.originalId || item.id.split('-')[0]
      const inspectItem = this.inspectResult.list.find(listItem => listItem.id == originalId)
      
      if (!inspectItem) return
      
      if (type === 'qualified' && delta > 0) {
        // 增加合格数量：优先找空状态的项，其次找非合格状态的项
        let targetItem = inspectItem.commonOrderList.find(commonItem => commonItem.testingStatus === '')
        if (!targetItem) {
          targetItem = inspectItem.commonOrderList.find(commonItem => 
            commonItem.testingStatus === 1 || commonItem.testingStatus === 2
          )
        }
        if (targetItem) {
          const oldStatus = targetItem.testingStatus
          targetItem.testingStatus = 0
          inspectItem.qualifiedNum++
          if (oldStatus === 1) {
            inspectItem.noQualifiedNum--
          } else if (oldStatus === 2) {
            inspectItem.unrecyclable--
          }
        }
      } else if (type === 'qualified' && delta < 0) {
        // 减少合格数量：找到第一个合格状态的项改为空状态
        const targetItem = inspectItem.commonOrderList.find(commonItem => commonItem.testingStatus === 0)
        if (targetItem) {
          targetItem.testingStatus = ''
          inspectItem.qualifiedNum--
        }
      } else if (type === 'unqualified' && delta > 0) {
        // 增加不合格数量：优先找空状态的项，其次找合格状态的项
        let targetItem = inspectItem.commonOrderList.find(commonItem => commonItem.testingStatus === '')
        if (!targetItem) {
          targetItem = inspectItem.commonOrderList.find(commonItem => commonItem.testingStatus === 0)
        }
        if (targetItem) {
          const oldStatus = targetItem.testingStatus
          targetItem.testingStatus = 1
          inspectItem.noQualifiedNum++
          if (oldStatus === 0) {
            inspectItem.qualifiedNum--
          }
        }
      } else if (type === 'unqualified' && delta < 0) {
        // 减少不合格数量：找到第一个质量问题状态的项改为空状态
        const targetItem = inspectItem.commonOrderList.find(commonItem => commonItem.testingStatus === 1)
        if (targetItem) {
          targetItem.testingStatus = ''
          inspectItem.noQualifiedNum--
        }
      }
      
      console.log('更新后的inspectResult:', JSON.stringify(this.inspectResult, null, 2))
    },
    getInspectPrice(item) {
      // 获取inspectResult中对应商品的price
      if (item.id === 'unrecyclable-1') {
        return ''
      }
      
      const originalId = item.originalId || item.id.split('-')[0]
      const inspectItem = this.inspectResult.list?.find(listItem => listItem.id == originalId)
      return inspectItem ? inspectItem.price : ''
    },
    updateInspectPrice(item, event) {
      // 更新inspectResult中对应商品的price
      if (item.id === 'unrecyclable-1') {
        return
      }
      
      const originalId = item.originalId || item.id.split('-')[0]
      const inspectItem = this.inspectResult.list?.find(listItem => listItem.id == originalId)
      
      if (inspectItem) {
        const newPrice = parseFloat(event.detail.value) || 0
        inspectItem.price = newPrice
        console.log('更新价格:', originalId, newPrice)
      }
    },
  },
  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()
          this.updateCurrentGoods()
        })
      } catch (error) {
        console.error('解析订单数据失败:', error)
      }
    }
    
    if (options && options.orderId) {
      this.orderId = options.orderId
    }
    
    console.log(this.orderId, 'orderId')
  },

}
</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;
}

.category-nav {
  width: 80px;
  background: #fff;
  border-radius: 24px 0 0 24px;
  padding: 24px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  height: 100%;
  overflow-y: auto;
  position: relative;
  z-index: 2;

  .category-item {
    width: 64px;
    height: 44px;
    border-radius: 16px 0 0 16px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    font-size: 16px;
    color: #222;
    margin-bottom: 12px;
    background: #fff;
    position: relative;
    transition: background 0.2s, color 0.2s, font-weight 0.2s;
    padding-left: 12px;

    &.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: 2px;
        border-radius: 4px;
        background: #ffb400;
        bottom: auto;
      }
    }

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

.goods-list {
  flex: 1;
  height: calc(100vh - 110rpx - var(--status-bar-height) - 80px);
  padding: 0 0 0 16px;
  overflow-y: auto;
  background: none;
}

.goods-card {
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06);
  margin-bottom: 18px;
  padding: 18px 18px 9px 18px;


}

.goods-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;

  .goods-img {
    width: 56px;
    height: 56px;
    border-radius: 16px;
    margin-right: 12px;
    background: #f8f8f8;
    object-fit: contain;
  }

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

    .goods-title-row {
      display: flex;
      align-items: baseline;

      .goods-name {
        font-size: 16px;
        font-weight: bold;
        color: #222;
        margin-right: 8px;
      }

      .goods-price {
        font-size: 15px;
        color: #ffb400;
        font-weight: bold;

        .goods-unit {
          font-size: 13px;
          color: #bbb;
        }
      }
    }

    .goods-desc {
      font-size: 13px;
      color: #999;
      margin-top: 4px;
    }
  }
}

.goods-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;

  .row-label {
    font-size: 14px;
    color: #888;
    width: 80px;
    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: 32px;
    border-radius: 12px;
    background: #f6f6f6;
    border: none;
    font-size: 15px;
    color: #222;
    padding-left: 10px;
    margin-left: 8px;
  }
}

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

  .btn-outline {
    flex: 1;
    height: 40px;
    border-radius: 16px;
    border: 1px solid #ffe09a;
    color: #ffb400;
    background: #fff0d2;
    font-size: 15px;
    font-weight: 500;
    box-shadow: none;
    padding: 0 18px;
  }

  .btn-main {
    flex: 1;
    height: 40px;
    border-radius: 16px;
    background: linear-gradient(90deg, #ffd01e 0%, #ffac04 100%);
    color: #fff;
    border: none;
    font-size: 15px;
    font-weight: 500;
    box-shadow: none;
    padding: 0 18px;
  }
}



.goods-brand {
  font-size: 12px;
  color: #ffb400;
  margin-top: 2px;
  font-weight: 500;
}

.goods-limit {
  font-size: 12px;
  color: #ffb400;
  margin-top: 2px;
  font-weight: 500;
}


</style>

