<template>
  <view style="display: block;">
    <view class="top">
      <uv-image src="../../../../static//logo/logo.jpg" width="40px" height="40px" style="margin-top:10rpx" />

      <!-- 唯一兼容 iPad 的写法：纯 2D Canvas -->
      <canvas id="barcode" type="2d" class="barcode-canvas"></canvas>
    </view>

    <view class="content mt-16">
      <p>物料：
        <text>{{ material?.materialName }}</text>
        <text v-if="material?.quantity">x {{ material?.quantity }}</text>
      </p>
      <p>描述：
        <text v-if="material?.description">{{ material?.description || '-' }}</text>
        <text v-else>
          <text v-if="material?.materialShortName">{{ material?.materialShortName }} / </text>
          <text v-if="material?.model">{{ material?.model }} / </text>
          <text v-if="material?.specification">{{ material?.specification }} / </text>
          <text v-if="material?.typeName">{{ material?.typeName }} </text>
        </text>
      </p>
      <view class="top">
        <p>备注：
          <text>
            <text v-if="item?.uniqueCodeRemark">{{ item?.uniqueCodeRemark }}</text>
            <text v-else class="empty">未填写</text>
          </text>
        </p>
        <uv-image :src="qrCode" width="80rpx" height="80rpx" />
      </view>
    </view>
  </view>

</template>

<script setup>
import { onMounted, computed, watch } from 'vue';
import JsBarcode from 'jsbarcode';

const props = defineProps({
  detail: { type: Object, default: null }
});

const qrCode = computed(() => props.detail?.material?.[0]?.qrCode);
const material = computed(() => props.detail?.material?.[0]);
const barcodeValue = computed(() => props.detail?.material?.[0]?.code || '');
console.log(props.detail?.material?.[0]?.code, 'code==>');


// iPad 兼容核心：不用 document，只用 uni 官方 API
const drawBarcode = () => {
  if (!barcodeValue.value) return;

  const query = uni.createSelectorQuery();
  query.select('#barcode')
    .fields({ node: true, size: true })
    .exec((res) => {
      const canvas = res[0]?.node;
      if (!canvas) return;

      const ctx = canvas.getContext('2d');
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 渲染条形码
      JsBarcode(canvas, barcodeValue.value, {
        format: 'CODE128',
        width: 2,
        height: 40,
        displayValue: false,
        margin: 10,
      });
    });
};

// 延迟执行，保证 iPad 能加载
onMounted(() => {
  setTimeout(drawBarcode, 400);
});

// 数据变化重新绘制
watch(
  () => props.detail,
  () => setTimeout(drawBarcode, 400),
  { deep: true }
);
</script>

<style scoped lang="scss">
.top {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.content {

  // display: flex;
  p {
    font-weight: 600;
    font-size: 14px;
  }

  text {
    font-weight: 400;
    font-size: 14px;
  }
}

.empty {
  color: #D3D3D3;
}

/* 必须给宽度高度，iPad 才会显示 */
.barcode-canvas {
  width: 40%;
  height: 20px;
}
</style>