//index.js

const HTTP = require("../../../requestFn/Api");

//获取应用实例
const app = getApp()
const {
  baseURL
} = app.globalData;
Page({
  data: {
    imgsrc: "/static/mine/view_face_background.png",
    src: "",
    windowWidth: 0,
    windowHeight: 0,
    canvasshow: true,
    access_token: '',
    userImage: "",
    cameraShow: true,
    tipsText: ""
  },
  onLoad(options) {
    var that = this
    const {
      garden_id
    } = options;
    that.setData({
      garden_id
    })
    wx.showLoading({
      title: '努力加载中',
      mask: true
    }) //屏幕宽度
    var sysInfo = wx.getSystemInfoSync();
    that.setData({
      windowWidth: sysInfo.windowWidth / 2,
      windowHeight: sysInfo.windowHeight / 2,
    })
    that.ctx = wx.createCameraContext();
    //每次更新access_token
    wx.request({
      url: "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + app.globalData.client_id + "&client_secret=" + app.globalData.client_secret,
      method: 'POST',
      dataType: "json",
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        app.globalData.access_token = res.data.access_token;
        that.setData({
          access_token: res.data.access_token
        });
        //打印access_token
        wx.hideLoading();
        // that.initData();
        that.start()
      }
    })

  },
  start() {
    this.setOwner();
    this.interval = setInterval(this.takePhoto, 5000);
  },
  init() {
    this.setData({
      cameraShow: true,
      canvasshow: false
    })
    this.start();
  },
  // initData() {
  //   wx.initFaceDetect();
  //   this.cameraEngine = wx.createCameraContext();
  //   // 3、获取 Camera 实时帧数据
  //   const listener = this.cameraEngine.onCameraFrame((frame) => {
  //     // 4、人脸识别，使用前需要通过 wx.initFaceDetect 进行一次初始化，推荐使用相机接口返回的帧数据
  //     wx.faceDetect({
  //       frameBuffer: frame.data,
  //       width: frame.width,
  //       height: frame.height,
  //       enablePoint: true,
  //       enableConf: true,
  //       enableAngle: true,
  //       enableMultiFace: true,
  //       success: async (faceData) => {
  //         console.log(faceData);
  //         let face = faceData.faceInfo[0]
  //         // if (face.x == -1 || face.y == -1) {
  //         //   this.tipsText = '检测不到人'
  //         // }
  //         // if (faceData.faceInfo.length > 1) {
  //         //   this.tipsText = '请保证只有一个人'
  //         // } else {
  //         //   const {
  //         //     pitch,
  //         //     roll,
  //         //     yaw
  //         //   } = face.angleArray;
  //         //   const standard = 0.5
  //         //   if (Math.abs(pitch) >= standard || Math.abs(roll) >= standard ||
  //         //     Math.abs(yaw) >= standard) {
  //         //     this.tipsText = '请平视摄像头'
  //         //   } else if (face.confArray.global <= 0.8 || face.confArray.leftEye <=
  //         //     0.8 || face.confArray.mouth <= 0.8 || face.confArray.nose <= 0.8 ||
  //         //     face.confArray.rightEye <= 0.8) {
  //         //     this.tipsText = '请勿遮挡五官'
  //         //   } else {
  //         //     if (this.isVerify) return
  //         //     //人脸位置校验
  //         //     var centerWidth = 250;
  //         //     var centerHeight = 250;
  //         //     if (face.x > (frame.width - centerWidth) / 2 && face.x < (frame
  //         //         .width - centerWidth) / 2 + centerWidth && face.y > (frame
  //         //         .height - centerHeight) / 2 && face.y < (frame.height -
  //         //         centerHeight) / 2 + centerHeight) {
  //         //       this.tipsText = '校验中...'
  //         //       this.isVerify = true;
  //         //       // 太快获取的人脸可能比较抽象,给用户一个准备时间
  //         //       // setTimeout(async () => {
  //         //       this.base64 = await this.changeDataToBase64(
  //         //         frame);
  //         //       this.searchUserFace();
  //         //       // }, 300)
  //         //     } else {
  //         //       this.tipsText = '请将人脸对准中心位置'
  //         //     }

  //         //   }
  //         // }
  //       },
  //       fail: (err) => {
  //         console.log(err);
  //         // if (this.isVerify) return
  //         // if (err.x == -1 || err.y == -1) {
  //         //   this.tipsText = '检测不到人'
  //         // } else {
  //         //   this.tipsText = err.errMsg || '网络错误，请退出页面重试'
  //         // }
  //       },
  //     })
  //   })
  //   // 5、开始监听帧数据
  //   listener.start()
  //   setTimeout(()=>{
  //     listener.stop()
  //   },2000)
  // },
  initData() {
    const session = wx.createVKSession({
      track: {
        plane: {
          mode: 3
        },
        face: {
          mode: 1
        }
      },
      version: 'v2',
    })
    this.setData({
      session
    })
    // 需要调用一次 start 以启动
    session.start(errno => {
      console.log("启动");
      if (!errno) {
        session.on('updateAnchors', anchors => {
          anchors.forEach(anchor => {
            console.log('anchor.points', anchor.points)
            console.log('anchor.origin', anchor.origin)
            console.log('anchor.size', anchor.size)
            console.log('anchor.angle', anchor.angle)
          })
        })

        // 当人脸从相机中离开时，会触发 removeAnchors 事件
        session.on('removeAnchors', () => {
          console.log('removeAnchors')
        })
      }
    })
    session.stop(res => {
      console.log("关闭");
      console.log(res);
    })
  },
  stop() {
    clearInterval(this.interval)
  },
  takePhoto() {
    var that = this;
    that.setText("")
    var takephonewidth
    var takephoneheight
    that.ctx.takePhoto({
      quality: 'medium',
      success(res) {
        let data = res;
        // 获取图片真实宽高
        wx.getImageInfo({
          src: res.tempImagePath,
          success(res) {
            takephonewidth = res.width;
            takephoneheight = res.height;
          }
        })
        wx.getFileSystemManager().readFile({
          filePath: res.tempImagePath, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success(res) {
            //成功的回调
            wx.request({
              url: "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=" + that.data.access_token,
              data: {
                image: res.data,
                image_type: "BASE64",
                max_face_num: 1,
                face_field: "eye_status,quality"
              },
              method: 'POST',
              dataType: "json",
              header: {
                'content-type': 'application/json'
              },
              success(res) {
                console.log(res.data);
                if (res.data.error_msg === "SUCCESS") {
                  let quality = res.data.result.face_list[0].quality;
                  let eye_status = res.data.result.face_list[0].eye_status
                  const {
                    left_eye,
                    right_eye,
                    nose,
                    mouth,
                    left_cheek,
                    right_cheek,
                    chin_contour
                  } = quality.occlusion;
                  const {
                    left_eye: left_eye1,
                    right_eye: right_eye1
                  } = eye_status;
                  const {
                    illumination
                  } = quality;
                  const location = res.data.result.face_list[0].location
                  const {
                    left,
                    top,
                    height,
                    width
                  } = location;
                  var x1 = left / takephonewidth * that.data.windowWidth;
                  var y1 = top / takephoneheight * that.data.windowHeight;
                  var sw = (width / takephonewidth * that.data.windowWidth);
                  var sh = (height / takephoneheight * that.data.windowHeight);
                  var centerX = x1 + sw * 0.5;
                  var centerY = y1 + sh * 0.5;
                  var screenX = that.data.windowWidth * 0.5;
                  var screenY = that.data.windowHeight * 0.5; //左右角度
                  var x = res.data.result.face_list[0].angle.yaw; //俯仰角度
                  var y = res.data.result.face_list[0].angle.pitch;
                  if (((x >= -12.0 && x <= 12.0) && (y >= -8.0 && y <= 15.0) && (sw <= that.data.windowWidth * 0.5 && sh <= that.data.windowHeight * 0.5)) && (((centerX >= screenX - 20.0) && (centerX <= screenX + 20.0)) && (centerY >= screenY - 80.0) && (centerY <= screenY + 80.0))) {
                    if (illumination < 20) {
                      that.setText("当前光线较弱")
                      return false
                    } else if (left_eye1 < 0.5 || right_eye1 < 0.5) {
                      that.setText("请保持双眼睁开")
                      return false
                    } else if (
                      left_eye > 0.2 || right_eye > 0.2 || nose > 0.2 || mouth > 0.2 || left_cheek > 0.2 || right_cheek > 0.2 || chin_contour > 0.2) {
                      that.setText("请勿遮挡五官")
                      return false
                    } else {
                      that.setData({
                        cameraShow: false,
                        canvasshow: true
                      })
                      that.drawImag(data);
                    }
                  } else {
                    that.setText("请将人脸对准中心位置")
                    return false
                  }
                } else if (res.data.error_msg === "pic not has face") {
                  that.setData({
                    tipsText: "未检测到人脸"
                  })
                }
              }
            })
          }
        })
      }
    })
  },
  upload() {
    var that = this;
    clearInterval(that.interval);
    const userInfo = wx.getStorageSync('userInfo')
    wx.uploadFile({
      filePath: that.data.userImage,
      name: 'file',
      url: baseURL + '/upload',
      header: {
        "token": userInfo.token
      },
      success(res) {
        const pic_url = JSON.parse(res.data).data;
        that.InputFace(pic_url);
      },
      fail(res) {
        console.log(res);
      }
    })
  },
  onUnload() {
    clearInterval(this.interval)
  },
  previewImage() {
    wx.previewImage({
      urls: [this.data.userImage],
    })
  },
  setOwner() {
    var timeStamp = Date.parse(new Date)
    this.setData({
      owner: timeStamp / 1000
    })
  },
  drawImag(data) {
    const that = this;
    const query = this.createSelectorQuery()
    query.select(`#canvas${this.data.owner}`).fields({
      node: true,
      size: true
    });
    query.exec((res) => {
      const canvas = res[0].node
      const ctx = canvas.getContext('2d')
      const dpr = wx.getSystemInfoSync().pixelRatio
      canvas.width = res[0].width * dpr
      canvas.height = res[0].height * dpr
      ctx.scale(dpr, dpr)
      let userImage = data.tempImagePath
      that.setData({
        userImage
      })
      const img = canvas.createImage()
      img.src = userImage
      img.onload = function () {
        ctx.drawImage(img, 0, 0, 100, 100)
      }
    })
  },
  setText(val) {
    this.setData({
      tipsText: val
    })
  },
 async InputFace(pic_url) {
    const {
      garden_id
    } = this.data;
   const {code} = await HTTP.Face({
      method: "post",
      garden_id: garden_id - 0,
      pic_url
    })
    if(code==0){
      wx.showToast({
        title: '上传成功',
        icon: 'success',
        duration: 2000,
      })
       setTimeout(() => {
         wx.navigateBack()
       }, 2000);
    }else{
      setTimeout(() => {
        wx.navigateBack()
      }, 2000);
    } 
  }
})