<template>
  <view class="container">
    <!-- 扫码按钮 -->
    <button type="primary" @click="scanCode" class="scan-btn">
      扫码识别图书
    </button>

    <!-- 图书信息展示 -->
    <view class="book-info" v-if="bookData.title">
      <image :src="bookData.image" class="book-cover" mode="widthFix"></image>
      <view class="book-title">{{ bookData.title }}</view>
      <view class="book-desc">作者：{{ bookData.author }}</view>
      <view class="book-desc">出版社：{{ bookData.publisher }}</view>
      <view class="book-desc">出版日期：{{ bookData.pubdate }}</view>
      <view class="book-desc">ISBN：{{ isbn }}</view>
    </view>

    <!-- 无数据提示 -->
    <view class="empty" v-else>
      请点击按钮扫描图书条形码
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isbn: '', // 扫码得到的ISBN
      bookData: {} // 图书信息
    }
  },
  methods: {
    // 调用微信扫码
    async scanCode() {
      try {
        // 只允许扫条形码（图书ISBN）
        const res = await uni.scanCode({
          onlyFromCamera: true,
          scanType: ['barCode']
        })
        
        // res.result 就是扫码得到的ISBN编码
        // this.isbn = res.result
        this.isbn = '9787020167319'
        console.log('扫码结果：', this.isbn)
        
        // 根据ISBN查询图书信息
        this.getBookInfo()
        
      } catch (err) {
        uni.showToast({
          title: '扫码失败',
          icon: 'none'
        })
      }
    },

    // 查询图书信息（免费公开接口）
    async getBookInfo() {
      uni.showLoading({ title: '查询中...' })
      
      try {
        this.bookData = {
          title: "活着",
          author: "余华",
          publisher: "人民文学出版社",
          pubdate: "2012-08-01",
          image: "https://qiniu.aiyxlib.com/1606124577077"
        };

        uni.hideLoading();
        uni.showToast({ title: "查询成功" });
        // const res = await uni.request({
        //   url: 'https://api.jike.xyz/situ/book/isbn/' + this.isbn,
        //   method: 'GET'
        // })
        
        // if (res.data.code === 200) {
        //   this.bookData = res.data.data
        //   uni.showToast({ title: '查询成功' })
        // } else {
        //   uni.showToast({ title: '未查询到图书信息', icon: 'none' })
        // }
      } catch (err) {
        uni.showToast({ title: '查询失败', icon: 'none' })
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 40rpx;
}
.scan-btn {
  margin-bottom: 40rpx;
}
.book-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.book-cover {
  width: 300rpx;
  height: 420rpx;
  margin-bottom: 20rpx;
  border: 1rpx solid #eee;
}
.book-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 15rpx;
}
.book-desc {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}
.empty {
  text-align: center;
  color: #999;
  margin-top: 100rpx;
}
</style>