<template>
  <view class="inspect-result-container" :class="{ 'popup-open': isPopupOpen }">
    <!-- 顶部导航栏 -->
    <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="more" size="24" color="#222" />
      </view>
    </view>
    <view class="main-content">
      <!-- 合格产品卡片 -->
      <view v-if="hasQualifiedItems" class="result-card">
        <view class="card-title">合格产品</view>
        <view v-for="(item, index) in qualifiedList" :key="item.uniqueKey || index" class="result-group">
          <view class="row-main">
            <view class="goods-name-section">
              <text class="goods-name">{{ getGoodsName(item.shopId) }}</text>
              <text class="goods-brand">{{ getBrandStyleInfo(item) }}</text>
              <text class="goods-style-price" v-if="getStylePriceInfo(item)">{{ getStylePriceInfo(item) }}</text>
            </view>
            <text class="row-count">x{{ item.count }}</text>
          </view>
          <view class="price-input-row">
            <text class="price-label">总金额</text>
            <input class="price-input" v-model="item.total" type="digit" placeholder="请输入金额" />
          </view>

          <!-- 选择理由模块 -->
          <view v-if="item.items && item.items.length > 0">
            <view v-for="(commonItem, itemIndex) in item.items" :key="commonItem.id || itemIndex" class="row-reason">
              <text class="reason-label">{{ getQualifiedItemLabel(item, itemIndex) }}</text>
              <view class="reason-select" @click="selectReasonForQualified(commonItem, item)">
                <text class="reason-placeholder" :class="{ 'selected': hasSelectedReason(commonItem) }">
                  {{ hasSelectedReason(commonItem) ? '已选择' : '请选择理由（选填）' }}
                </text>
                <uni-icons type="right" size="18" color="#bbb" />
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 不合格产品卡片 -->
      <view v-if="hasUnqualifiedItems" class="result-card">
        <view class="card-title">不合格产品</view>
        <view v-for="group in unqualifiedGroups" :key="group.shopId" class="result-group">
          <view class="row-main">
            <view class="goods-name-section">
              <text class="goods-name">质量问题</text>
              <text class="goods-brand"></text>
            </view>
            <text class="row-count">x{{ group.count }}</text>
          </view>
          <view class="price-input-row">
            <text class="price-label">总金额</text>
            <input class="price-input" v-model="group.total" type="digit" placeholder="请输入金额" />
          </view>
          <!-- 选择理由模块 -->
          <view v-if="inspectData && inspectData.list">
            <view v-for="(item, index) in (inspectData.list.find(i => i.id === 'quality_issue')?.commonOrderList || [])"
              :key="item.id || item.testingStatus" class="row-reason">
              <text class="reason-label">质量问题{{ index + 1 }}</text>
              <view class="reason-select" @click="selectReason(item)">
                <text class="reason-placeholder" :class="{ 'selected': hasSelectedReason(item) }">
                  {{ hasSelectedReason(item) ? '已选择' : '请选择理由' }}
                </text>
                <uni-icons type="right" size="18" color="#bbb" />
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 不可回收产品卡片 -->
      <view v-if="hasUnrecyclableItems" class="result-card">
        <view class="card-title">不可回收产品</view>
        <view v-for="item in unrecyclableList" :key="item.id" class="result-group">
          <view class="row-main">
            <view class="goods-name-section">
              <text class="goods-name">不可回收</text>
              <text class="goods-brand"></text>
            </view>
            <text class="row-count">x{{ item.count }}</text>
          </view>
          <view class="price-input-row">
            <text class="price-label">总金额</text>
            <input class="price-input" v-model="item.total" type="digit" placeholder="请输入金额" />
          </view>
          <!-- 选择理由模块 -->
          <view v-if="inspectData && inspectData.list">
            <view v-for="(commonItem,index) in (inspectData.list.find(i => i.id === 'unrecyclable')?.commonOrderList || [])"
              :key="commonItem.id || commonItem.testingStatus" class="row-reason">
              <text class="reason-label">不可回收{{ index +1 }}</text>
              <view class="reason-select" @click="selectReason(commonItem)">
                <text class="reason-placeholder" :class="{ 'selected': hasSelectedReason(commonItem) }">
                  {{ hasSelectedReason(commonItem) ? '已选择' : '请选择理由' }}
              </text>
              <uni-icons type="right" size="18" color="#bbb" />
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 回收信息卡片 -->
      <view class="result-card info-card">
        <view class="card-title-row">
          <text class="card-title">回收信息</text>
          <view class="status-tag">待质检</view>
        </view>
        <view class="info-row">
          <text class="info-label">订单编号</text>
          <text class="info-value copy-btn"
		    @click="$utils.copyText(order?.ordeNo)"
		    >{{ order?.ordeNo }} 复制</text>
        </view>
        <view class="info-row">
          <text class="info-label">取件时间</text>
          <text class="info-value">{{ order?.goTime || '2025-03-20 11:00' }}</text>
        </view>
      </view>
    </view>
    <!-- 底部操作按钮 -->
    <view class="footer-btns">
      <button class="btn-outline" @tap="goPrev">上一步</button>
      <button class="btn-main" @tap="finishInspect">完成质检</button>
    </view>
    <!-- 理由弹窗 -->
    <uni-popup ref="reasonPopup" type="bottom" :mask-click="false" :safe-area="false" class="reason-popup-wrapper">
      <view class="reason-popup">
        <view class="popup-header">
          <text class="popup-close" @tap="closeReasonPopup">关闭</text>
          <text class="popup-title">{{ currentReasonTitle }}</text>
        </view>
        <scroll-view class="popup-content" scroll-y="true">
          <view class="popup-section">
            <text class="section-label">上传图片</text>
            <view class="img-list">
              <view class="img-item add" @tap="addReasonImg">
                <uni-icons type="plusempty" size="32" color="#bbb" />
              </view>
              <view v-for="(img, idx) in reasonImages" :key="idx" class="img-item">
                <image :src="img" class="img" />
                <view class="img-del" @tap="removeReasonImg(idx)">×</view>
              </view>
            </view>
          </view>
          <view class="popup-section">
            <text class="section-label">自定义理由</text>
            <textarea class="custom-reason-input" v-model="customReason" placeholder="请输入自定义理由..." maxlength="200" />
          </view>
          <view class="popup-section">
            <text class="section-label">质检级别</text>
            <view class="level-options">
              <view v-for="level in ['S', 'A', 'B', 'C']" :key="level" 
                    :class="['level-option', { 'selected': currentQualityLevel === level }]"
                    @tap="selectQualityLevel(level)">
                <text class="level-text">{{ level }}</text>
              </view>
            </view>
          </view>
          <view class="popup-section">
            <text class="section-label">选择理由</text>
            <view v-for="(item, index) in reasonOptions" :key="item.id" class="reason-row" @tap="toggleReason(index)">
              <view :class="['checkbox', { checked: reasonChecked.includes(item.reason) }]" />
              <text class="reason-text">{{ item.reason }}</text>
            </view>
          </view>
        </scroll-view>
        <button class="popup-save-btn" @tap="saveReason">保存</button>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import pullRefreshMixin from '../mixins/pullRefreshMixin.js'
