<template>
  <view class="page-container">
    <NavBar :title="'选择盘点项'" />

    <view class="search-bar">
      <input
        v-model="keyword"
        class="search-input"
        placeholder="搜索编码/名称"
        confirm-type="search"
        @confirm="handleSearch"
      />
      <text class="search-btn" @click="handleSearch">搜索</text>
    </view>

    <view class="select-all-bar">
      <view class="checkbox-wrap" @click="toggleSelectAll">
        <text :class="['checkbox', isAllSelected ? 'checkbox-checked' : '']">{{ isAllSelected ? '✓' : '' }}</text>
        <text class="select-all-text">全选</text>
      </view>
      <text class="select-count">已选 {{ selectedItems.length }} 项</text>
    </view>

    <scroll-view scroll-y class="list-scroll">
      <view v-for="item in filteredList" :key="item.productId + '_' + (item.warehouseId || '')" class="item-row" @click="toggleSelect(item)">
        <view class="checkbox-wrap">
          <text :class="['checkbox', isSelected(item) ? 'checkbox-checked' : '']">{{ isSelected(item) ? '✓' : '' }}</text>
        </view>
        <view class="item-info">
          <view class="info-row">
            <text class="info-label">仓库</text>
            <text class="info-val">{{ textValue(item.warehouseName) }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">库区</text>
            <text class="info-val">{{ textValue(item.areaName) }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">编码</text>
            <text class="info-val code">{{ textValue(item.productBarCode) }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">名称</text>
            <text class="info-val name">{{ textValue(item.productName) }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">库存数量</text>
            <text class="info-val stock">{{ textValue(item.stockCount) }}</text>
          </view>
        </view>
      </view>

      <view v-if="loading" class="loading-text">加载中...</view>
      <view v-if="!loading && !list.length" class="empty-text">暂无数据</view>
    </scroll-view>

    <view class="bottom-actions">
      <view class="bottom-btn cancel-btn" @click="handleCancel">取消</view>
      <view class="bottom-btn confirm-btn" @click="handleConfirm">确定</view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import NavBar from '@/components/common/NavBar.vue'
import { generateCheckItemsByProduct } from '@/api/mes/materialCheck'

const routeProductId = ref('')
const list = ref([])
const selectedItems = ref([])
const loading = ref(false)
const keyword = ref('')
let isFirstLoad = true

const filteredList = computed(() => {
  if (!keyword.value) return list.value
  return list.value.filter(item =>
    (item.productBarCode || '').includes(keyword.value) ||
    (item.productName || '').includes(keyword.value) ||
    (item.warehouseName || '').includes(keyword.value)
  )
})

const isAllSelected = computed(() => {
  return filteredList.value.length > 0 && filteredList.value.every(item => isSelected(item))
})

function textValue(v) {
  if (v === 0) return '0'
  if (v == null) return '-'
  return String(v).trim() || '-'
}

function getItemKey(item) {
  return `${item.productId || item.id}_${item.warehouseId || ''}_${item.areaId || ''}`
}

function isSelected(item) {
  const key = getItemKey(item)
  return selectedItems.value.some(s => getItemKey(s) === key)
}

function toggleSelect(item) {
  const key = getItemKey(item)
  const idx = selectedItems.value.findIndex(s => getItemKey(s) === key)
  if (idx >= 0) {
    selectedItems.value.splice(idx, 1)
  } else {
    selectedItems.value.push({ ...item })
  }
}

function toggleSelectAll() {
  if (isAllSelected.value) {
    selectedItems.value = []
  } else {
    selectedItems.value = [...filteredList.value]
  }
}

async function loadData() {
  loading.value = true
  try {
    const ids = routeProductId.value.split(',').map(id => Number(id.trim())).filter(Boolean)
    const res = await generateCheckItemsByProduct({
      productIds: ids,
      categoryType: 2,
      allowEmpty: true
    })
    const data = Array.isArray(res) ? res : (Array.isArray(res?.data) ? res.data : [])
    list.value = data
  } catch (e) {
    console.error('loadData error', e)
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

function handleSearch() {}

function handleCancel() {
  uni.navigateBack()
}

function handleConfirm() {
  if (!selectedItems.value.length) {
    uni.showToast({ title: '请至少选择一项', icon: 'none' })
    return
  }
  getApp().globalData._materialCheckItemSelectResult = [...selectedItems.value]
  uni.navigateBack()
}

onLoad((options) => {
  routeProductId.value = options?.productIds || options?.productId || ''
})

onShow(() => {
  const prevSelected = getApp().globalData?._materialCheckItemSelected
  if (prevSelected && Array.isArray(prevSelected)) {
    selectedItems.value = prevSelected.map(item => ({
      id: item.id || item.productId,
      productId: item.productId || item.id,
      warehouseId: item.warehouseId,
      areaId: item.areaId,
      warehouseName: item.warehouseName,
      areaName: item.areaName,
      productBarCode: item.productBarCode,
      productName: item.productName,
      stockCount: item.stockCount,
      productPrice: item.productPrice
    }))
    getApp().globalData._materialCheckItemSelected = null
  }
  if (isFirstLoad) {
    isFirstLoad = false
    loadData()
  }
})
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background: #f5f6f8;
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

.search-bar { display: flex; gap: 16rpx; padding: 20rpx 24rpx; background: #fff; }
.search-input { flex: 1; height: 72rpx; padding: 0 24rpx; background: #f3f4f6; border-radius: 12rpx; font-size: 28rpx; }
.search-btn { display: flex; align-items: center; justify-content: center; width: 120rpx; height: 72rpx; background: #1f4b79; color: #fff; border-radius: 12rpx; font-size: 28rpx; }

.select-all-bar { display: flex; align-items: center; justify-content: space-between; padding: 20rpx 24rpx; background: #fff; border-bottom: 1rpx solid #f0f0f0; }
.checkbox-wrap { display: flex; align-items: center; gap: 12rpx; }
.checkbox { width: 40rpx; height: 40rpx; border: 2rpx solid #d1d5db; border-radius: 8rpx; display: flex; align-items: center; justify-content: center; font-size: 24rpx; color: #fff; background: #fff;
  &.checkbox-checked { background: #1f4b79; border-color: #1f4b79; }
}
.select-all-text { font-size: 28rpx; color: #374151; }
.select-count { font-size: 26rpx; color: #1f4b79; font-weight: 600; }

.list-scroll { height: calc(100vh - 330rpx - env(safe-area-inset-bottom)); }
.item-row { display: flex; align-items: flex-start; gap: 16rpx; padding: 20rpx 24rpx; background: #fff; border-bottom: 1rpx solid #f0f0f0;
  &:active { background: #f9fafb; }
}
.item-info { flex: 1; display: flex; flex-direction: column; gap: 8rpx; }
.info-row { display: flex; align-items: center; gap: 16rpx; }
.info-label { width: 120rpx; font-size: 24rpx; color: #9ca3af; flex-shrink: 0; }
.info-val { flex: 1; font-size: 26rpx; color: #374151;
  &.code { font-family: monospace; color: #6b7280; }
  &.name { font-weight: 500; color: #1a1a1a; }
  &.stock { font-weight: 600; color: #1f4b79; }
}

.loading-text, .empty-text { padding: 40rpx; text-align: center; color: #9ca3af; font-size: 26rpx; }

.bottom-actions { position: fixed; left: 0; right: 0; bottom: 0; display: flex; gap: 18rpx; padding: 18rpx 24rpx calc(18rpx + env(safe-area-inset-bottom)); background: #fff; box-shadow: 0 -8rpx 24rpx rgba(15,23,42,0.06); z-index: 99; }
.bottom-btn { flex: 1; height: 84rpx; line-height: 84rpx; text-align: center; border-radius: 16rpx; font-size: 30rpx; font-weight: 600;
  &:active { opacity: 0.85; }
}
.cancel-btn { background: #eef2f7; color: #475569; }
.confirm-btn { background: #1f4b79; color: #fff; }
</style>
