<template>
  <gui-page :custom-header="true" :header-class="['gui-theme-background-color']">
    <template #gHeader>
      <view style="height:44px;" class="gui-flex gui-nowrap gui-rows gui-align-items-center">
        <text
          style="font-size:44rpx;"
          class="gui-header-leader-btns gui-color-white font-icons"
          @tap="goBack"
        >&#xe6c5;</text>
        <text
          class="gui-h4 gui-blod gui-flex1 gui-text-center gui-ellipsis gui-color-white gui-primary-text"
        >扫描清单资源档</text>
        <view style="width:40px;" />
      </view>
    </template>

    <template #gBody>
      <view class="list-content">
        <view class="table-title">
          <span>已扫物料资源清单</span>
        </view>

        <!-- 数据列表 -->
        <view v-if="cardList?.length" class="scroll-box">
          <view
            v-for="(item, idx) in cardList"
            :key="item.id"
            class="swipe-card"
            :data-index="idx"
            @touchstart="touchStart"
            @touchmove="touchMove"
            @touchend="touchEnd"
          >
            <!-- 原来整套卡片结构原封不动 -->
            <view class="card-content" :style="{ transform: `translateX(${item.slideX || 0}px)` }">
              <view class="card-list-flexbox">
                <view class="card-list-item">
                  <text class="text-1 gui-color-gray">物料号</text>
                  <text class="text-2 gui-color-gray">{{ item.materialNo }}</text>
                </view>
                <view class="card-list-item">
                  <text class="text-1 gui-color-gray">物料名称</text>
                  <text class="text-2 gui-color-gray">{{ item.materialName }}</text>
                </view>
                <view class="card-list-item">
                  <text class="text-1 gui-color-gray">数量</text>
                  <text class="text-2" style="color: orange;font-weight: bold;">{{ item.batchQty }}</text>
                </view>
                <view class="card-list-item">
                  <text class="text-1 gui-color-gray">批号</text>
                  <text class="text-2" style="color: orange;font-weight: bold;">{{ item.batchNumber }}</text>
                </view>
              </view>
            </view>
            <!-- 删除按钮移出来，和card-content同级 -->
            <view class="btn-delete" @tap.stop="deleteItem(item, idx)">删除</view>
          </view>
        </view>

        <!-- 空态 -->
        <view v-else>
          <view class="bg-image">
            <image src="@/static/empty.png" mode="heightFix" />
            <text>这里什么都没有...</text>
          </view>
        </view>
      </view>
    </template>
  </gui-page>
</template>

<script>
import { onReachBottom } from '@dcloudio/uni-app'
import { ref, defineComponent, onMounted, onBeforeMount } from 'vue'

