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

// const base64js = require('base64-arraybuffer');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    src:'https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg',
    height: 0,
    width: 0,
    showPage: '' // '' 为拍照 ，'error'为不通过，'success' 为通过
  },

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


  // 视频流(前端判断二维码)
  cameraFrame() {
    let flag = true
    const that = this
    const listener = this.cameraContext.onCameraFrame(async (frame) => {
      console.log(frame.width,frame.height);
      if (flag) {
        flag = false
        // 文件系统
        const fileSystem = wx.getFileSystemManager()
        that.setData({
          height: frame.height,
          width: frame.width
        })
        // 实时帧渲染到canvas
        // await wx.canvasPutImageData({
        //   canvasId: 'myCanvas',
        //   x:0,
        //   y:0,
        //   width: frame.width,
        //   height: frame.height,
        //   data: new Uint8ClampedArray(frame.data),
        // })
        // const fileData = await wx.canvasToTempFilePath({
        //   canvasId: 'myCanvas',
        //   x: frame.width / 4,
        //   y: frame.height / 4,
        //   width: frame.width / 2,
        //   height: frame.height / 3,
        //   quality: 'high',
        //   fileType: 'jpg',
        //   destWidth: frame.width / 2,
        //   destHeight: frame.height / 3,
        // })
        // const base = fileSystem.readFileSync(fileData.tempFilePath, 'base64')
        // console.log('qr_result',flag,5555,base);

        // const qr_result = await that.handleCodeAnalysis(base)
        // console.log('qr_result',flag,5555,qr_result.data);
        // 前端校验取消
        const data = new Uint8ClampedArray(frame.data);
        // // const nData = data.slice(data.length / 4, data.length / 4 * 3)
        const qian_result = qrcode.decodefrank(frame.width, frame.height, data)
        console.log('qe_result',qian_result,999)
        // console.log('qr_result.data.codeinfo',qr_result.data.codeinfo)
        if (qian_result) {
       
          // 原图（默认放大两倍）
          const photo1 = await that.handleTakePoto(that.cameraContext, 1)
          // 放大图（四倍）
          // await new Promise((resovle) => {
          //   setTimeout(() => {
          //     resovle()
          //   },300)
          // })
          console.log('5555');
          const photo2 = await that.handleTakePoto(that.cameraContext, 4,{flash:'on'})
          console.log(photo2.tempImagePath,'photo1');
          // this.setData({
          //   src:photo2.tempImagePath
          // })
          // 原图base64
          const base64_1 = fileSystem.readFileSync(photo1.tempImagePath, 'base64')
          // 放大四倍图 base64
          const base64_2 = fileSystem.readFileSync(photo2.tempImagePath, 'base64')

          // 请求接口
          Promise.all([that.handleApiCheck(base64_1,'small'), that.handleApiCheck(base64_2,'big')])
            .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 {
          setTimeout(() => {
            flag = true
          },750)
        }

      }
    })
    listener.start()
  },

  // 后端接口解析二维码
  handleCodeAnalysis(base64) {
    // console.log('base',base64)
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://www.7856.work:4433/api/Bym_upload/',
        method: 'POST',
        data: {
          base: base64,
          labelCodejson: 'BeiyinmeiAi'
        },
        success(res) {
          resolve(res)
        },
        fail(err) {
          reject(err)
        }
      })
    })
  },

  // 视频流拍照
  async handleTakePoto(context = this.cameraContext, zoom = 2, param) {
    await context.setZoom({
      zoom
    })
    if (zoom == 4) {
      await new Promise((resovle) => {
        setTimeout(() => {
          resovle()
        },300)
      })
    }
    return await context.takePhoto({
      flash:param?.flash || 'off',
      quality:'high',
      selfieMirror: param?.selfieMirror || false,
      // success(res) {
      //   console.log(res,zoom,222222);
      // }
    })
  },

  // 接口请求
  handleApiCheck(base64,type) {
    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,
          type
        },
        success(res) {
          resolve(res)
        },
        fail(err) {
          reject(err)
        }
      })
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})