
var app = getApp()
var api = require('../../utils/api.js');

const SEC = 1000
const MIN = 60 * SEC
const HOUR = 60 * MIN
Page({
  data: {
    currentLatitude: 0,     //用户当前纬度
    currentLongitude: 0,    //用户当前经度
    is_btn_disabled: true,  //开始按钮状态
    locationAccuracy: 0,    //gps 误差
    isLearning: false,      //是否在学习中？
    startTime: null,        //开始时间
    clock: '00:00:00',      //计时
    shareCanvasWidth: 200,
    shareCanvasHeight: 280,
    shareImage: '',
    shareText: '',
    shareTextPosX: '',
    shareTextPosY: '',
    shareTempFilePath: '',
    showPopup: false
  },
  onLoad: function () {
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          screenWidth: res.screenWidth,
          screenHeight: res.screenHeight,
          bannerWidth: res.screenWidth,
          bannerHeight: res.screenWidth * 363 / 543
        })
      }
    })
    var pt_student = wx.getStorageSync('pt_student')
    if (!pt_student) {
      var we_chat_user = wx.getStorageSync('we_chat_user')
      if(we_chat_user) {
        wx.redirectTo({
          url: '/pages/bind-phone/index',
        })
      } else {
        wx.redirectTo({
          url: '/pages/login/index',
        })
      }
    } else {
      app.globalData.ptStudent = pt_student;
    }

    wx.getLocation({
      success: (res) => {
        // let validLocation = this.validLocation(res.latitude, res.longitude)
        wx.request({
          url: api.checkPositionUrl,
          method: 'GET',
          data: {
            latitude: res.latitude,
            longitude: res.longitude,
            student_id: pt_student.id
          },
          success: res => {
            let validLocation = false;
            if (res.data.status == 'success' && res.data.result == 'ok') {
              validLocation = true;
            } else {
              validLocation = api.isTest ? true : false;
            }
            this.setData({
              is_btn_disabled: !validLocation
            })
            if(validLocation) {
              var start_time = wx.getStorageSync('check_card_start_time')
              if(start_time) {
                this.setData({
                  startTime: start_time,
                  isLearning: true
                })
                this.startClock()
              }
            }
          },
        });
        this.setData({
          currentLatitude: res.latitude,
          currentLongitude: res.longitude,
          accuracy: res.accuracy
        })

      }
    })

    wx.request({
      url: api.getShareInfoUrl,
      method: 'GET',
      data: {
        'student_id': pt_student.id
      },
      success: res => {
        if (res.data.status == 'success') {
          this.setData({
            shareCanvasWidth: res.data.width,
            shareCanvasHeight: res.data.height,
            shareImage: res.data.shareImage,
            shareText: res.data.shareText,
            shareTextPosX: res.data.shareTextPosX,
            shareTextPosY: res.data.shareTextPosY,
          })
          wx.downloadFile({
            url: res.data.shareImage,
            success: res => {
              this.setData({
                shareImage: res.tempFilePath
              })
            }
          })
        }
      }
    })
  },
  validLocation(latitude, longitude) {
    let res = api.isTest ? true : false;
    wx.request({
      url: api.checkPositionUrl,
      method: 'GET',
      data: {
        latitude: latitude,
        longitude: longitude
      },
      success: res => {
        if(res.data.status == 'success' && res.data.result == 'ok') {
          res = true;
        }
      }
    });
    return res;
  },
  hidePhotoPopup() {
    this.setData({
      showPopup: false,
      clock: '00:00:00'
    })
  },
  handleBtnClick() {
    wx.getLocation({
      success: (res) => {
        // let validLocation = this.validLocation(res.latitude, res.longitude)
        wx.request({
          url: api.checkPositionUrl,
          method: 'GET',
          data: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: res => {
            let validLocation = false;
            if (res.data.status == 'success' && res.data.result == 'ok') {
              validLocation = true;
            } else {
              validLocation = api.isTest ? true : false;
            }
            this.setData({
              is_btn_disabled: !validLocation
            })
            this.checkCard()
          },
        });
      }
    })
  },
  checkCard: function() {
    let isLearning = this.data.isLearning
    let is_btn_disabled = this.data.is_btn_disabled
    let that = this;
    if (is_btn_disabled) {
      wx.showToast({
        title: '请到学校之后再打卡',
        icon: 'none',
        duration: 800
      })
      return;
    }
    if (isLearning) {
      let check_card_id = wx.getStorageSync('check_card_id');
      wx.request({
        url: api.endCheckCardUrl,
        method: 'GET',
        data: {
          'check_card_id': check_card_id
        },
        success: res => {
          if (res.data.status == 'success') {
            that.setData({
              isLearning: !isLearning
            })
            that.endClock()
          } else {
            wx.showToast({
              title: res.data.info,
              icon: 'none',
              duration: 800
            })
          }
        }
      })
    } else {
      wx.request({
        url: api.startCheckCardUrl,
        method: 'GET',
        data: {
          'student_id': app.globalData.ptStudent.id
        },
        success: res => {
          if (res.data.status == 'success') {
            wx.setStorageSync('check_card_id', res.data.check_card_id)
            var start_time = new Date().getTime()
            wx.setStorageSync('check_card_start_time', start_time)
            that.setData({
              isLearning: !isLearning,
              startTime: start_time
            })
            that.startClock()
          } else {
            wx.showToast({
              title: res.data.info,
              icon: 'none',
              duration: 800
            })
          }
        }
      })
    }
  },
  startClock() {
    let interval = setInterval(() => {
      let now = new Date().getTime()
      let startTime = this.data.startTime

      let diff = now - startTime
      let hours = Math.floor(diff / HOUR)
      hours = (hours < 10 ? '0' + hours : hours)

      diff = diff % HOUR
      let mins = Math.floor(diff / MIN)
      mins = (mins < 10 ? '0' + mins : mins)

      diff = diff % MIN
      let sec = Math.ceil(diff / SEC)
      sec = (sec < 10 ? '0' + sec : sec)

      
      this.setData({
        clock: "" + hours + ":" + mins + ":" + sec
      })
    }, SEC)
    this.interval = interval
  },
  endClock() {
    clearInterval(this.interval)
    this.setData({
      isLearning: false,
      showPopup: true
    })
    wx.setStorageSync('check_card_start_time', '')
    const ctx = wx.createCanvasContext('shareCanvas')
    let width = this.data.shareCanvasWidth
    let height = this.data.shareCanvasHeight
    let image = this.data.shareImage
    let text = this.data.shareText
    let text_x = this.data.shareTextPosX
    let text_y = this.data.shareTextPosY
    // ctx.fillStyle = "#fff"
    // ctx.fillRect(0, 0, width, height)
    ctx.drawImage(image)
    ctx.fillStyle = "#fff"
    ctx.setFontSize(24)
    ctx.textAlign = 'center'
    // ctx.fillText('我已成功打卡14天', width / 2, height / 2 - 7)
    ctx.fillText(text, text_x, text_y)
    ctx.draw(false, this.getTempFilePath)
  },
  togglePopup() {
    this.setData({
      showPopup: !this.data.showPopup
    });
  },
  getTempFilePath: function () {
    wx.canvasToTempFilePath({
      canvasId: 'shareCanvas',
      success: (res) => {
        this.setData({
          shareTempFilePath: res.tempFilePath
        })
      }
    })
  },
  handleShare() {
    // wx.canvasToTempFilePath({
    //   canvasId: 'shareCanvas',
    //   success: (res) => {
    //     wx.saveImageToPhotosAlbum({
    //       filePath: res.tempFilePath,
    //       success: () => {
    //         wx.showToast({
    //           title: '已保存到相册'
    //         })
    //       }
    //     })
    //   }
    //   }, this)
    if (!this.data.shareTempFilePath) {
      wx.showModal({
        title: '提示',
        content: '图片绘制中，请稍后重试',
        showCancel: false
      })
    }
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareTempFilePath,
      success: (res) => {
        // this.setData({
        //   showPopup: false
        // })
      },
      complete: res => {
        this.setData({
          showPopup: false,
          clock: '00:00:00'
        })
      }
    })
  },
  onShareAppMessage: function (t) {
    var a = this;
    return {
      path: "/pages/index/index",
      success: function (t) {
      },
      title: "钢琴时间打卡"
    };
  },
  
})
