<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>
            </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 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,
      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,
            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 = []
      }
      // 不在这里设置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 = []
      }
      // 使用从上一个页面传过来的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.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}`
      }
    },
    
    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
          // 同步理由信息
          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
        }
      })
      
      // 同步不可回收产品金额
      this.unrecyclableList.forEach(unrecyclableItem => {
        const inspectItem = this.inspectData.list.find(item => item.id === 'unrecyclable')
        if (inspectItem) {
          inspectItem.price = parseFloat(unrecyclableItem.total) || 0
        }
      })
    }
  }
}
</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: 120px;
}

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

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #222;
  margin-bottom: 18px;
}

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

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

.result-row,
.result-group {
  margin-bottom: 18px;
}

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

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

    .goods-name {
      font-size: 26rpx;
      font-weight: bold;
      color: #222;
      line-height: 1.2;
    }

    .goods-brand {
      font-size: 22rpx;
      color: #999;
      font-weight: normal;
      line-height: 1.2;
      margin-top: 2px;
    }
  }

  .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: 12px;
  margin-bottom: 8px;

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

  .price-input {
    flex: 1;
    height: 40px;
    border-radius: 12px;
    background: #f6f6f6;
    border: none;
    font-size: 16px;
    color: #222;
    padding: 0 16px;
    margin-left: 12px;
    font-weight: bold;
  }
}

.row-reason {
  display: flex;
  align-items: center;
  margin-top: 8px;

  .reason-label {
    font-size: 13px;
    color: #bbb;
    min-width: 80px;
  }

  .reason-input {
    flex: 1;
    height: 36px;
    border-radius: 12px;
    background: #f6f6f6;
    border: none;
    font-size: 26rpx;
    color: #222;
    padding-left: 12px;
    margin-left: 8px;
  }

  .reason-select {
    flex: 1;
    display: flex;
    align-items: center;
    height: 36px;
    border-radius: 12px;
    background: #f6f6f6;
    font-size: 26rpx;
    color: #bbb;
    padding-left: 12px;
    margin-left: 8px;
    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: 24px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06);
  margin: 0 24px 24px 24px;
  padding: 24px 24px 0 24px;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 16px;

  .info-label {
    font-size: 13px;
    color: #bbb;
    min-width: 80px;
  }

  .info-value {
    font-size: 13px;
    color: #222;
    margin-left: 8px;
  }

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

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

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

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

  .popup-header {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60px;
    border-bottom: 1px solid #f0f0f0;
    position: relative;

    .popup-close {
      position: absolute;
      left: 20px;
      color: #666;
      font-size: 16px;
    }

    .popup-title {
      font-size: 18px;
      font-weight: 600;
      color: #222;
    }
  }

  .popup-content {
    height: calc(75vh - 60px - 82px);
    overflow-y: auto;
  }

  .popup-section {
    padding: 0 20px 24px 20px;

    &:first-child {
      padding-top: 24px;
    }

    .section-label {
      font-size: 16px;
      color: #222;
      margin-bottom: 16px;
      display: block;
      font-weight: 500;
    }
    
    .custom-reason-input {
      width: 100%;
      min-height: 80px;
      padding: 12px;
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      font-size: 14px;
      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: 32px;

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

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

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

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

    .reason-row {
      display: flex;
      align-items: center;
      padding: 16px 0;
      border-bottom: 1px solid #f0f0f0;

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

      .checkbox {
        width: 20px;
        height: 20px;
        border-radius: 4px;
        border: 2px solid #ddd;
        margin-right: 12px;
        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: 12px;
            font-weight: bold;
          }
        }
      }

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

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