<template>
  <view class="page-container">
    <NavBar :title="'盘点执行'" />

    <!-- 盘点单信息 -->
    <view class="header-card" v-if="detail">
      <view class="header-top">
        <text class="header-no">{{ textValue(detail.no) }}</text>
      </view>
      <view class="header-info">
        <view class="info-row">
          <text class="info-label">盘点仓库</text>
          <text class="info-value">{{ textValue(detail.warehouseName || getWarehouseName()) }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">盘点库位</text>
          <text class="info-value">{{ textValue(getAreaName()) }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">盘点时间</text>
          <text class="info-value">{{ formatDateTime(detail.checkTime) }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">盘点人</text>
          <text class="info-value">{{ textValue(detail.creatorName || detail.creator) }}</text>
        </view>
      </view>
    </view>

    <!-- 加载中 -->
    <view v-if="loading" class="hint">加载中...</view>

    <!-- 备件盘点列表 -->
    <view v-else-if="items.length" class="check-list">
      <view v-for="(item, idx) in items" :key="idx" class="check-card">
        <!-- 序号标题 -->
        <view class="check-card-header">
          <text class="check-card-index">{{ idx + 1 }}</text>
          <view class="check-card-header-info">
            <text class="check-card-name">{{ textValue(item.productName) }}</text>
            <text class="check-card-code">{{ textValue(item.productBarCode) }}</text>
          </view>
        </view>

        <!-- 备件信息 -->
        <view class="sparepart-info">
          <view class="sp-row">
            <text class="sp-label">规格型号</text>
            <text class="sp-value">{{ textValue(item.standard || item.productStandard || item.deviceSpec) }}</text>
          </view>
        </view>

        <!-- 库存信息 -->
        <view class="stock-info">
          <view class="st-row">
            <text class="st-label">账面库存</text>
            <text class="st-value">{{ formatNumber(item.stockCount) }} {{ textValue(item.productUnitName || item.unitName || '个') }}</text>
          </view>
          <view class="st-row">
            <text class="st-label">最小单位</text>
            <text class="st-value">{{ textValue(item.productUnitName || item.unitName || '个') }}</text>
          </view>
          <view class="st-row">
            <text class="st-label">换算关系</text>
            <text class="st-value">{{ getConvertText(item) }}</text>
          </view>
        </view>

        <!-- 实盘数量输入 -->
        <view class="input-row">
          <text class="input-label">实盘数量</text>
          <view class="input-control">
            <view class="input-btn minus" @click="handleMinus(idx)">-</view>
            <input v-model="item._checkCount" class="input-field" type="digit" placeholder="0" />
            <view class="input-btn plus" @click="handlePlus(idx)">+</view>
          </view>
        </view>

        <!-- 差异 -->
        <view class="diff-row">
          <text class="diff-label">差异</text>
          <text :class="['diff-value', diffClass(item)]">{{ getDiffText(item) }}</text>
        </view>

        <!-- 备注 -->
        <view class="remark-row">
          <text class="remark-label">备注</text>
          <input v-model="item._remark" class="remark-input" placeholder="请输入备注" />
        </view>
      </view>
    </view>

    <!-- 无数据 -->
    <view v-else class="hint">暂无盘点数据</view>

    <!-- 底部提交 -->
    <view v-if="items.length" class="bottom-actions">
      <view class="submit-btn" @click="handleSubmit">提交盘点结果</view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import NavBar from '@/components/common/NavBar.vue'
import { getSparepartCheckDetail, executeSparepartCheck } from '@/api/mes/sparepartCheck'
import { getProductDetail } from '@/api/mes/sparepart'

const detail = ref(null)
const items = ref([])
const loading = ref(false)

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

function formatNumber(v) {
  if (v == null) return '0'
  return String(v)
}

function formatDateTime(value) {
  if (!value) return '-'
  if (Array.isArray(value) && value.length >= 5) {
    const [y, m, d, h = 0, min = 0, s = 0] = value
    const pad = (n) => String(n).padStart(2, '0')
    return `${y}-${pad(m)}-${pad(d)} ${pad(h)}:${pad(min)}:${pad(s)}`
  }
  const date = new Date(Number(value))
  if (Number.isNaN(date.getTime())) return String(value)
  const pad = (n) => String(n).padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}

function getWarehouseName() {
  const item = items.value[0]
  return item?.warehouseName || ''
}

function getAreaName() {
  const item = items.value[0]
  return item?.areaName || ''
}

function getConvertText(item) {
  const purchaseUnit = item?.purchaseUnitName
  const ratio = item?.purchaseUnitConvertQuantity
  const unit = item?.productUnitName || item?.unitName || '个'
  if (purchaseUnit && ratio) {
    return `1${purchaseUnit}=${ratio}${unit}`
  }
  return '-'
}

function getDiff(item) {
  const count = Number(item._checkCount) || 0
  const stock = Number(item.stockCount) || 0
  return count - stock
}

function getDiffText(item) {
  const d = getDiff(item)
  const unit = item?.productUnitName || item?.unitName || '个'
  if (d === 0) return `0 ${unit}`
  return `${d > 0 ? '+' : ''}${d} ${unit}`
}

function diffClass(item) {
  const d = getDiff(item)
  if (d > 0) return 'positive'
  if (d < 0) return 'negative'
  return ''
}

function handleMinus(idx) {
  const val = Number(items.value[idx]._checkCount) || 0
  if (val > 0) {
    items.value[idx]._checkCount = String(val - 1)
  }
}

function handlePlus(idx) {
  const val = Number(items.value[idx]._checkCount) || 0
  items.value[idx]._checkCount = String(val + 1)
}

onLoad(async (options) => {
  const id = options?.id
  if (!id) {
    uni.showToast({ title: '参数错误', icon: 'none' })
    return
  }
  loading.value = true
  try {
    const res = await getSparepartCheckDetail(id)
    const data = res?.data || res
    detail.value = data
    const rawItems = data?.items || []

    // 补全备件详细信息
    const enrichedItems = await Promise.all(
      rawItems.map(async (item) => {
        if (!item.productId) return item
        try {
          const productRes = await getProductDetail(item.productId)
          const product = productRes?.data || productRes
          if (product && product.id) {
            return {
              ...item,
              standard: item.standard || product.standard || product.deviceSpec,
              productUnitName: item.productUnitName || product.unitName || product.minStockUnitName,
              minStockUnitName: item.minStockUnitName || product.minStockUnitName,
              purchaseUnitName: item.purchaseUnitName || product.purchaseUnitName,
              purchaseUnitConvertQuantity: item.purchaseUnitConvertQuantity || product.purchaseUnitConvertQuantity,
              _checkCount: item.checkCount != null ? String(item.checkCount) : '',
              _remark: item.remark || ''
            }
          }
        } catch (e) {
          console.error('补全备件信息失败:', item.productId, e)
        }
        return {
          ...item,
          _checkCount: '',
          _remark: ''
        }
      })
    )

    items.value = enrichedItems
  } catch (e) {
    const msg = e?.message || e?.data?.msg || '加载失败'
    console.error('加载盘点单失败:', e)
    uni.showToast({ title: String(msg).substring(0, 50), icon: 'none' })
  } finally {
    loading.value = false
  }
})

async function handleSubmit() {
  // 校验至少有一项填写了盘点数量
  const submitItems = items.value.map((item) => {
    const actual = Number(item._checkCount) || 0
    const stock = item.stockCount != null ? Number(item.stockCount) : 0
    return {
      id: Number(item.id),
      warehouseId: Number(item.warehouseId),
      areaId: item.areaId ? Number(item.areaId) : undefined,
      productId: Number(item.productId),
      productPrice: item.productPrice != null ? Number(item.productPrice) : 0,
      stockCount: stock,
      actualCount: actual,
      count: actual - stock,
      remark: item._remark || ''
    }
  })

  try {
    const now = new Date()
    const pad = (n) => String(n).padStart(2, '0')
    const checkTimeStr = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`
    const payload = {
      id: Number(detail.value.id),
      checkTime: checkTimeStr,
      sourceType: detail.value.sourceType,
      categoryType: detail.value.categoryType,
      checkStatus: 1,
      remark: '',
      fileUrl: '',
      items: submitItems
    }
    console.log('[盘点提交]', JSON.stringify(payload))
    uni.showLoading({ title: '提交中...', mask: true })
    await executeSparepartCheck(payload)
    uni.hideLoading()
    uni.showToast({ title: '盘点完成', icon: 'success' })
    setTimeout(() => uni.navigateBack(), 1500)
  } catch (e) {
    uni.hideLoading()
    const msg = e?.message || e?.data?.msg || e?.response?.data?.msg || '盘点失败'
    console.error('盘点提交失败:', e)
    uni.showToast({ title: String(msg).substring(0, 50), icon: 'none' })
  }
}
</script>

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

/* 顶部信息卡片 */
.header-card {
  background: #fff;
  margin: 20rpx 24rpx;
  padding: 24rpx;
  border-radius: 16rpx;
}
.header-top { margin-bottom: 20rpx; }
.header-no { font-size: 32rpx; font-weight: 700; color: #1a1a1a; }
.header-info { border-top: 1rpx solid #f0f0f0; padding-top: 20rpx; }
.info-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16rpx;
  &:last-child { margin-bottom: 0; }
}
.info-label { font-size: 26rpx; color: #6b7280; }
.info-value { font-size: 26rpx; color: #1a1a1a; font-weight: 500; }

/* 盘点卡片列表 */
.check-list { padding: 0 24rpx; }
.check-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
}

/* 卡片序号头部 */
.check-card-header {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}
.check-card-index {
  width: 48rpx;
  height: 48rpx;
  border-radius: 24rpx;
  background: #1f4b79;
  color: #fff;
  font-size: 26rpx;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}
.check-card-header-info { flex: 1; }
.check-card-name { font-size: 30rpx; font-weight: 700; color: #1a1a1a; display: block; }
.check-card-code { font-size: 24rpx; color: #9ca3af; margin-top: 4rpx; display: block; }

/* 备件信息 */
.sparepart-info { margin-bottom: 20rpx; }
.sp-row { display: flex; align-items: center; justify-content: space-between; }
.sp-label { font-size: 26rpx; color: #6b7280; }
.sp-value { font-size: 26rpx; color: #1a1a1a; font-weight: 500; }

/* 库存信息 */
.stock-info {
  background: #f8fafc;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}
.st-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12rpx;
  &:last-child { margin-bottom: 0; }
}
.st-label { font-size: 24rpx; color: #6b7280; }
.st-value { font-size: 26rpx; color: #16a34a; font-weight: 600; }

/* 实盘数量 */
.input-row { margin-bottom: 20rpx; }
.input-label { font-size: 26rpx; color: #1a1a1a; font-weight: 500; margin-bottom: 12rpx; display: block; }
.input-control { display: flex; align-items: center; gap: 12rpx; }
.input-btn {
  width: 64rpx; height: 64rpx; border-radius: 12rpx;
  background: #f3f4f6; display: flex; align-items: center; justify-content: center;
  font-size: 36rpx; color: #374151; font-weight: 600;
  &:active { background: #e5e7eb; }
}
.input-field {
  flex: 1; height: 64rpx; text-align: center;
  background: #f8fafc; border: 1rpx solid #e0e0e0; border-radius: 10rpx;
  font-size: 30rpx; color: #1a1a1a; font-weight: 600;
}

/* 差异 */
.diff-row { display: flex; align-items: center; justify-content: space-between; padding: 16rpx 0; border-top: 1rpx solid #f0f0f0; margin-bottom: 16rpx; }
.diff-label { font-size: 26rpx; color: #6b7280; }
.diff-value { font-size: 28rpx; font-weight: 700;
  &.positive { color: #16a34a; }
  &.negative { color: #dc2626; }
}

/* 备注 */
.remark-row { display: flex; align-items: center; gap: 16rpx; }
.remark-label { font-size: 26rpx; color: #6b7280; flex-shrink: 0; }
.remark-input {
  flex: 1; height: 64rpx;
  background: #f8fafc; border: 1rpx solid #e0e0e0; border-radius: 10rpx;
  padding: 0 16rpx; font-size: 26rpx; color: #374151;
}

/* 底部 */
.hint { padding: 120rpx 0; text-align: center; color: #94a3b8; font-size: 28rpx; }
.bottom-actions {
  position: fixed; left: 0; right: 0; bottom: 0;
  padding: 20rpx 24rpx calc(20rpx + env(safe-area-inset-bottom));
  background: #fff; box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.06);
}
.submit-btn {
  height: 88rpx; line-height: 88rpx; text-align: center;
  background: #1a3a5c; color: #fff; font-size: 30rpx; font-weight: 600;
  border-radius: 12rpx;
  &:active { opacity: 0.9; }
}
</style>