import OSS from '@/utils/oss-upload/oss/index.js'

export default {
  mixins: [pullRefreshMixin],
  data() {
    return {
      inspectData: null, // 从步骤一传过来的质检数据
      order: null, // 订单数据
      qualifiedList: [],
      unqualifiedGroups: [],
      unrecyclableList: [],
      goodsNameMap: {}, // 商品id => 名称
      reasonPopupVisible: false,
      currentReasonTitle: '',
      reasonImages: [],
      reasonOptions: [],
      reasonChecked: [],
      customReason: '', // 自定义理由输入
      currentReasonItem: null,
      currentQualityLevel: '', // 当前选择的质检级别
      isPopupOpen: false, // 控制弹窗状态
      scrollTop: 0 // 记录滚动位置
    }
  },
  computed: {
    hasQualifiedItems() {
      return this.qualifiedList && this.qualifiedList.length > 0
    },
    hasUnqualifiedItems() {
      return this.unqualifiedGroups && this.unqualifiedGroups.length > 0
    },
    hasUnrecyclableItems() {
      return this.unrecyclableList && this.unrecyclableList.length > 0
    }
  },
  onLoad(options) {
    // 接收质检数据和订单数据
    if (options && options.resultData) {
      try {
        const resultData = JSON.parse(decodeURIComponent(options.resultData))
        this.inspectData = resultData.inspectResult
        this.order = resultData.order
        this.processInspectData()
      } catch (error) {
        console.error('解析数据失败:', error)
      }
    }
    if (options && options.inspectData && !options.resultData) {
      try {
        this.inspectData = JSON.parse(decodeURIComponent(options.inspectData))
        this.processInspectData()
      } catch (error) {
        console.error('解析质检数据失败:', error)
      }
    }
  },
  methods: {
    async processInspectData() {
      if (!this.inspectData || !this.inspectData["list"]) return
      this.qualifiedList = []
      this.unqualifiedGroups = []
      this.unrecyclableList = []
      // 只收集普通商品的 shopId 作为 goodsId
      const allIds = []
      this.inspectData["list"].forEach(item => {
        if (item.shopId && item.id !== 'unrecyclable' && item.id !== 'quality_issue') {
          allIds.push(item.shopId)
        }
      })
      console.log('allIds', allIds)
      const uniqueIds = Array.from(new Set(allIds.filter(Boolean)))
      console.log('uniqueIds', uniqueIds)
      await this.fetchGoodsNames(uniqueIds)
      // 合格商品 - 按照商品、品牌、款式作为唯一标识生成独立数据
      this.inspectData["list"].forEach(item => {
        if (item.qualifiedNum > 0 && item.id !== 'unrecyclable' && item.id !== 'quality_issue') {
          // 为每个品牌款式组合创建独立的条目
          const uniqueKey = item.uniqueKey || `${item.shopId}_${item.pinId || 'no-brand'}_${item.styleId || 'no-style'}`
          
          this.qualifiedList.push({
            shopId: item.shopId,
            count: item.qualifiedNum,
            total: item.price || 0,
            classId: item.categoryId,
            brandName: item.brandName || '',
            styleName: item.styleName || '',
            pinId: item.pinId || '',
            styleId: item.styleId || '',
            uniqueKey: uniqueKey,
            qualityLevel: item.qualityLevel || '', // 质检级别
            // 添加款式价格信息
            styleMinPrice: item.styleMinPrice || 0,
            styleMaxPrice: item.styleMaxPrice || 0,
            // 添加商品本身的价格信息
            productMinPrice: item.productMinPrice || 0,
            productMaxPrice: item.productMaxPrice || 0,
            originalItem: item, // 保存原始数据引用
            items: item.commonOrderList ? [...item.commonOrderList] : [{
              testingInstructions: '',
              testingImages: '',
              testingStatus: 0
            }]
          })
          console.log('qualifiedList', this.qualifiedList)
        }
      })
      // 不合格商品（只展示质量问题）
      this.inspectData["list"].forEach(item => {
        if (item.id === 'quality_issue' && item.noQualifiedNum > 0) {
          this.unqualifiedGroups.push({
            shopId: item.id,
            count: item.noQualifiedNum,
            total: item.price,
            items: item.commonOrderList ? [...item.commonOrderList] : []
          })
        }
      })
      // 不可回收商品
      this.inspectData["list"].forEach(item => {
        if (item.id === 'unrecyclable' && item.unrecyclable > 0) {
          this.unrecyclableList.push({
            id: item.id,
            count: item.unrecyclable,
            total: item.price,
            items: item.commonOrderList ? [...item.commonOrderList] : []
          })
        }
      })
    },
    async fetchGoodsNames(ids) {
      // 批量获取商品名称
      const nameMap = {}
      for (const id of ids) {
        try {
          const res = await this.$api('getGoodsDetail', { goodsId: id })
          if (res && res.code === 200 && res.result) {
            nameMap[id] = res.result.name
          }
        } catch (e) {
          nameMap[id] = '未知商品'
        }
      }
      this.goodsNameMap = nameMap
    },
    getGoodsName(id) {
      return this.goodsNameMap[id] || '未知商品'
    },
    goBack() {
      uni.navigateBack()
    },
    goPrev() {
      uni.navigateBack()
    },
    finishInspect() {
      // 校验金额必填性
      // 检查合格产品金额
      for (const item of this.qualifiedList) {
        if (!item.total || item.total === '' || parseFloat(item.total) <= 0) {
          uni.showToast({ title: '请填写合格产品金额', icon: 'none' })
          return
        }
      }
      // 检查不合格产品金额
      // for (const group of this.unqualifiedGroups) {
      //   if (!group.total || group.total === '' || parseFloat(group.total) <= 0) {
      //     uni.showToast({ title: '请填写不合格产品金额', icon: 'none' })
      //     return
      //   }
      // }
      // // 检查不可回收产品金额
      // for (const item of this.unrecyclableList) {
      //   if (!item.total || item.total === '' || parseFloat(item.total) <= 0) {
      //     uni.showToast({ title: '请填写不可回收产品金额', icon: 'none' })
      //     return
      //   }
      // }
      
      // 校验理由必填性
      // 1. 合格产品理由可选填
      // 2. 质量问题和不可回收理由必填
      // 检查质量问题
      const qualityItem = this.inspectData["list"].find(item => item.id === 'quality_issue')
      if (qualityItem && qualityItem.noQualifiedNum > 0) {
        const hasReason = qualityItem.commonOrderList && qualityItem.commonOrderList.some(c => {
          // 只要填写了理由或图片即可
          return (c.testingInstructions && c.testingInstructions.trim() !== '') ||
            (c.testingImages && c.testingImages.trim() !== '')
        })
        if (!hasReason) {
          uni.showToast({ title: '质量问题理由必填', icon: 'none' })
          return
        }
      }
      // 检查不可回收
      const unrecyclableItem = this.inspectData["list"].find(item => item.id === 'unrecyclable')
      if (unrecyclableItem && unrecyclableItem.unrecyclable > 0) {
        const hasReason = unrecyclableItem.commonOrderList && unrecyclableItem.commonOrderList.some(c => {
          return (c.testingInstructions && c.testingInstructions.trim() !== '') ||
            (c.testingImages && c.testingImages.trim() !== '')
        })
        if (!hasReason) {
          uni.showToast({ title: '不可回收理由必填', icon: 'none' })
          return
        }
      }
      // 同步用户输入的金额到inspectData
      this.syncPriceToInspectData()
      
      // 在提交前将质量问题和不可回收中的id值置为空
      const processedList = this.inspectData["list"].map(item => {
        if (item.id === 'quality_issue' || item.id === 'unrecyclable') {
          // 对于质量问题和不可回收，将id置为空
          return { ...item, id: '' }
        }
        return item
      })
      
      const inspectDatas = {...this.inspectData, list: JSON.stringify(processedList, null, 2)}
      console.log('最终的质检数据:', inspectDatas);
      this.$api('submitQualityInfo',  inspectDatas , res => {
        if (res && res.code === 200) {
          uni.showToast({ title: '质检完成', icon: 'success' })
          uni.reLaunch({ url: '/pages/component/home' })
        }
      })
      uni.showToast({ title: '完成质检', icon: 'success' })
    },
    selectReason(item) {
      // 直接使用传入的item，因为它已经是commonOrderList中的具体项
      let popupItem = item
      let type = 0 // 默认类型
      
      // 根据testingStatus确定类型
      if (item.testingStatus === 1) {
        type = 1 // 质量问题
      } else if (item.testingStatus === 2) {
        type = 2 // 不可回收
      }
      
      this.currentReasonItem = popupItem
      // 判断类型，动态设置标题
      if (popupItem.testingStatus === 1) {
        this.currentReasonTitle = '质量问题'
      } else if (popupItem.testingStatus === 2) {
        this.currentReasonTitle = '不可回收'
      } else {
        this.currentReasonTitle = this.getGoodsName(popupItem.shopId || popupItem.id)
      }
      // 只使用testingImages字段
      if (popupItem.testingImages && popupItem.testingImages.trim() !== '') {
        this.reasonImages = popupItem.testingImages.split(',').filter(img => img.trim() !== '')
      } else {
        this.reasonImages = []
      }
      // 初始化质检级别
      this.currentQualityLevel = popupItem.qualityLevel || ''
      // 不在这里设置reasonChecked
      this.selectReasonForUnqualified(popupItem, type)
      this.lockScroll()
      this.$refs.reasonPopup.open()
    },
    selectReasonForQualified(commonItem, parentItem) {
      this.currentReasonItem = commonItem
      this.currentReasonTitle = this.getGoodsName(parentItem.shopId || parentItem.id)
      // 只使用testingImages字段
      if (commonItem.testingImages && commonItem.testingImages.trim() !== '') {
        this.reasonImages = commonItem.testingImages.split(',').filter(img => img.trim() !== '')
      } else {
        this.reasonImages = []
      }
      // 初始化质检级别
      this.currentQualityLevel = commonItem.qualityLevel || ''
      // 使用从上一个页面传过来的categoryId
      this.selectReasonForUnqualified(commonItem, 0, parentItem.classId)
      this.lockScroll()
      this.$refs.reasonPopup.open()
    },

    selectReasonForUnqualified(item, type, classId = '') {
      console.log(item)
      // 根据类型确定classId
      if (!classId) {
        if (type === 1) {
          // 质量问题
          classId = ''
        } else if (type === 2) {
          // 不可回收
          classId = ''
        } else {
          // classId
          classId = item.classId || ''
        }
      }
      
      console.log('[selectReasonForUnqualified] classId:', classId, 'type:', type)
      
      this.$api('getcheckoutReasons', {
        classId: classId,
        type: type
      }, res => {
        if (res.code == 200) {
          this.reasonOptions = res.result;
          if (item.testingInstructions && item.testingInstructions.trim() !== '') {
            const instructions = item.testingInstructions.split(',').map(s => s.trim()).filter(Boolean)
            // 分离预设理由和自定义理由
            this.reasonChecked = []
            this.customReason = ''
            
            instructions.forEach(instruction => {
              const foundOption = this.reasonOptions.find(option => option.reason === instruction)
              if (foundOption) {
                this.reasonChecked.push(instruction)
              } else {
                // 如果不在预设选项中，认为是自定义理由
                this.customReason = this.customReason ? `${this.customReason},${instruction}` : instruction
              }
            })
          } else {
            this.reasonChecked = []
            this.customReason = ''
          }
          this.$nextTick(() => {
            this.reasonChecked = [...this.reasonChecked]
            console.log('[selectReasonForUnqualified] reasonOptions:', this.reasonOptions)
            console.log('[selectReasonForUnqualified] reasonChecked:', this.reasonChecked)
            console.log('[selectReasonForUnqualified] customReason:', this.customReason)
          })
        } else {
          console.error('[selectReasonForUnqualified] API返回错误:', res)
          uni.showToast({
            title: '获取理由列表失败',
            icon: 'none'
          })
        }
      }, err => {
        console.error('[selectReasonForUnqualified] API调用失败:', err)
        uni.showToast({
          title: '获取理由列表失败',
          icon: 'none'
        })
      })
    },
    closeReasonPopup() {
      this.unlockScroll()
      this.$refs.reasonPopup.close()
    },
    addReasonImg() {
      // 检查是否已达到最大数量限制
      if (this.reasonImages.length >= 9) {
        uni.showToast({
          title: '最多只能上传9张图片',
          icon: 'none'
        })
        return
      }

      uni.chooseMedia({
        count: 3 - this.reasonImages.length, // 剩余可选择数量
        mediaType: ['image'], // 只选择图片
        sourceType: ['camera'], // 直接使用相机拍照
        maxDuration: 30,
        sizeType: [ 'compressed'],
        camera: 'back',
        success: (res) => {
          console.log('选择的图片:', res.tempFiles)

          // 显示上传进度
          uni.showLoading({
            title: '上传中...'
          })

          // 处理选择的图片
          const uploadPromises = res.tempFiles.map(file => {
            return this.uploadImageToOSS(file.tempFilePath)
          })

          // 批量上传
          Promise.all(uploadPromises).then(urls => {
            this.reasonImages = this.reasonImages.concat(urls)
            uni.hideLoading()
            uni.showToast({
              title: '上传成功',
              icon: 'success'
            })
          }).catch(error => {
            console.error('上传失败:', error)
            uni.hideLoading()
            uni.showToast({
              title: '上传失败，请重试',
              icon: 'none'
            })
          })
        },
        fail: (error) => {
          console.error('选择图片失败:', error)
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          })
        }
      })
    },
    async uploadImageToOSS(filePath) {
      try {
        // 使用项目中的OSS上传工具
        const url = await OSS.ossUpload(filePath)
        return url
      } catch (error) {
        console.error('OSS上传失败:', error)
        throw error
      }
    },
    removeReasonImg(idx) {
      this.reasonImages.splice(idx, 1)
    },
    toggleReason(idx) {
      const val = this.reasonOptions[idx].reason.toString()
      const i = this.reasonChecked.indexOf(val)
      if (i > -1) {
        this.reasonChecked.splice(i, 1)
      } else {
        this.reasonChecked.push(val)
      }
      this.reasonChecked = [...this.reasonChecked]
      console.log('[toggleReason] reasonChecked:', this.reasonChecked)
    },
    saveReason() {
      if (this.currentReasonItem) {
        console.log('this.currentReasonItem', this.currentReasonItem)
        // 合并选择的理由和自定义理由
        const allReasons = [...this.reasonChecked]
        if (this.customReason && this.customReason.trim() !== '') {
          allReasons.push(this.customReason.trim())
        }
        // 直接更新当前项
        this.currentReasonItem.testingInstructions = allReasons.join(',')
        this.currentReasonItem.testingImages = this.reasonImages.join(',')
        this.currentReasonItem.qualityLevel = this.currentQualityLevel
      }
      this.closeReasonPopup()
    },


    lockScroll() {
      // 获取当前页面滚动位置
      uni.createSelectorQuery().selectViewport().scrollOffset((res) => {
        this.scrollTop = res.scrollTop
      }).exec()
      // 禁用页面滚动
      this.isPopupOpen = true
    },
    unlockScroll() {
      // 恢复页面滚动
      this.isPopupOpen = false
      // 恢复滚动位置
      this.$nextTick(() => {
        if (this.scrollTop > 0) {
          uni.pageScrollTo({
            scrollTop: this.scrollTop,
            duration: 0
          })
        }
      })
    },
    async onRefresh() {
      await this.refreshData && this.refreshData()
    },
    refreshData() {
      // 可根据实际需求刷新质检结果数据
      // 例如重新请求接口或重置数据
    },
    getItemBrand(id) {
      if (this.order && this.order.commonOrderList) {
        const orderItem = this.order.commonOrderList.find(item => item.id == id)
        return orderItem ? (orderItem.pinName || '') : ''
      }
      return ''
    },
    parseTestingInstructions() {
      return []
    },
    hasSelectedReason(item) {
      // console.log('item', item)
      // 检查该商品是否已选择理由或上传图片
      return (item.testingInstructions && item.testingInstructions.trim() !== '') ||
             (item.testingImages && item.testingImages.trim() !== '')
    },
    
    getBrandStyleInfo(item) {
      // 获取品牌款式信息
      const brandName = item.brandName || ''
      const styleName = item.styleName || ''
      
      if (brandName && styleName) {
        return `品牌：${brandName} | 款式：${styleName}`
      } else if (brandName) {
        return `品牌：${brandName}`
      } else if (styleName) {
        return `款式：${styleName}`
      } else {
        return this.getItemBrand(item.shopId)
      }
    },
    
    getQualifiedItemLabel(item, index) {
      // 生成合格产品的标签
      const goodsName = this.getGoodsName(item.shopId)
      const brandName = item.brandName || ''
      const styleName = item.styleName || ''
      
      if (brandName && styleName) {
        return `(${brandName}-${styleName})`
      } else if (brandName) {
        return `(${brandName})`
      } else {
        return `${goodsName}`
      }
    },
    
    getStylePriceInfo(item) {
      // 优先显示款式价格信息
      if (item.styleMinPrice || item.styleMaxPrice) {
        const minPrice = parseFloat(item.styleMinPrice)
        const maxPrice = parseFloat(item.styleMaxPrice)
        
        if (minPrice === maxPrice) {
          return `款式价格：¥${minPrice}`
        } else {
          return `款式价格：¥${minPrice}-${maxPrice}`
        }
      }
      
      // 如果没有款式价格，显示商品本身的价格
      if (item.productMinPrice || item.productMaxPrice) {
        const minPrice = parseFloat(item.productMinPrice)
        const maxPrice = parseFloat(item.productMaxPrice)
        
        if (minPrice === maxPrice) {
          return `商品价格：¥${minPrice}`
        } else {
          return `商品价格：¥${minPrice}-${maxPrice}`
        }
      }
      
      return ''
    },
    
    selectQualityLevel(level) {
      // 设置当前选择的质检级别
      this.currentQualityLevel = level
    },
    
    syncPriceToInspectData() {
      // 同步合格产品金额 - 按品牌款式唯一标识
      this.qualifiedList.forEach(qualifiedItem => {
        // 使用uniqueKey或者shopId+pinId+styleId来匹配
        const inspectItem = this.inspectData.list.find(item => {
          if (qualifiedItem.uniqueKey && item.uniqueKey) {
            return item.uniqueKey === qualifiedItem.uniqueKey
          }
          // 备用匹配方式
          return item.shopId === qualifiedItem.shopId && 
                 (item.pinId || '') === (qualifiedItem.pinId || '') &&
                 (item.styleId || '') === (qualifiedItem.styleId || '') &&
                 item.id !== 'unrecyclable' && 
                 item.id !== 'quality_issue'
        })
        
        if (inspectItem) {
          inspectItem.price = parseFloat(qualifiedItem.total) || 0
          // 同步质检级别 - 从items中获取第一个有级别的项目
          const itemWithLevel = qualifiedItem.items && qualifiedItem.items.find(item => item.qualityLevel)
          inspectItem.qualityLevel = itemWithLevel ? itemWithLevel.qualityLevel : (qualifiedItem.qualityLevel || '')
          // 同步理由信息
          if (qualifiedItem.items && qualifiedItem.items.length > 0) {
            inspectItem.commonOrderList = qualifiedItem.items
          }
        }
      })
      
      // 同步不合格产品金额和质检级别
      this.unqualifiedGroups.forEach(group => {
        const inspectItem = this.inspectData.list.find(item => item.id === 'quality_issue')
        if (inspectItem) {
          inspectItem.price = parseFloat(group.total) || 0
          // 同步质检级别
          if (inspectItem.commonOrderList && inspectItem.commonOrderList.length > 0) {
            const itemWithLevel = inspectItem.commonOrderList.find(item => item.qualityLevel)
            if (itemWithLevel) {
              inspectItem.qualityLevel = itemWithLevel.qualityLevel
            }
          }
        }
      })
      
      // 同步不可回收产品金额和质检级别
      this.unrecyclableList.forEach(unrecyclableItem => {
        const inspectItem = this.inspectData.list.find(item => item.id === 'unrecyclable')
        if (inspectItem) {
          inspectItem.price = parseFloat(unrecyclableItem.total) || 0
          // 同步质检级别
          if (inspectItem.commonOrderList && inspectItem.commonOrderList.length > 0) {
            const itemWithLevel = inspectItem.commonOrderList.find(item => item.qualityLevel)
            if (itemWithLevel) {
              inspectItem.qualityLevel = itemWithLevel.qualityLevel
            }
          }
        }
      })
    }
  }
}
</script>

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

  &.popup-open {
    overflow: hidden;
    height: 100vh;
  }
}

