<template>
  <view class="page-container">
    <NavBar :title="t('sparepartInbound.selectSparepart')" />

    <!-- 搜索区 -->
    <view class="search-bar">
      <view class="search-input-wrap">
        <text class="search-icon iconfont icon-search"></text>
        <input class="search-input" v-model="searchText" :placeholder="t('sparepartInbound.searchSparepartPlaceholder')" @input="onSearch" placeholder-class="search-placeholder" />
        <text v-if="searchText" class="search-clear" @click="clearSearch">✕</text>
      </view>
    </view>

    <!-- 备件列表 -->
    <scroll-view scroll-y class="sparepart-list" v-if="filteredList.length > 0">
      <view
        v-for="item in filteredList"
        :key="item.id"
        class="sparepart-card"
        :class="{ active: selectedId === item.id }"
        @click="selectedId = item.id"
      >
        <view class="sparepart-card-header">
          <text class="sparepart-name">{{ textValue(item.name) }}</text>
        </view>
        <view class="sparepart-card-body">
          <view class="sparepart-info-row">
            <text class="info-label">{{ t('sparepartInbound.sparepartCode') }}</text>
            <text class="info-value">{{ textValue(item.barCode) }}</text>
          </view>
          <view class="sparepart-info-row">
            <text class="info-label">{{ t('sparepartInbound.spec') }}</text>
            <text class="info-value">{{ textValue(item.standard || item.deviceSpec) }}</text>
          </view>
          <view class="sparepart-info-row">
            <text class="info-label">{{ t('sparepartInbound.category') }}</text>
            <text class="info-value">{{ textValue(item.categoryName) }}</text>
          </view>
          <view class="sparepart-info-row">
            <text class="info-label">{{ t('sparepartInbound.unit') }}</text>
            <text class="info-value">{{ textValue(item.unitName) }}</text>
          </view>
          <view class="sparepart-info-row">
            <text class="info-label">{{ t('sparepartInbound.purchaseUnit') }}</text>
            <text class="info-value">{{ textValue(item.purchaseUnitName) }}</text>
          </view>
          <view class="sparepart-info-row">
            <text class="info-label">{{ t('sparepartInbound.convertRatio') }}</text>
            <text class="info-value">1{{ textValue(item.purchaseUnitName) }}={{ textValue(item.purchaseUnitConvertQuantity) }}{{ textValue(item.unitName) }}</text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 空状态 -->
    <view v-else class="empty-wrap">
      <text v-if="loading" class="empty-text">{{ t('functionCommon.loading') }}</text>
      <text v-else class="empty-text">{{ t('sparepartInbound.noSparepartData') }}</text>
    </view>

    <!-- 底部确认按钮 -->
    <view class="bottom-actions">
      <view class="bottom-btn confirm-btn" @click="handleConfirm">
        {{ t('functionCommon.confirm') }}
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import NavBar from '@/components/common/NavBar.vue'
import { getSparepartSimpleList } from '@/api/mes/sparepart'

const { t } = useI18n()

const sparepartList = ref([])
const selectedId = ref(null)
const searchText = ref('')
const loading = ref(false)

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

const filteredList = computed(() => {
  let list = sparepartList.value
  const keyword = searchText.value.trim().toLowerCase()
  if (keyword) {
    list = list.filter(item => {
      return (item.name || '').toLowerCase().includes(keyword) ||
             (item.barCode || '').toLowerCase().includes(keyword) ||
             (item.standard || '').toLowerCase().includes(keyword)
    })
  }
  return list
})

function onSearch() {}

function clearSearch() {
  searchText.value = ''
}

async function loadSpareparts() {
  loading.value = true
  try {
    const raw = []
    let page = 1
    const maxPages = 5
    while (page <= maxPages) {
      const res = await getSparepartSimpleList(page)
      let root = res && res.data !== undefined ? res.data : res
      let pageList = Array.isArray(root)
        ? root
        : Array.isArray(root?.list) ? root.list
        : Array.isArray(root?.rows) ? root.rows
        : []
      if (!pageList.length) break
      raw.push(...pageList)
      if (pageList.length < 100) break
      page++
    }
    // 只显示分类为 "33" 的备件
    sparepartList.value = raw.filter(item => item.categoryName === '33')
    console.log('[sparepartSelect] 加载全部物料:', raw.length)
  } catch (e) {
    console.error('loadSpareparts error', e)
    uni.showToast({ title: t('functionCommon.loadFailed'), icon: 'none' })
  } finally {
    loading.value = false
  }
}

function handleConfirm() {
  if (!selectedId.value) {
    uni.showToast({ title: t('sparepartInbound.validatorSparepartRequired'), icon: 'none' })
    return
  }
  const item = sparepartList.value.find((d) => d.id === selectedId.value)
  if (!item) return
  // 存入 globalData 后跳转到对应确认页
  getApp().globalData._sparepartBeforeConfirm = item
  const from = getApp().globalData._sparepartSelectFrom || 'inbound'
  const url = from === 'outbound'
    ? '/pages_function/pages/sparepartOutbound/sparepartConfirm'
    : '/pages_function/pages/sparepartInbound/sparepartConfirm'
  uni.navigateTo({ url })
}

onShow(async () => {
  await loadSpareparts()
})
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background: #f5f6f8;
  padding-bottom: 140rpx;
}

/* 搜索栏 */
.search-bar {
  padding: 16rpx 24rpx;
  background: #fff;
}

.search-input-wrap {
  display: flex;
  align-items: center;
  height: 72rpx;
  padding: 0 16rpx;
  background: #f5f6f8;
  border-radius: 36rpx;
}

.search-icon {
  font-size: 32rpx;
  color: #999;
  margin-right: 12rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.search-placeholder {
  color: #bbb;
}

.search-clear {
  font-size: 28rpx;
  color: #999;
  padding: 8rpx;
}

/* 备件列表 */
.sparepart-list {
  padding: 16rpx 24rpx;
}

.sparepart-card {
  background: #fff;
  border-radius: 14rpx;
  padding: 24rpx;
  margin-bottom: 16rpx;
  border: 2rpx solid transparent;

  &.active {
    border-color: #2563eb;
    background: #f0f5ff;
  }
}

.sparepart-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.sparepart-name {
  font-size: 30rpx;
  font-weight: 700;
  color: #1a1a1a;
}

.sparepart-card-body {
  border-top: 1rpx solid #f0f0f0;
  padding-top: 16rpx;
}

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

  &:last-child {
    margin-bottom: 0;
  }
}

.info-label {
  width: 140rpx;
  font-size: 24rpx;
  color: #999;
  flex-shrink: 0;
}

.info-value {
  font-size: 26rpx;
  color: #333;
}

/* 空状态 */
.empty-wrap {
  padding: 120rpx 0;
  text-align: center;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 底部确认按钮 */
.bottom-actions {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 18rpx 24rpx calc(18rpx + env(safe-area-inset-bottom));
  background: #fff;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
  z-index: 99;
}

.bottom-btn {
  width: 100%;
  height: 84rpx;
  line-height: 84rpx;
  text-align: center;
  border-radius: 16rpx;
  font-size: 30rpx;
  font-weight: 600;
}

.confirm-btn {
  background: #1f4b79;
  color: #fff;
}
</style>
