<template>
	<view class="gui-img-crop">
		<u-navbar title="个人资料" :placeholder="true" bgColor="#2b2e3d" leftText="返回" :autoBack="true" titleStyle="font-weight:bold;color:#7a5831"></u-navbar>
		<view class="gui-cropper-wrapper" :style="{ height: height + 'px', width: width + 'px' }">
			<canvas
				canvas-id="bgCropper"
				id="bgCropper"
				class="gui-cropper-bg"
				:disable-scroll="true"
				@touchstart="touchStart"
				@touchmove="touchMove"
				@touchend="touchEnd"
				:style="{ width: width + 'px', height: height + 'px' }"
			></canvas>
			<canvas canvas-id="prevCropper" id="prevCropper" class="gui-cropper-prev" :disable-scroll="false"></canvas>
		</view>
		<view class="gui-flex">
			<view class="gui-cropper-btn" @tap="selectImg">+ 选择图片</view>
			<view class="gui-cropper-btn" @tap="saveImg">保存图片</view>
		</view>
	</view>
</template>
<script>
import WeCropper from '@/common/WeCropper.js';
import * as common from '@/config/common.js'; //引入common
import { baseUrl, baseApiUrl } from '@/config/config.js';
var _this;
export default {
	data() {
		return {
			token: '',
			// WeCropper 对象
			WeCropper: null,
			// 核心宽度系统会重新计算
			width: 300,
			// 核心高度系统会重新计算
			height: 500,
			// 剪裁设置对象
			cropperSets: {
				height: 500,
				width: 300,
				id: 'bgCropper',
				targetId: 'prevCropper',
				scale: 2.5, // 最大缩放倍数
				zoom: 8, // 缩放系数
				cut: {
					x: 0, // 裁剪框x轴起点
					y: 0, // 裁剪框y轴期起点
					width: 200, // 裁剪框宽度
					height: 200 // 裁剪框高度
				}
			},
			tmpFace: null, // 用于判断用户是否选择过图片
			imgType: '',
			transToJPG: ''
		};
	},
	onLoad: function (option) {
		// 获取屏幕信息规划剪裁组件宽度和高度
		const sysinfo = uni.getSystemInfoSync();
		this.width = sysinfo.windowWidth;
		this.height = sysinfo.windowHeight - sysinfo.statusBarHeight - 130;
		//#ifdef MP-WEIXIN
		let info = wx.getMenuButtonBoundingClientRect();
		this.height = sysinfo.windowHeight - info.top - sysinfo.statusBarHeight - 50;
		//#endif
		console.log(sysinfo);
		this.cropperSets.width = this.width;
		this.cropperSets.height = this.height;
		this.cropperSets.pixelRatio = sysinfo.pixelRatio;
		this.cropperSets.cut.x = (this.width - this.cropperSets.cut.width) / 2;
		this.cropperSets.cut.y = (this.height - this.cropperSets.cut.height) / 2;
		this.WeCropper = new WeCropper(this.cropperSets);
		_this = this;
		this.imgType = option.imgType;
		console.log(option);
	},
	methods: {
		selectImg: function () {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					this.WeCropper.pushOrign(res.tempFilePaths[0]);
					this.tmpFace = res.tempFilePaths[0];
				}
			});
		},
		touchStart(e) {
			this.WeCropper.touchStart(e);
		},
		touchMove(e) {
			this.WeCropper.touchMove(e);
		},
		touchEnd(e) {
			this.WeCropper.touchEnd(e);
		},
		saveImg: function () {
			if (this.tmpFace == null) {
				uni.showToast({
					title: '请选择图片',
					icon: 'none'
				});
				return;
			}

			uni.showLoading({
				mask: true,
				title: ''
			});
			this.WeCropper.getCropperImage((tempFilePath) => {
				if (tempFilePath) {
					console.log(tempFilePath);
					// 01. 此处 h5 端生成 base64 形式的图片数据, 其他端生成一个临时文件地址
					// 02. 可以连接 api 完成图片的上传工作
					// 03. 上传完成后关闭当页面，返回账户中心更新最新的头像地址即可
					let userToken = '';
					let auth = this.$db.get('auth');
					userToken = auth.token;
					console.log('userToken: ', userToken);
					// uni.getFileSystemManager().readFile({
					//     filePath: tempFilePath, //选择图片返回的相对路径
					//     encoding: 'jpeg', //编码格式
					//     success: res => { //成功的回调
					//         this.transToJPG = res.data
					// 		console.log("transToJPG", this.transToJPG);
					//     },
					// 	fail: (err) => {
					// 		console.log("failtransToJPG", err);
					// 	}

					// });
					uni.uploadFile({
						url: baseApiUrl + 'common/upload?token=' + userToken,
						filePath: tempFilePath,
						fileType: 'image',
						name: 'file',
						headers: {
							Accept: 'application/json',
							'Content-Type': 'multipart/form-data',
							token: userToken
						},
						formData: {},
						success: (uploadFileRes) => {
							// console.log(JSON.parse(uploadFileRes.data))
							var dataimg = JSON.parse(uploadFileRes.data);
							// console.log(dataimg.data.fullurl)
							let imgtype = this.imgType;
							console.log(imgtype);
							if (imgtype == 'changeIdentify') {
								_this.$api.updateface(
									{
										face: dataimg.data.fullurl
									},
									(data) => {
										if (data.code === 0) {
											_this.$common.errorToShow(data.msg);
										} else {
											_this.$common.successToShow('保存成功', function () {
												uni.navigateTo({
													// url: '/user_fenbao/info/getface'
												});
											});
										}
									}
								);
							} else if (imgtype == 'changeAvatar') {
								_this.$api.profile(
									{
										avatar: dataimg.data.fullurl
									},
									(data) => {}
								);
								uni.navigateBack({
									delta: 2
								});
							}
						},
						fail: (error) => {
							if (error && error.response) {
								this.$common.showError(error.response);
							}
						},
						complete: () => {
							setTimeout(function () {
								uni.hideLoading();
							}, 250);
						}
					});
				} else {
					console.log('获取图片地址失败，请稍后重试');
					uni.hideLoading();
				}
			});
		}
	}
};
</script>
<style>
.gui-flex {
	display: flex;
	background-color: #2b2e3d;
}
.gui-img-crop {
	width: 750rpx;
	background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAOwwAADsMBx2+oZAAAAB90RVh0U29mdHdhcmUATWFjcm9tZWRpYSBGaXJld29ya3MgOLVo0ngAAAAWdEVYdENyZWF0aW9uIFRpbWUAMDkvMjIvMjBpulvaAAAAQ0lEQVRIie3VsQ0AIAwDQZth2H8eljET0JgGiXf/OilNLGmqXJLVtqMNbwcMDAwMDHyck/SxXb/U/04NDAwMDPw+vAGUagde2qkMXgAAAABJRU5ErkJggg==');
	height: 100%;
	position: fixed;
	z-index: 90;
	left: 0;
	top: 0;
}

/* #ifdef H5 */
.gui-img-crop {
	top: 44px;
}

/* #endif */

.gui-cropper-wrapper {
	overflow: hidden;
}

.gui-cropper-bg {
}

.gui-cropper-prev {
}

.gui-cropper-btn {
	width: 50%;
	text-align: center;
	line-height: 50px;
	font-size: 28rpx;
	color: #ffffff;
}
</style>