.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: 22rpx;
    margin-left: -22rpx;
  }

  .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;
  flex-direction: column;
  background: none;
  padding-bottom: 240rpx;
}

.result-card {
  background: #fff;
  border-radius: 48rpx;
  box-shadow: 0 8rpx 48rpx rgba(0, 0, 0, 0.06);
  margin: 0 24rpx 24rpx 24rpx;
  padding: 48rpx 48rpx 0 48rpx;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #222;
  margin-bottom: 36rpx;
}

.card-title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 36rpx;
}

.status-tag {
  background: #fff7e6;
  color: #ffb400;
  font-size: 24rpx;
  border-radius: 24rpx;
  padding: 4rpx 26rpx;
  font-weight: 400;
  height: 44rpx;
  display: flex;
  align-items: center;
}

.result-row,
.result-group {
  margin-bottom: 36rpx;
}

.row-main {
  display: flex;
  align-items: center;

  .goods-name-section {
    display: flex;
    flex-direction: column;
    margin-right: 8px;

    .goods-name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      line-height: 1.3;
    }

    .goods-brand {
      font-size: 26rpx;
      color: #666;
      font-weight: normal;
      line-height: 1.3;
      margin-top: 4rpx;
    }
    
    .goods-style-price {
      font-size: 26rpx;
      color: #ff6b35;
      font-weight: 600;
      line-height: 1.3;
      margin-top: 4rpx;
    }
  }

  .row-name {
    font-size: 26rpx;
    font-weight: bold;
    color: #222;
    margin-right: 8px;
  }

  .row-count {
    font-size: 13px;
    color: #888;
    margin-right: 8px;
  }

  .row-total {
    font-size: 26rpx;
    color: #222;
    font-weight: bold;
    margin-left: auto;
  }
}

