const app = require('../../utils/util.js');
var util = require('../../utils/md5.js')
import WxValidate from '../../utils/WxValidate';
var QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js');
Page({
  data: {
    time: '',
    lng: '', // 经度
    lat: '', // 纬度
    visitLocation: '',
    info: '', //老人锕
    imgPath: [{}, {}],
    isTrue: true,
    index: 0,
    visitPhoto: '',
    infoId: '',
  },
  // 老人点击后去跳转采集页面
  oldClick(e) {
    let fid = e.currentTarget.dataset.infos.fid;
    let name = e.currentTarget.dataset.infos.name;
    const app = getApp()
    app.globalData.id = fid
    app.globalData.name = name
    wx.switchTab({
      url: `/pages/collectInfo/collectInfo`,
      success: function (e) {
        var page = getCurrentPages().pop();
        if (page == undefined || page == null) return;
        page.onLoad();
      }
    })
  },
  // 获得当前时间
  time() {
    var timestamp = Date.parse(new Date());
    var date = new Date(timestamp);
    //获取年份  
    var Y = date.getFullYear();
    //获取月份  
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //获取当日日期 
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    this.setData({
      time: Y + '-' + M + '-' + D
    })
  },
  // 选择照片上传并后台接口
  zhaopian() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success: (res) => {
        var tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: app.globalData.publicUrl + '/sys/user/upload',
          filePath: tempFilePaths[0],
          name: 'uploadFile',
          formData: {
            "user": "test",
          },
          header: {
            appletsId: wx.getStorageSync('openId'),
          },
          success: (res) => {
            console.log(JSON.parse(res.data), "45454545");
            let datas = JSON.parse(res.data)
            wx.request({
              url: app.globalData.publicUrl + '/user/getPeople',
              method: "POST",
              header: {
                appletsId: wx.getStorageSync('openId')
              },
              data: {
                photoPath: datas.data
              },
              success: (res) => {
                console.log(res, '有没有face')
                if (res.data.code == 0) {
                  if (datas.code == 0) {
                    if (this.data.imgPath.length < 3) {
                      this.data.imgPath.push(datas.data)
                      this.setData({
                        imgPath: this.data.imgPath
                      })
                      this.data.visitPhoto = this.data.imgPath.join(',')
                      if (this.data.imgPath.length == 2) {
                        this.setData({
                          isTrue: false
                        })
                      }
                    }
                  }
                } else {
                  wx.showToast({
                    title: '人脸识别不通过，请重新上传',
                    icon: 'none',
                    duration: 3000,
                  })
                }
              }
            })
          }
        })
      }
    })
  },
  // 删除照片 
  closeImage(e) {
    console.log(e.currentTarget.dataset.index, "00");
    this.data.imgPath.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      imgPath: this.data.imgPath,
    })
    let aa = this.data.imgPath.join(',')
    this.setData({
      visitPhoto: aa,
    })
    if (this.data.imgPath.length == 0 || this.data.imgPath.length == 1) {
      this.setData({
        isTrue: true
      })
    }
    console.log(this.data.imgPath, "00000000000");
  },
  //提交(表单验证)
  formSubmit(e) {
    console.log(e.detail, "daying");
    /***4-3(表单提交校验)*/
    const params = e.detail.value
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    /*** 这里添写验证成功以后的逻辑**/
    //验证通过以后->
    this.submitInfo(params);
  },
  // 真正提交  人脸比对
  submitInfo(params) {
    console.log(params);
    console.log(this.data.visitPhoto, "照片");
    console.log(this.data.infoId);
    wx.showLoading({
      title: '加载中',
    })
    if (this.data.visitPhoto.length > 0) {
      let obj = {};
      obj = {
        ...params,
        infoId: this.data.infoId,
        visitPhoto: this.data.visitPhoto,
        lat: this.data.lat,
        lng: this.data.lng,
        visitLocation: this.data.visitLocation
      }
      // 比对接口
      wx.request({
        url: app.globalData.publicUrl + '/visit/doFace3',
        method: "POST",
        header: {
          appletsId: wx.getStorageSync('openId')
        },
        data: {
          infoId: this.data.infoId,
          visitPhoto: this.data.visitPhoto,
        },
        success: (res) => {
          // 如果上传不是人脸图片 则没有score
          console.log(res)
          if (res.data && res.data.data && res.data.data.score) {
            console.log(res.data.data.score, "分数是");
            if (res.data.data.score > 80) {
              console.log("比对成功了");
              //提交的接口 
              wx.request({
                url: app.globalData.publicUrl + '/visit/add',
                method: "POST",
                header: {
                  appletsId: wx.getStorageSync('openId')
                },
                data: obj,
                success: (res) => {
                  if (res.data.code == 0) {
                    wx.hideLoading();
                    wx.showModal({
                      showCancel: false,
                      content: '提交成功',
                      success() {
                        wx.switchTab({
                          url: '/pages/index/index',
                        })
                      }
                    })
                  } else if (res.data.code == 1) {
                    wx.showModal({
                      showCancel: false,
                      content: res.data.message,
                      success() {
                        wx.switchTab({
                          url: '/pages/index/index',
                        })
                      }
                    })
                  }
                }
              })
            } else {
              wx.showToast({
                title: '人脸比对相似度过低，请重新拍照!',
                icon: 'none',
                duration: 2000,
              })
            }
          } else {
            wx.showToast({
              title: '人脸比对失败,请传老人现场照片',
              icon: 'none',
              duration: 2000,
            })
          }
        }
      })
    } else {
      wx.showToast({
        title: '请上传现场照片',
        icon: 'none',
        duration: 2000,
      })
    }
  },
  showModal(error) {
    wx.showToast({
      title: error.msg,
      icon: 'none',
      duration: 2000,
    })
  },

  //获取位置
  getSelfLocation: function (varSendOrgId) {
    console.log(this.data.info, "老人的信心呢锕");
    // 拿到老人照片中采集时候的定位
    let split = this.data.info.photoAndLocation.split("/");
    let lon = parseFloat(split[0])
    let lat = parseFloat(split[1])
    // 实例化API核心类
    var qqmapsdk = new QQMapWX({
      key: 'B5DBZ-NGIHP-SQMD4-LHMG3-NJ72Z-7KFOV' //申请的开发者秘钥key
    });
    wx.getLocation({
      //type: 'wgs84',
      type: 'gcj02',
      success: (res) => {
        console.log(res, "0000000");
        // 返回当前定位的经纬度
        var latitude = parseFloat(res.latitude).toFixed(5);
        var longitude = parseFloat(res.longitude).toFixed(5);
        this.setData({
          lng: longitude, //经度
          lat: latitude, //纬度        
        });
        // 判断距离
        qqmapsdk.calculateDistance({
          mode: 'walking', //步行，驾车为'driving'
          to: [{
            latitude: lat,
            longitude: lon
          }, {
            latitude: latitude,
            longitude: longitude
          }],
          success: (res) => {
            console.log(res.result.elements[0].distance, "距离的");
            if (res.result.elements[0].distance > 1000) {
              wx.showModal({
                showCancel: false,
                content: '当前位置超出老人家范围,请重新扫码定位',
                success() {
                  wx.switchTab({
                    url: '/pages/index/index',
                  })
                }
              })
            }
          },
        })
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: (res) => {
            //获取当前地址成功
            console.log(res, "为是都是都是");
            this.setData({
              visitLocation: res.result.address
            })
          },
          fail: function (res) {
            console.log('获取当前地址失败');

          }
        });
      },
      fail: function (res) {

      }
    });
  },
  // 获取当前扫码老人的id 
  oldsInfo(id) {
    wx.request({
      url: app.globalData.publicUrl + '/info/one',
      method: "GET",
      header: {
        appletsId: wx.getStorageSync('openId')
      },
      data: {
        id: id
      },
      success: (res) => {
        console.log(res, "777777");
        if (res.data.code == 0) {
          this.setData({
            info: res.data.data
          })
          // 去定位
          this.getSelfLocation();
        } else {
          wx.showModal({
            showCancel: false,
            content: '查询失败,当前二维码过期或失效',
            success() {
              wx.switchTab({
                url: '/pages/index/index',
              })
            }
          })

        }
      }
    })
  },
  // 表单验证规则
  initValidate() {
    const rules = {
      health: {
        required: true,
      },
      mind: {
        required: true,
      },
      security: {
        required: true,
      },
      hygiene: {
        required: true,
      },
      live: {
        required: true,
      },
      demand: {
        required: true,
      },
      visitMessage: {
        required: true,
      },
      urgency: {
        required: true,
      }
    };
    const messages = {
      health: {
        required: '请选择健康状况',
      },
      mind: {
        required: '请选择精神状态',
      },
      security: {
        required: '请选择安全情况',
      },
      hygiene: {
        required: '请选择卫生环境',
      },
      live: {
        required: '请选择居住环境',
      },
      visitMessage: {
        required: '请输入备注说明',
      },
      demand: {
        required: '请输入老人需求',
      },
      urgency: {
        required: '请选择需求紧急程度',
      }
    };
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },
  onLoad: function (opotions) {
    console.log(opotions, "dayin");
    // 获得当前时间
    this.time();
    // 扫码传参 获得老人的id 
    this.oldsInfo(opotions.id);
    this.setData({
      imgPath: [],
      infoId: opotions.id
    })
    console.log(this.data.imgPath, "照片啊锕  锕啊 ");
    this.initValidate();
  },
})