// pages/fenggu/takephoto/takephoto.js
var util = require('../../../utils/util')
var Counter = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 验证步骤
    stepIndex: 0,

    // tab切换（AI验证，示范切换）
    tabIndex: 1,
    windowWidth:'',
    windowHeight:'',
    result_zoom: 0,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getBaseTakePhoto()
  },

//获取
getBaseTakePhoto(){
  var that = this
  var nCounter = 0
  const {
    screenWidth,
    screenHeight
  } = wx.getSystemInfoSync()
  const windowWidth = 750
  const windowHeight = screenHeight / screenWidth * windowWidth
  this.setData({
    windowWidth,
    windowHeight,
  })
  // console.log('wind', windowWidth, 'height', windowHeight)
  this.ctx = wx.createCameraContext()
  this.listener = this.ctx.onCameraFrame((frame) => {
    if (nCounter == 25) {
      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);
      // console.log('data', data)
      var clamped = new Uint8ClampedArray(data);
      // console.log('clamped', clamped)
      // 实时帧数据添加到Canvas上
      // console.log('===========')
      wx.canvasPutImageData({
        canvasId: 'myCanvas',
        x: 0,
        y: 0,
        width: frame.width, //288  288 
        height: frame.height, //512 381 
        data: clamped,
        success: (res) => {
          // 转换临时文件 
          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) => {
              // console.log('成功成功成功')
              //进行编码
              const base = wx.getFileSystemManager().readFileSync(res.tempFilePath, 'base64')
              // console.log('base',base)
              that.setData({
                src: res.tempFilePath
              });
              wx.request({
                url: 'https://ai.tj5.cc:35437/object/',
                // url: 'https://tj5.cc:4433/object/',
                // url:'https://ai.china315net.com:35437/object/',
                method: "POST",
                data: {
                  base
                },
                success: (res) => {
                  var result = res.data.result;
                  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 result_zoom = parseFloat((0.85 / result_w).toFixed(1))
                    console.log('result_zoom',result_zoom)
                    console.log('result_w',result_w)
                  if (result_zy > 0.588) { //0.568
                    state = 'left'
                  } else if (result_zy < 0.405) { //0.425
                    state = 'right'
                  } else if (result_sx > 0.577) { //0.547
                    state = 'on'
                  } else if (result_sx < 0.401) { //0.411
                    state = 'down'
                  } else {
                    let text = '大框参数已经完善'
                    var take_Count = 0;
                    // console.log('大框参数已经完善', text)
                    let singe_state = true
                    take_Count++,
                    wx.removeStorageSync('singe_state')
                    that.setData({
                      singe_state,
                      small_finish: true
                    })
                    status = 'true'
                    if (text === text && that.data.stepIndex === 0  ) {
                      console.log('大框参数完成进行拍照')
                      that.takePhoto();
                      let takephoto = 'succes'
                      that.setData({
                        takephoto,
                        stepIndex:1
                      })
                      console.log('that.data.takephoto', that.data.takephoto)
                    }
                    //新修改
                    else if (that.data.takephoto === 'succes' && that.data.stepIndex ===1 ) {
                      console.log('进入小框判断')
                      var result = res.data.result;
                      var d_result_zy = result[minindex][0];
                      var d_result_sx = result[minindex][1];
                      if (d_result_zy > 0.546) { //0.546
                        state_x = 'left'
                      } else if (d_result_zy < 0.445) { //0.445
                        state_x = 'right'
                      } else if (d_result_sx > 0.571) { //0.531
                        state_x = 'on'
                      } else if (d_result_sx < 0.450) { //0.410
                        state_x = 'down'
                      } else {
                        console.log('全部完成')
                        that.takePhoto2()
                        that.listener.stop()
                      }
                    } else {
                      console.log('拍照失败')
                      // that.takePhoto2()
                    }
                  }
                },
                fail: (error) => {
                  console.log('目标检测失败', error)
                }
              })
            },
            fail: (error) => {
              console.log('转换临时文件失败:', error);
            }
          }, that)
        },
        fail: (error) => {
          console.log('绘制图像数据失败', error)
        }
      })
    }
    nCounter++
    if (nCounter >= 50) {
      nCounter = 0
    }
  }, 100)
  this.listener.start()
},

  takePhoto: function () {
    // console.log('takePhoto')
    var that = this
    Counter++;
    that.ctx.setZoom({
      zoom: 1.0,
      success: (res) => {
        setTimeout(() => {
          that.ctx.takePhoto({
            quality: 'high', //高质量
            flash: 'off',
            success: (res) => {
              /*储存 */
              const base = wx.getFileSystemManager().readFileSync(res.tempImagePath, 'base64')
              // console.log('base',base)
              // console.log('开始解析')
              // wx.request({
              //   url: 'https://ai.tj5.cc:35437/api/small_upload/',
              //   method: 'POST',
              //   data: {
              //     base,
              //     'labelCodejson': this.data.labelCode
              //   },
              //   success: (res) => {
              //     var dtime = util.formatTime(new Date)
              //     wx.setStorage({
              //       key: 'dtime',
              //       data: dtime
              //     })
              //     var res_data = res.data
              //     var succes_data = res_data.succes
              //     if (res_data === '码解析失败' || succes_data === 'loser' || res.statusCode !== 200) {
              //       const datajson = '码解析失败'
              //       wx.setStorage({
              //         key: 'datajson',
              //         data: datajson
              //       })
              //     } else {
              //       var img_reader = res_data.img_reader
              //       wx.setStorage({
              //         key: 'img_reader',
              //         data: img_reader
              //       })
              //       var img_method = res_data.img_method
              //       wx.setStorage({
              //         key: 'img_method',
              //         data: img_method
              //       })
              //       var points = res_data.points
              //       wx.setStorage({
              //         key: 'points',
              //         data: points
              //       })
              //       var datajson = res_data.codeinfo;
              //       wx.setStorage({
              //         key: 'datajson',
              //         data: datajson
              //       })
              //     }
              //   },
              //   fail: (res) => {
              //     if (res.errMsg.indexOf('timeout') !== -1) {
              //       const datajson = '码解析失败'
              //       wx.setStorage({
              //         key: 'datajson',
              //         data: datajson
              //       })
              //     }
              //   },
              //   complete: (res) => {
              //     if (!res.data) {
              //       const datajson = '码解析失败'
              //       wx.setStorage({
              //         key: 'datajson',
              //         data: datajson
              //       })
              //     }
              //   },
              //   timeout: 3000
              // })
              //新增请求接口
              wx.request({
                url: 'https://ai.tj5.cc:35437/classify16/',
                method: "POST",
                data: {
                  'image_type': 20,
                  'base': base,
                },
                success: (res) => {
                  let result_value = res.data.result
                  let yuan_file = res.data.image_path
                  wx.setStorage({
                    key: 'yuan_file',
                    data: yuan_file
                  })
                  if (result_value == 14) {
                    let hint_phone = result_value
                    this.setData({
                      hint_phone
                    })
                    wx.setStorage({
                      key: 'hint_phone',
                      data: hint_phone
                    })
                  } else {
                    let hint_phone = result_value
                    wx.setStorage({
                      key: 'hint_phone',
                      data: hint_phone
                    })
                  }
                },
                fail: error => {
                  console.log('调用upload失败', error)
                }
              });
              var dtime_2 = util.formatTime(new Date)
              wx.setStorage({
                key: 'dtime_2',
                data: dtime_2
              })
            }
          })
        }, 350);
      }
    })
  },


  takePhoto2: function () {
    // console.log('takePhoto2')
    const that = this;
    function isIOS() {
      let system = wx.getSystemInfoSync().system
      return system.indexOf('iOS') !== -1
    }
    if (isIOS()) {
      console.log('ios')
      if (this.data.result_zoom === 0) {
        this.setData({
          result_zoom: 4
        })
      }
      console.log('this.data.result_zoom',this.data.result_zoom)
      that.ctx.setZoom({
        zoom: this.data.result_zoom,
        success: res => {
          const takephoto2_state = res.errMsg;
          this.setData({
            takephoto2_state,
          });
          setTimeout(() => {
            that.ctx.takePhoto({
              quality: 'high',
              flash: 'on',
              success: res => {
                wx.setStorage({
                  key: 'originalImagePath',
                  data: res.tempImagePath,
                });
                this.setData({
                  bigfileimage: res.tempImagePath,
                  stepIndex:2
                });
                wx.redirectTo({
                  url: '../../upload/upload?path=' + that.data.bigfileimage + '&char=0'
                });
              },
              fail: err => {
                console.error('拍照失败', err);
                that.takePhoto2()
              }
            });
          })
        },
        fail: err => {
          console.error('设置缩放失败', err);
        }
      });
    } else {
      if (this.data.result_zoom === 0) {
        this.setData({
          result_zoom: 6
        })
      }
      const one_zoom = parseFloat((this.data.result_zoom * 0.82).toFixed(1));
      const benchmarkLevel = (wx.getStorageSync('benchmarkLevel') || 0)
      const phone_model = (wx.getStorageSync('phone_model') || '')
      let timeS;
      let  phone_list= ['NOH-AN00','NOH-AN01','OCE-AN10','JAD-AL00','LNA-AL00','NOP-AN00','NOH-AL10','ABR-AL80','MNA-AL00','JAD-AL50','ABR-AL00','ABR-AL90','ABR-AL60','ABR-AL60','NOH-AN50']
      if(phone_list.includes(phone_model)){
        timeS = 850
      }
      else if (benchmarkLevel > 40) {
        timeS = 350;
      } else if (benchmarkLevel > 30) {
        timeS = 380;
      } else if (benchmarkLevel > 20) {
        timeS = 410
      } else if (benchmarkLevel > 10) {
        timeS = 450;
      } else {
        timeS = 450;
      }
      this.takePhotoZoom(one_zoom, timeS)
    }

  },
  takePhotoZoom: function (one_zoom,timeS) {
    console.log('one_zoom',one_zoom)
    console.log('timeS',timeS)
    var that = this
    that.ctx.setZoom({
      zoom: one_zoom,
      success: (res) => {
        console.log('res.zoom  成功', res.zoom)
        setTimeout(() => {
          that.ctx.takePhoto({
            quality: 'high', //高质量
            flash: 'off',
            success: (res) => {
              console.log('放大拍照日志res', res)
              /*储存 */
              wx.setStorage({
                key: 'originalImagePath',
                data: res.tempImagePath,
              })
              wx.setStorage({
                key: 'one_zoom',
                data: one_zoom
              });
              this.setData({
                bigfileimage: res.tempImagePath,
                result_zoom: this.data.result_zoom
              })

              wx.navigateTo({
                url: '../../upload/upload?path=' + that.data.bigfileimage + '&char=0'
              })
            },
            fail: (err) => {
              console.error('拍照失败2', err);
              that.takePhoto2()
            }
          })
        }, timeS);
      },
      fail: err => {
        console.error('设置缩放失败', err);
      }
    })

  },


  // ai验证，示范tab切换
  tabChange(e) {
    const tindex = e.target.dataset?.tindex || 1
    // this.setData({
    //   tabIndex:tindex
    // })
    // 跳转示例页面
    if (tindex == 2) {
      wx.navigateTo({
        url: '/pages/fenggu/example/example'
      })
    }
  },


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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})