.price-input-row {
  display: flex;
  align-items: center;
  margin-top: 24rpx;
  margin-bottom: 16rpx;

  .price-label {
    font-size: 26rpx;
    color: #888;
    min-width: 160rpx;
    flex-shrink: 0;
  }

  .price-input {
    flex: 1;
    height: 80rpx;
    border-radius: 24rpx;
    background: #f6f6f6;
    border: none;
    font-size: 32rpx;
    color: #222;
    padding: 0 32rpx;
    margin-left: 24rpx;
    font-weight: bold;
  }
}



.row-reason {
  display: flex;
  align-items: center;
  margin-top: 16rpx;

  .reason-label {
    font-size: 26rpx;
    color: #bbb;
    min-width: 160rpx;
    max-width: 240rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .reason-input {
    flex: 1;
    height: 72rpx;
    border-radius: 24rpx;
    background: #f6f6f6;
    border: none;
    font-size: 26rpx;
    color: #222;
    padding-left: 24rpx;
    margin-left: 16rpx;
  }

  .reason-select {
    flex: 1;
    display: flex;
    align-items: center;
    height: 72rpx;
    border-radius: 24rpx;
    background: #f6f6f6;
    font-size: 26rpx;
    color: #bbb;
    padding-left: 24rpx;
    margin-left: 16rpx;
    justify-content: flex-end;
  }

  .reason-placeholder {
    color: #bbb;
    font-size: 26rpx;
    flex-shrink: 0;
    &.selected {
      color: #52c41a;
      font-weight: 500;
    }
  }
}

.info-card {
  background: #fff;
  border-radius: 48rpx;
  box-shadow: 0 8rpx 48rpx rgba(0, 0, 0, 0.06);
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 32rpx;

  .info-label {
    font-size: 26rpx;
    color: #bbb;
    min-width: 160rpx;
  }

  .info-value {
    font-size: 26rpx;
    color: #222;
    margin-left: 16rpx;
  }

  .copy-btn {
    color: #ffb400;
    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;
  }
}

.reason-popup-wrapper {
  z-index: 10000 !important;
}

.reason-popup-wrapper .uni-popup__wrapper {
  z-index: 10000 !important;
}

.reason-popup {
  background: #fff;
  border-radius: 48rpx 48rpx 0 0;
  padding: 0;
  height: 75vh;
  position: relative;
  z-index: 9999;

  .popup-header {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 120rpx;
    border-bottom: 2rpx solid #f0f0f0;
    position: relative;

    .popup-close {
      position: absolute;
      left: 40rpx;
      color: #666;
      font-size: 32rpx;
    }

    .popup-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #222;
    }
  }

  .popup-content {
    height: calc(75vh - 120rpx - 164rpx);
    overflow-y: auto;
  }

  .popup-section {
    padding: 0 40rpx 48rpx 40rpx;

    &:first-child {
      padding-top: 48rpx;
    }

    .section-label {
      font-size: 32rpx;
      color: #222;
      margin-bottom: 32rpx;
      display: block;
      font-weight: 500;
    }
    
    .level-options {
      display: flex;
      gap: 24rpx;
      margin-bottom: 32rpx;

      .level-option {
        width: 80rpx;
        height: 80rpx;
        border-radius: 16rpx;
        border: 4rpx solid #ddd;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #fff;
        cursor: pointer;
        transition: all 0.2s;

        &.selected {
          border-color: #ffb400;
          background: #ffb400;
          
          .level-text {
            color: #fff;
            font-weight: bold;
          }
        }

        .level-text {
          font-size: 32rpx;
          color: #666;
          font-weight: 500;
        }
      }
    }
    
    .custom-reason-input {
      width: 100%;
      min-height: 160rpx;
      padding: 24rpx;
      border: 2rpx solid #e0e0e0;
      border-radius: 16rpx;
      font-size: 28rpx;
      color: #222;
      background: #fff;
      resize: none;
      box-sizing: border-box;
      
      &::placeholder {
        color: #999;
      }
      
      &:focus {
        border-color: #ffb400;
        outline: none;
      }
    }

    .img-list {
      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;
      margin-bottom: 64rpx;

      .img-item {
        width: 150rpx;
        height: 150rpx;
        border-radius: 24rpx;
        background: #f8f8f8;
        position: relative;

        .img {
          width: 100%;
          height: 100%;
          border-radius: 24rpx;
          object-fit: cover;
        }

        .img-del {
          position: absolute;
          top: -12rpx;
          right: -12rpx;
          width: 48rpx;
          height: 48rpx;
          background: rgba(0, 0, 0, 0.6);
          color: #fff;
          border-radius: 50%;
          text-align: center;
          line-height: 48rpx;
          font-size: 32rpx;
          font-weight: bold;
        }

        &.add {
          display: flex;
          align-items: center;
          justify-content: center;
          background: #f8f8f8;
          border: 4rpx dashed #ddd;
          color: #bbb;
        }
      }
    }

    .reason-row {
      display: flex;
      align-items: center;
      padding: 32rpx 0;
      border-bottom: 2rpx solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .checkbox {
        width: 40rpx;
        height: 40rpx;
        border-radius: 8rpx;
        border: 4rpx solid #ddd;
        margin-right: 24rpx;
        background: #fff;
        position: relative;

        &.checked {
          border-color: #ffb400;
          background: #ffb400;

          &::after {
            content: '✓';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #fff;
            font-size: 24rpx;
            font-weight: bold;
          }
        }
      }

      .reason-text {
        font-size: 32rpx;
        color: #222;
        line-height: 1.4;
      }
    }
  }

  .popup-save-btn {
    position: fixed;
    bottom: 68rpx;
    left: 40rpx;
    right: 40rpx;
    height: 96rpx;
    border-radius: 48rpx;
    background: linear-gradient(90deg, #ffd01e 0%, #ffac04 100%);
    color: #fff;
    font-size: 36rpx;
    font-weight: 600;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 8rpx 24rpx rgba(255, 172, 4, 0.3);
  }
}
</style>