// pages/addtrainimg/addtrainimg.js
const app = getApp();
function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'undefined' || time === null || time === 'null') {
    return ''
  } else if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    briefIntroduction: '',
    trainSum: 0,
    trainLocation: '',
    trainDate: '',
    trainTime: '',
    trainbeforeImg: '',
    trainingImg: '',
    trainafterImg: '',
    trainbeforeImgBase64: '',
    trainingImgBase64: '',
    trainafterImgBase64: '',
    trainbeforeImgExtension: '',
    trainingImgExtension: '',
    trainafterImgExtension: '',
    trainbeforeImgLocation: '',
    trainingImgLocation: '',
    trainafterImgLocation: '',
    isShootingNow: false,
    isShootingBefore: false,
    isShootinging: false,
    isShootingAfter: false,
    addbriefIntroductionIconImgUrl: 'http://39.102.232.151:8030/cover/添加证书icon.png',
    companyId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options, 'addtrainimg options')
    this.data.companyId = options.companyId
    // 获取camera context
    const cameraContext = wx.createCameraContext()
    this.cameraContext = cameraContext
    // console.log(this.cameraContext, 'this.cameraContext')
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.setNavigationBarTitle({
      title: '新增培训影像'
    })
    wx.setNavigationBarColor({
      backgroundColor: '#090D9C',
      frontColor: '#ffffff',
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },
  inputBriefIntroduction(event) {
    this.data.briefIntroduction = event.detail.value
  },
  inputTrainSum(event) {
    console.log(event, 'inputTrainSum')
    this.data.trainSum = event.detail.value
  },
  chosenTrainLocation(event) {
    this.setData({
      trainLocation: event.detail.value.join('-')
    })
  },
  chosenTrainDate(event) {
    this.setData({
      trainDate: event.detail.value
    })
  },
  chosenTrainTime(event) {
    this.setData({
      trainTime: event.detail.value + ":00"
    })
  },
  takePhotoBefore() {
    if (this.data.isShootingBefore === false ) {
      this.setData({
        isShootingBefore: true
      })
      return
    }
    let photo = {
      quality: 'high',
      success: (res) => {
        this.setData({
          trainbeforeImg: res.tempImagePath
        })
        // 获取定位
        wx.getLocation({
          type: 'wgs84',
          altitude: false,
          success: (res1) => {
            this.data.trainbeforeImgLocation = res1.latitude + ',' + res1.longitude
          }
        })
        const index = res.tempImagePath.indexOf('.')
        this.data.trainbeforeImgExtension = res.tempImagePath.substr(index + 1)
        this.data.trainbeforeImgTime = parseTime(new Date())
        const fileSystemManager = wx.getFileSystemManager()
        fileSystemManager.getFileInfo({
          filePath: res.tempImagePath,
          success: (res1) => {
            fileSystemManager.readFile({
              filePath: res.tempImagePath,
              position: 0,
              encoding: 'base64',
              length: res1.size,
              success: (res2) => {
                this.data.trainbeforeImgBase64 = res2.data
              }
            })
          }
        })
      },
      complete: () => {
        this.setData({
          isShootingBefore: false
        })
      }
    }
    this.cameraContext.takePhoto(photo)
  },
  takePhotoing() {
    if (this.data.isShootinging === false ) {
      this.setData({
        isShootinging: true
      })
      return
    }
    let photo = {
      quality: 'high',
      success: (res) => {
        this.setData({
          trainingImg: res.tempImagePath
        })
        // 获取定位
        wx.getLocation({
          type: 'wgs84',
          altitude: false,
          success: (res1) => {
            this.data.trainingImgLocation = res1.latitude + ',' + res1.longitude
          },
          fail: () => {
            this.data.trainingImgLocation = this.data.trainbeforeImgLocation
          }
        })
        const index = res.tempImagePath.indexOf('.')
        this.data.trainingImgExtension = res.tempImagePath.substr(index + 1)
        this.data.trainingImgTime = parseTime(new Date())
        const fileSystemManager = wx.getFileSystemManager()
        fileSystemManager.getFileInfo({
          filePath: res.tempImagePath,
          success: (res1) => {
            fileSystemManager.readFile({
              filePath: res.tempImagePath,
              position: 0,
              encoding: 'base64',
              length: res1.size,
              success: (res2) => {
                this.data.trainingImgBase64 = res2.data
              }
            })
          }
        })
      },
      complete: () => {
        this.setData({
          isShootinging: false
        })
      }
    }
    this.cameraContext.takePhoto(photo)
  },
  takePhotoAfter() {
    if (this.data.isShootingAfter === false ) {
      this.setData({
        isShootingAfter: true
      })
      return
    }
    let photo = {
      quality: 'high',
      success: (res) => {
        this.setData({
          trainafterImg: res.tempImagePath
        })
        // 获取定位
        wx.getLocation({
          type: 'wgs84',
          altitude: false,
          success: (res1) => {
            this.data.trainafterImgLocation = res1.latitude + ',' + res1.longitude
          },
          fail: () => {
            this.data.trainafterImgLocation = this.data.trainbeforeImgLocation
          }
        })
        const index = res.tempImagePath.indexOf('.')
        this.data.trainafterImgExtension = res.tempImagePath.substr(index + 1)
        this.data.trainafterImgTime = parseTime(new Date())
        const fileSystemManager = wx.getFileSystemManager()
        fileSystemManager.getFileInfo({
          filePath: res.tempImagePath,
          success: (res1) => {
            fileSystemManager.readFile({
              filePath: res.tempImagePath,
              position: 0,
              encoding: 'base64',
              length: res1.size,
              success: (res2) => {
                this.data.trainafterImgBase64 = res2.data
              }
            })
          }
        })
      },
      complete: () => {
        this.setData({
          isShootingAfter: false
        })
      }
    }
    this.cameraContext.takePhoto(photo)
  },
  takePhoto() {
    if (this.data.isShootingBefore) {
      this.takePhotoBefore()
    }
    if (this.data.isShootinging) {
      this.takePhotoing()
    }
    if (this.data.isShootingAfter) {
      this.takePhotoAfter()
    }
  },
  uploadPhoto() {
    if (!this.data.briefIntroduction) {
      wx.showToast({
        title: '请输入简介',
        icon: 'error'
      })
      return
    }
    if (!this.data.trainLocation) {
      wx.showToast({
        title: '请输入地点',
        icon: 'error'
      })
      return
    }
    if (!this.data.trainDate) {
      wx.showToast({
        title: '请输入日期',
        icon: 'error'
      })
      return
    }
    if (!this.data.trainTime) {
      wx.showToast({
        title: '请输入时间',
        icon: 'error'
      })
      return
    }
    if (!this.data.trainbeforeImgBase64) {
      wx.showToast({
        title: '请输入培训前照片',
        icon: 'error'
      })
      return
    }
    if (!this.data.trainingImgBase64) {
      wx.showToast({
        title: '请输入培训中照片',
        icon: 'error'
      })
      return
    }
    if (!this.data.trainafterImgBase64) {
      wx.showToast({
        title: '请输入培训后照片',
        icon: 'error'
      })
      return
    }
    if (!this.data.trainbeforeImgLocation) {
      wx.showToast({
        title: '请输入培训前定位',
        icon: 'error'
      })
      return
    }
    if (!this.data.trainingImgLocation) {
      wx.showToast({
        title: '请输入培训中定位',
        icon: 'error'
      })
      return
    }
    if (!this.data.trainafterImgLocation) {
      wx.showToast({
        title: '请输入培训后定位',
        icon: 'error'
      })
      return
    }
    wx.showLoading({
      title: '正在上传',
    })
    // wx.request
    wx.request({
      url: app.globalData.appBaseUrlV2 + '/api/trainImage',
      method: 'POST',
      header: {
        Authorization: app.globalData.Authorization
      },
      data: {
        afterImgBase64: this.data.trainafterImgBase64,
        afterImgExtention: this.data.trainafterImgExtension,
        afterImgLocation: this.data.trainafterImgLocation,
        beforeImgBase64: this.data.trainbeforeImgBase64,
        beforeImgExtention: this.data.trainbeforeImgExtension,
        beforeImgLocation: this.data.trainbeforeImgLocation,
        briefIntroduction: this.data.briefIntroduction,
        companyId: this.data.companyId,
        location: this.data.trainLocation,
        peopleNum: this.data.trainSum,
        time: this.data.trainDate + ' ' + this.data.trainTime,
        trainingImgBase64: this.data.trainingImgBase64,
        trainingImgExtention: this.data.trainingImgExtension,
        trainingImgLocation: this.data.trainingImgLocation
      },
      success: (res) => {
        console.log(res, 'upload train img item')
        wx.showToast({
          title: '添加成功',
        })
        wx.navigateBack()
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  }
})