// pages/beiyinmei/beiyinmei.js
import qrcode, {
  height
} from '../../utils/llqrcodefrankyin.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    height: 0,
    width: 0,
    showPage: ''  // '' 为拍照 ，'error'为不通过，'success' 为通过
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.cameraContext = wx.createCameraContext()
    this.cameraContext.setZoom({
      zoom: 2
    })
    this.cameraFrame()
    // this.cameraFrameApi()
  },

  // 视频流（后端校验二维码）
  cameraFrameApi() {
    let flag = true
    const that = this
    const listener = this.cameraContext.onCameraFrame((frame) => {
      if (flag) {
        flag = false
        that.setData({
          width: frame.width,
          height: frame.height,
        })
        wx.canvasPutImageData({
          canvasId: 'myCanvas',
          width: frame.width,
          height: frame.height,
          data: new Uint8ClampedArray(frame.data),
          success(rew) {
            console.log(rew, 99);
            wx.canvasToTempFilePath({
              canvasId: 'myCanvas',
              x: frame.width / 2 - 150,
              y: frame.height / 2 - 150,
              width: 300,
              height: 300,
              destWidth: 300,
              destHeight: 300,
              quality: 'high',
              fileType: 'jpg',
              success(path) {
                console.log(path.tempFilePath, 66);
                const base = wx.getFileSystemManager().readFileSync(path.tempFilePath, 'base64')
                that.setData({
                  src: 'data:image/jpeg;base64,' + base
                })
                wx.request({
                  url: 'https://ai.tj5.cc:35437/object/',
                  method: "POST",
                  data: {
                    base
                  },
                  success(g) {
                    console.log(g, 'cccc');
                    flag = true
                  }
                })
              },
              fail(rr) {
                console.log(rr, 5555);
              }
            })
          },
          fail(err) {
            console.log(err);
          }
        })
      }
    })
    listener.start()
  },

  // 视频流(前端判断二维码)
  cameraFrame() {
    let flag = true
    const that = this
    const listener = this.cameraContext.onCameraFrame(async (frame) => {
      if (flag) {
        flag = false
        const data = new Uint8ClampedArray(frame.data);
        // const nData = data.slice(data.length / 4, data.length / 4 * 3)
        const qr_result = qrcode.decodefrank(frame.width, frame.height, data)
        if (qr_result) {
          that.setData({
            height: frame.height,
            width: frame.width
          })
          // 文件系统
          const fileSystem = wx.getFileSystemManager()
          // 原图（默认放大两倍）
          const photo1 = await that.handleTakePoto()
          // 放大图（四倍）
          const photo2 = await that.handleTakePoto(that.cameraContext, 4)

          // 原图base64
          const base64_1 = fileSystem.readFileSync(photo1.tempImagePath, 'base64')
          // 放大四倍图 base64
          const base64_2 = fileSystem.readFileSync(photo2.tempImagePath, 'base64')

          // 请求接口
          Promise.all([that.handleApiCheck(base64_1), that.handleApiCheck(base64_2)])
            .then(value => {
              let pageType = 'error'
              const result1 = value[0],result2 = value[1]
              // data.result  == 2 为真
              if (result1.data.result == 2 && result2.data.result == 2) {
                pageType = 'success'
              }
              that.setData({
                showPage:pageType
              })
            })
        } else {
          flag = true
        }

      }
    })
    listener.start()
  },

  // 视频流拍照
  async handleTakePoto(context = this.cameraContext, zoom = 2, param) {
    await context.setZoom({
      zoom
    })
    return await context.takePhoto({
      quality: param?.quality || 'high',
      selfieMirror: param?.selfieMirror || false,
    })
  },

  // 接口请求
  handleApiCheck(base64) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://www.7856.work:4433/api/Bym_classfily_post/',
        method: 'POST',
        data: {
          device_id: '50',
          base: base64
        },
        success(res) {
          resolve(res)
        },
        fail(err) {
          reject(err)
        }
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})