<template>
	<view :style="[mainStyle]">
		<!-- 上传区域 -->
		<view class="upload-box">
			<block v-if="form.image && form.image.length > 0"><image v-for="(item, index) in form.image" style="width: 100%;" mode="widthFix" :src="item"></image></block>
			<block v-else>
				<view class="upload-area" @click="choiceImages"><image class="upload-icon" src="../static/images/plus.png"></image></view>
				<view class="upload-title">请上传处方图片</view>
			</block>
			<view class="note">您上传的处方图片要求字迹清楚、清晰可辨认、信息完整（含姓名，疾病，年龄，性别及医生签名等信息）</view>
		</view>
		<!-- 信息 -->
		<view class="form-box">
			<view class="form-item bottom-border">
				<view>是否需要代煎药</view>
				<view><switch :checked="form.isBoilMedicine" data-name="isBoilMedicine" @change="switchChange" color="#11bb8b" style="transform: scale(0.7)"></switch></view>
			</view>
			<view class="form-item bottom-border">
				<view>是否是孕妇</view>
				<view><switch :checked="form.isPregnantWoman" data-name="isPregnantWoman" @change="switchChange" color="#11bb8b" style="transform: scale(0.7)"></switch></view>
			</view>
			<view class="form-item">
				<view>备注</view>
				<view><input class="note-input" v-model="form.note" placeholder="备注，给商家留言" /></view>
			</view>
		</view>
		<!-- 收货地址 -->
		<view class="address-box">
			<view class="form-item" @tap="addOrUpdateAddress">
				<view>收货地址</view>
				<view style="display: flex;align-items: center">
					<input v-if="!address.address" class="note-input" disabled="true" placeholder="添加收货地址" />
					<view v-else>{{ address.address + address.house }}</view>
					<image class="arrow-icon" src="../static/images/arrow.png"></image>
				</view>
			</view>
		</view>
		<!-- 按钮 -->
		<view class="bottom-bar">
			<view class="bottom-btn" :disabled="buttonClicked" @click="submitUpdata()"><text>提交处方</text></view>
		</view>

		<canvas canvas-id="canvas" :style="'width:' + cWidth + 'px;height:' + cHeight + 'px;position: absolute;left:-1000px;top:-1000px;'"></canvas>
	</view>
</template>

<script>
const app = getApp();
const requsetmessage = require('../../utils/requestmessage.js');
const req = require('../../utils/request.js');
const api = require('../../utils/api.js');
const utils = require('../../utils/util.js');
export default {
	data() {
		return {
			mainStyle: app.globalData.mainStyle,
			form: {
				image: [],
				isBoilMedicine: false,
				isPregnantWoman: false,
				note: '',
				buttonClicked: false
			},
			address: {}
		};
	},

	onLoad(options) {},

	onShow() {},

	methods: {
		switchChange(e) {
			this.form[e.currentTarget.dataset.name] = e.detail.value;
		},

		addOrUpdateAddress() {
			let url = 'mine/address/address?isChoose=true';
			app.globalData.openPage(url);
		},

		//提交数据
		async submitUpdata() {
			var tha = this;
			if (!this.form.image || this.form.image.length <= 0) {
				req.msg('请上传处方图片');
				return;
			}
			if (!this.address.id) {
				req.msg('请选择收货地址');
				return;
			}
			if (tha.buttonClicked) {
				console.log('重复点击了，返回>>>>>');
				return;
			}
			tha.buttonClicked = true;
			//订阅处方审核通知
			await requsetmessage
				.prescribingAudit()
				.then(res => {
					req.postRequest(
						'/api/orderdurg/save',
						{
							drugImgUrl: tha.form.image.join(','),
							isFrying: tha.form.isBoilMedicine ? '1' : '0',
							isPregnant: tha.form.isPregnantWoman ? '1' : '0',
							remarks: tha.form.note,
							addressId: tha.address.id,
							merchantId:req.getStorage('MERCHANT').id,
						},
						data => {
							tha.buttonClicked = false;
							uni.navigateBack();
						},
						true
					);
				})
				.catch(() => {
					tha.buttonClicked = false;
				});
		},

		//处方图片上传
		choiceImages(event) {
			let that = this;
			wx.chooseImage({
				count: 9,
				sourceType: ['album', 'camera'],
				sizeType: ['compressed'],
				async success(res) {
					console.log(res);
					let list = res.tempFiles;
					console.log(list);
					let allList = [];
					for (let i = 0; i < list.length; i++) {
						//两M
						if (list[i].size > 50000) {
							var path = await that.compressImg(list[i].path);
							var data = {
								formData: {
									flag: 726
								},
								filePath: path,
								name: 'file'
							};
							allList.push(data);
						} else {
							var data = {
								formData: {
									flag: 722
								},
								filePath: list[i].path,
								name: 'file'
							};
							allList.push(data);
						}
					}
					console.log(allList);
					let successUp = 0;
					let failUp = 0;
					let count = 0;
					// 多图上传 allList:图片数组 successUp：上传成功次数 现在上传的下标
					that.uploadImgs(allList, successUp, failUp, count);
				},
				fail(err) {}
			});
		},
		//通过canvans缩放长宽来压缩图片 path:图片本地路径  limitNum：压缩到长宽多大
		async compressImg(path, multiple = 2, limitNum = 600) {
			console.log('图片链接', path);
			let that = this;
			return new Promise((resolve, reject) => {
				wx.getImageInfo({
					src: path,
					success(res) {
						var canvasWidth = res.width; //图片原始长宽
						var canvasHeight = res.height;
						console.log('图片的基本信息', res);
						// while循环 保证宽高在100以内 Math.trunc()去掉小数点右边数
						while (canvasWidth > limitNum || canvasHeight > limitNum) {
							canvasWidth = Math.trunc(res.width / multiple);
							canvasHeight = Math.trunc(res.height / multiple);
							multiple++;
						}
						//设置画布长宽
						that.setData({
							cWidth: canvasWidth,
							cHeight: canvasHeight
						});
						//----------绘制图形并取出图片路径--------------
						var ctx = wx.createCanvasContext('canvas');
						ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight);
						ctx.draw(
							false,
							setTimeout(() => {
								wx.canvasToTempFilePath({
									canvasId: 'canvas',
									destWidth: canvasWidth,
									destHeight: canvasHeight,
									success: function(res) {
										console.log(res.tempFilePath); //图片路径
										resolve(res.tempFilePath);
									},
									fail: function(res) {
										console.log(res.errMsg);
									}
								});
							}, 100)
						);
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			});
		},
		//多张图片上传
		uploadImgs: function(allList, successUp, failUp, count) {
			console.log(allList, successUp, failUp, count);
			let tha = this;
			let length = allList.length; //总共上传的数量
			uni.showLoading({
				title: '上传中'
			});
			var index = 0;
			var promise = Promise.all(
				allList.map(tempFilePath => {
					return new Promise(function(resolve, reject) {
						req.uploadFile('/api/upload', tempFilePath.filePath, res => {
							let fileUrls = tha.form.image;
							tha.form.image = fileUrls.concat(res.src);
							if (index == allList.length - 1) {
								uni.hideLoading();
							}
							index++;
						});
					});
				})
			);
			promise.then(function(results) {}).catch(function(err) {});
		}
	}
};
</script>

<style>
@import './uploadPrescription.css';
</style>
