// 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: null,
    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() {
	wx.showLoading({title: '请稍后......',})
	// 获取位置
	this.getWXLocation().then((res)=>{
		wx.hideLoading();
		this.data.trainbeforeImgLocation = res.latitude + ',' + res.longitude;

		this.onTakePhoto = function(res){
			var tempImagePath = res.tempImagePath;
			var index = tempImagePath.indexOf('.');

			this.data.trainbeforeImgExtension = tempImagePath.substr(index + 1);
			this.data.trainbeforeImgTime = parseTime(new Date());
			this.data.trainbeforeImgBase64 ='data:image/jpeg;base64,'+ res.data;

			this.setData({trainbeforeImg:tempImagePath, isShootingBefore: false});
		};

		if(this.data.isShootingBefore === false) {
		  this.setData({
			isShootingBefore: true
		  })
		  return
		}
	}).catch(() => {
		wx.hideLoading();
	});
  },
  takePhotoing() {
	wx.showLoading({title: '请稍后......',})
	// 获取位置
	this.getWXLocation().then((res)=>{
		wx.hideLoading();
		this.data.trainingImgLocation = res.latitude + ',' + res.longitude;

		this.onTakePhoto = function(res){
			var tempImagePath = res.tempImagePath;
			var index = tempImagePath.indexOf('.');

			this.data.trainingImgExtension = tempImagePath.substr(index + 1);
			this.data.trainingImgTime = parseTime(new Date());
			this.data.trainingImgBase64 ='data:image/jpeg;base64,'+ res.data;

			this.setData({trainingImg:tempImagePath, isShootinging: false});
		};

		if (this.data.isShootinging === false ) {
		  this.setData({
			isShootinging: true
		  })
		  return
		}
	}).catch(() => {
		wx.hideLoading();
		this.data.trainingImgLocation = this.data.trainbeforeImgLocation
	});
  },
  takePhotoAfter() {
	
	wx.showLoading({title: '请稍后......',})
	// 获取位置
	// this.getWXLocation().then((res)=>{
	// 	wx.hideLoading();
	// 	this.data.trainafterImgLocation = res.latitude + ',' + res.longitude;

		this.onTakePhoto = function(res){
			var tempImagePath = res.tempImagePath;
			var index = tempImagePath.indexOf('.');

			this.data.trainafterImgExtension = tempImagePath.substr(index + 1);
			this.data.trainafterImgTime = parseTime(new Date());
			this.data.trainafterImgBase64 ='data:image/jpeg;base64,'+ res.data;

			this.setData({trainafterImg:tempImagePath, isShootingAfter: false});
		};

		if (this.data.isShootingAfter === false ) {
		  this.setData({
			isShootingAfter: true
		  })
		  return
		}
	// }).catch(() => {
	// 	wx.hideLoading();
	// 	this.data.trainafterImgLocation = this.data.trainbeforeImgLocation
	// });
    
  },
  takePhoto() {
	wx.showLoading({title: '请稍后...',})
	this.cameraContext.takePhoto({
	  quality: 'high',
	  success: (res) => {
		  wx.hideLoading();
		var tempImagePath = res.tempImagePath;
		const fileSystemManager = wx.getFileSystemManager();
		
		wx.showLoading({title: '请稍后....',})
		fileSystemManager.getFileInfo({
		  filePath: tempImagePath,
		  success: (res1) => {
			  wx.hideLoading();
			  wx.showLoading({title: '请稍后.....',})
			fileSystemManager.readFile({
			  filePath: tempImagePath,
			  position: 0,
			  encoding: 'base64',
			  length: res1.size,
			  success: (res2) => {
				  wx.hideLoading();
				res2.tempImagePath = tempImagePath;
				this.onTakePhoto && this.onTakePhoto(res2);
			  }
			})
		  }
		})
	  },
	  complete: () => {
		//wx.hideLoading();
	  }
	})
  },
  uploadPhoto() {
	  console.log('uploadPhoto ________________ ', this.data);

    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()
      }
    })
  },

	
	/**
	  * 打开位置权限
	  * @return: 
	  * @version: V0.1
	  * @author: Kimber
	  * @updatetime: 2022/6/24(周五)
	  * @createtime: 2022/6/24(周五)
	  */
	getWXLocation(){
		return new Promise(function(resolve, reject){
			var getLocation = function(){
				// 获取定位
				// wx.getLocation({
          wx.getFuzzyLocation({
					type: 'wgs84',
					altitude: false,
					success: (res) => {
						return resolve(res)
					},
					fail: (err) => {
						return reject(err)
					}
				})
			}
			
			wx.getSetting({
				success: (res) => {
					var auth = res.authSetting;

					//非初始化进入该页面,且未授权
					if(auth['scope.userLocation'] != undefined && auth['scope.userLocation'] != true) {
						wx.showModal({
						  title: '是否授权当前位置',
						  content: '需要获取您的地理位置，请确认授权，否则无法上传照片',
						  success: function (res) {
							if(res.cancel) {
							  wx.showToast({
								title: '授权失败',
								icon: 'error',
								duration: 1000
							  })
							}else if(res.confirm) {
							  wx.openSetting({
								success: function (dataAu) {
								  if (dataAu.authSetting["scope.userLocation"] == true) {
									wx.showToast({
									  title: '授权成功',
									  icon: 'success',
									  duration: 1000
									})
									//再次授权，调用getLocationt的API
									getLocation();
								  } else {
									wx.showToast({
									  title: '授权失败',
									  icon: 'error',
									  duration: 1000
									})
								  }
								}
							  })
							}
						  }
						})
					} else if (res.authSetting['scope.userLocation'] == undefined) {//初始化进入
						getLocation();
					}
					else  { //授权后默认加载
						getLocation();
					}
				}
			})
		})
	},
})