export default defineComponent({
  setup() {
    const parentRow = uni.getStorageSync('mixMaterialDetail') ?? {}
    const detailId = ref('')
    const queryParams = ref({ pageSize: 10, pageNo: 1, id: '' })
    const cardList = ref([])
	const hasMore = ref(true)

    onBeforeMount(() => {
      detailId.value = JSON.parse(parentRow)?.id
    })

    onMounted(() => {
      search()
    })

    const search = () => {
      // uni.$reqGet('getScannedOutSendResourcePage', { ...queryParams.value, id: detailId.value }).then(
	  uni.$reqGet('getScannedOutSendResourcePage', { id: detailId.value }).then(
        ({ data }) => {
          const list = data?.inoutRequestSubdetailList ?? []
		  cardList.value = list
		  console.log('返回数据:', list)  // ← 添加调试，看数据是否存在
		  console.log('数据长度:', list.length)
		  // 如果首次加载不足10条，标记为没有更多数据
		  hasMore.value = list.length >= queryParams.value.pageSize
        }
      )
    }

const goBack = () => {
  // 设置刷新标记，让 scannedMaterials 返回时刷新数据
  uni.setStorageSync('needRefreshScanOut', 'true')
  
  uni.removeStorageSync('mixMaterialDetail')
  uni.$goBack('/pages/workbranch/warehouse/scanInOut/Out/scannedMaterials')
}

    /* ===== 左滑删除 ===== */
    const touchStart = e => {
      const idx = e.currentTarget.dataset.index
      cardList.value.forEach((v, i) => {
        if (i !== idx) v.slideX = 0
      })
      const row = cardList.value[idx]
      row.startX = e.touches[0].pageX
      row.slideX = row.slideX || 0
    }

    const touchMove = e => {
      const idx = e.currentTarget.dataset.index
      const row = cardList.value[idx]
      const delta = e.touches[0].pageX - row.startX
      row.slideX = delta < 0 ? Math.max(delta, -70) : Math.min(delta, 0)
    }

    const touchEnd = e => {
      const idx = e.currentTarget.dataset.index
      const row = cardList.value[idx]
      row.slideX = row.slideX <= -35 ? -70 : 0
    }

    const deleteItem = (item, idx) => {
      // 调用删除接口
      uni.$reqDelete('deleteScanOutMaterial', { id: item.id }).then(res => {
        if (res.code === 0) {
          // 后端返回成功，删除本地数据
          cardList.value.splice(idx, 1)
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
        } else {
          // 后端返回失败，提示错误信息
          uni.showToast({
            title: res.data || '删除失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      })
    }

    /* 下拉加载更多 */
    // onReachBottom(() => {
    //   // 如果没有更多数据，直接返回不调用接口
    //   if (!hasMore.value) return
      
    //   queryParams.value.pageNo += 1
      
    //   uni.$reqGet('getScannedOutSendResourcePage', { ...queryParams.value, id: detailId.value }).then(
    //     ({ data }) => {
    //       const list = data?.inoutRequestSubdetailList ?? []
    //       cardList.value.push(...list)
    //       // 如果本次返回数据不足10条，标记为没有更多数据
    //       hasMore.value = list.length >= queryParams.value.pageSize
    //     }
    //   )
    // })

    return { goBack, cardList, touchStart, touchMove, touchEnd, deleteItem }
  }
})
</script>

<style lang="scss" scoped>
	.gui-header-leader-btns {
		color: black;
		font-size: 24px !important;
		margin-left: 24rpx;
	}

	.list-content {
		margin-top: 80px;
		background-color: #edeeee;
	}

	.card-list-flexbox {
		display: flex;
		flex-direction: row;
		align-items: center;
		flex-wrap: wrap;
		margin: 3px 2px;

		.card-list-item {
			width: 750rpx;
			min-height: 40px;
			margin: 2rpx 0;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-between;
			background-color: #fff;

			uni-text {
				font-size: 14px;
				min-height: 40px;
				text-align: left;
				padding: 0 12px;
				display: flex;
				flex-direction: row;
				align-items: center;
			}

			.text-1 {
				flex: 1;
				min-height: 40px;
				justify-content: flex-start;
			}

			.text-2 {
				flex: 3;
				min-height: 40px;
				justify-content: flex-end;
				margin-right: 4px;
				padding: 2px 6px;
			}
		}

		.card-list-item:nth-of-type(1) {

			.text-1 {
				flex: 9;
				font-weight: bold;
				color: black !important;
			}

			.text-2 {
				flex: 4;
				display: flex;
				flex-direction: row;
				justify-content: flex-end;
				align-items: center;
				color: limegreen !important;
			}
		}

	}

	.font-icons {
		width: 40px;
		font-size: 20px;
	}

	.table-title {
		height: 40px;
		line-height: 40px;
		margin: 0 0 4px 0;
		padding: 0 12px;
		font-size: 16px;
		font-weight: bold;
		background-color: white;
	}

	/* 左滑删除样式 */
	.scroll-box{ padding: 0 12px; }
	.swipe-card {
  position: relative;
  overflow: hidden; // ✅ 关键
  margin-bottom: 8px;
  border-radius: 6px;
}
.card-content {
  position: relative; // ✅ 关键
  z-index: 2;
  background: #fff;
  transition: transform 0.25s;
  width: 100%;
}
.btn-delete {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto 0;        // 上下 auto → 垂直居中
  width: 70px;
  height: 80rpx;         // ✅ 固定高度
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e54d42;
  color: #fff;
  font-size: 14px;
  border-radius: 0 6px 6px 0;
  z-index: 1;
}
</style>
