// 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,
    frame: {},
    tag: false,
    showPage: '' // '' 为拍照 ，'error'为不通过，'success' 为通过
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.cameraContext = wx.createCameraContext()
    // this.cameraContext.setZoom({
    //   zoom: 1
    // })
    // this.cameraFrame()
    // this.cameraFrameApi()
    var nCounter = 0
    var that = this
    var tag = true
    this.ctx = wx.createCameraContext()
    this.listener = this.ctx.onCameraFrame((frame) => {
      if (nCounter == 25 && tag) {
        tag = false
        // if (this.data.tag) return
        // this.data.tag = true
        // setTimeout(() => {
        //   this.data.tag = false
        // }, 1000)
        this.setData({
          ['frame.width']: frame.width,
          ['frame.height']: frame.height
        })
        var data = new Uint8Array(frame.data)
        var clamped = new Uint8ClampedArray(data)
        wx.canvasPutImageData({
          canvasId: 'myCanvas',
          x: 0,
          y: 0,
          width: frame.width, //288  288
          height: frame.height, //512 381
          data: clamped,
          success: () => {
            wx.canvasToTempFilePath({
              canvasId: 'myCanvas',
              x: 0,
              y: (frame.height - frame.width) / 2,
              width: frame.width, //288
              height: frame.width, //352
              fileType: 'jpg',
              destWidth: frame.width,
              destHeight: frame.width,
              // 精度修改
              quality: 'high',
              success: (res) => {
                const base = wx
                  .getFileSystemManager()
                  .readFileSync(res.tempFilePath, 'base64')
                // console.log('base',base)
                that.setData({
                  src: res.tempFilePath
                })
                wx.request({
                  url: 'https://www.7856.work:4433/clear_fuzzy_detect/', //目标检测+判断清晰模糊接口 测试地址
                  // url: 'https://tj5.cc:4433/object/',
                  // url:'https://ai.china315net.com:35437/object/',
                  method: 'POST',
                  data: {
                    base
                  },
                  success: async (_res) => {
                    try {
                      var result = _res.data.result
                      var coord = _res.data.coord[0][5]
                      console.log('coord', coord)
                      var minindex = -1
                      var mindistance = 2
                      for (var i = 0; i < result.length; i++) {
                        var sublist = result[i]
                        var distance =
                          Math.abs(sublist[0] - 0.5) +
                          Math.abs(sublist[1] - 0.5)
                        if (distance < mindistance) {
                          mindistance = distance
                          minindex = i
                        }
                      }
                      var result_zy = result[minindex][0]
                      var result_sx = result[minindex][1]
                      var result_w = result[minindex][2]

                      var d_result_zy = result[minindex][0]
                      var d_result_sx = result[minindex][1]

                      var result_zoom = parseFloat((0.85 / result_w).toFixed(1))
                      that.setData({
                        result_zoom: result_zoom
                      })
                      let state = ''
                      let status = ''
                      let state_x = ''
                      console.log(888888888);
                      if (d_result_zy > 0.546 || d_result_zy < 0.445 || d_result_sx > 0.571 || d_result_sx < 0.45) {
                        console.log(666666);
                      
                      
                        console.log('识别二维码成功');
                        // 原图（默认放大两倍）
                        const photo1 = await that.handleTakePoto(wx.createCameraContext(), 1)
                        // 放大图（四倍）
                        // await new Promise((resovle) => {
                        //   setTimeout(() => {
                        //     resovle()
                        //   },300)
                        // })
                        console.log('5555');
                        const photo2 = await that.handleTakePoto(wx.createCameraContext(), 4, {
                          flash: 'on'
                        })
                        console.log(photo2.tempImagePath, 'photo1');
                        // this.setData({
                        //   src:photo2.tempImagePath
                        // })
                        // 原图base64
                        const base64_1 = wx
                          .getFileSystemManager().readFileSync(photo1.tempImagePath, 'base64')
                        // 放大四倍图 base64
                        const base64_2 = wx
                          .getFileSystemManager().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 {
                      tag = true
                      wx.showToast({
                        title: '请把识别二维码对准拍照框',
                      })

                    }
                    } catch (error) {
                      tag = true
                      wx.showToast({
                        title: '请把识别二维码对准拍照框',
                      })
                    }
                  },
                  fail(err) {
                    tag = true
                    console.log(err);
                  }
                })
              },
              fail: (error) => {
                console.log('转换临时文件失败:', error)
              }
            })
          },
          fail: (error) => {
            console.log('绘制图像数据失败', error)
          }
        })
      }
      nCounter++
      if (nCounter >= 50) {
        nCounter = 0
      }
    }, 100)
    this.listener.start()
  },


  // 视频流(前端判断二维码)
  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: -frame.width / 4,
          y: -frame.height / 4,
          width: frame.width,
          height: frame.height,
          data: new Uint8ClampedArray(frame.data),
        })
        const fileData = await wx.canvasToTempFilePath({
          canvasId: 'myCanvas',
          x: 0,
          y: 0,
          width: frame.width,
          height: frame.height,
          quality: 'high',
          fileType: 'jpg',
          destWidth: frame.width,
          destHeight: frame.height,
        })

        this.setData({
          src: fileData.tempFilePath
        })
        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 (qr_result.data.codeinfo) {

          // 原图（默认放大两倍）
          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() {

  }
})