<template>
	<view>
		<view style="background: #fff; position: fixed; top: 0; width: 100%; z-index: 1">
			<view class="drma_title" style="font-size: 28rpx; color: #181818; padding: 20rpx 20rpx 0">
				<view class="pic" @tap="getdrama_list" :data-drama_id="seat_data.prev_show">
					<image
						:src="'/static/images/ui/' +(seat_data.prev_show !== 0 ? 'dram_activeleft.png' : 'dram_left.png')"
						alt="" />
				</view>
				<view>{{ seat_data.show_info.show_date }}</view>
				<view class="pic" @tap="getdrama_list" :data-drama_id="seat_data.next_show">
					<image
						:src="'/static/images/ui/' +(seat_data.next_show !== 0 ? 'dram_activeright.png' : 'dram_right.png')"
						alt="" />
				</view>
			</view>
			<view class="seat_grade">
				<view
					:class="'seat_grade_info  ' + (item.tkt_num == 0 ? 'null_tic' : '') + ' ' + (select_grade == item.grade ? 'select' : '')"
					:data-num="item.tkt_num" :data-select_grade="item.grade" @tap="select_gradeFun"
					v-for="(item, index) in seat_data.grade_list" :key="index">
					<image :src="'/static/images/seats/' + item.grade + '.png'"
						style="width:12px;height:12px;margin-left: 20rpx;"></image>
					<view style="margin: 0 10rpx 0 10rpx">¥{{ item.price }}</view>
				</view>
			</view>
			<view class="direction">
				<view style="margin-top: -35rpx">舞台方向</view>
			</view>
		</view>
		<view class="canvasView" @touchstart.stop.prevent="touch1.start" @touchmove.stop.prevent="touch1.move"
			@touchend.stop.prevent="touch1.end" @touchcancel.stop.prevent="touch1.end">
			<!-- #ifdef MP-WEIXIN || MP-TOUTIAO -->
			<canvas id="myCanvas" type="2d"
				:style="'height:'+maxCanvasH* scaleNum+'px;width:'+ maxCanvasW* scaleNum +'px;left:'+(move.x)+'px;top:'+(move.y+canvasTopGap)+'px;'"></canvas>
			<!-- #endif -->
			<!-- #ifdef MP-ALIPAY || MP-BAIDU  -->
			<canvas id="myCanvas" canvas-id="myCanvas" :width="maxCanvasW" :height="maxCanvasH"
				:style="'height:'+maxCanvasH * scaleNum +'px;width:'+ maxCanvasW * scaleNum +'px;left:'+(move.x)+'px;top:'+(move.y+canvasTopGap)+'px;'"></canvas>
			<!-- #endif -->
		</view>
		<view class="bottom">
			<view class="seat_tips" v-if="selected_seats.length">
				<view class="loc" v-for="(item, index) in selected_seats" :key="index">
					<view class="info">
						<image :src="'/static/images/seats/' + item.grade + '.png'" style="width: 16px;height: 16px;">
						</image>
						<text :decode="true" style="font-size: 24rpx">&nbsp;{{ item.seat_info }}</text>
					</view>

					<image :data-ticket_id="item.ticket_id" src="/static/images/ui/close.png"
						style="width: 16px;height: 16px;" @click="cancel_sel" />
				</view>
			</view>
			<view class="submit">
				<view class="cacu" v-if="total_price">
					<view class="text">共计</view>
					<view class="info">
						<view class="price">
							¥
							<text style="font-size: 44rpx; font-weight: bold">{{ total_price }}.00</text>
						</view>
						<view class="num" v-if="selected_seats.length">已选择{{ selected_seats.length }}个座位</view>
					</view>
				</view>
				<button class="button" :disabled="!total_price" @tap="make_order">下一步</button>
			</view>
		</view>
	</view>
</template>

<script>
	// pages/make_order/choose_sit/choose_sit.js
	import {
		httpUtil,
		http
	} from '../../../utils/util.js';
	import MinaTouch from './mina-touch';
	import seatImg from './seatImg.js';
	export default {
		data() {
			return {
				drama_id: null,
				screenWidth: 375,
				screenHeight: 764,
				canvasTopGap: 175,
				canvasBottomGap: 64,
				ctx: null,
				canvasImg: null,
				select_grade: '',
				selected_seats: [],
				total_price: '',
				max_select: 6,
				//缩放比例（画布宽度适应屏幕）
				scaleNum: 1,
				// 二次放大比例(适应座位位置)
				scaleNumTwice: 1,
				//手动挪动偏移距离
				move: {
					x: 0,
					y: 0
				},
				scaleShift: {
					x: 0,
					y: 0
				},
				tapTimeGap: true,
				timer: 0,
			};
		}
		/**
		 * 生命周期函数--监听页面加载
		 */
		,
		async onLoad(options) {
			let that = this
			uni.getSystemInfo({
				success(res) {
					//获取屏幕的宽成功
					that.screenWidth = res.screenWidth
					that.screenHeight = res.screenHeight
					// #ifdef MP-ALIPAY
					that.screenWidth = res.windowWidth
					that.screenHeight = res.windowHeight
					// #endif
				}
			});
			await this.initData(options.drama_id)
			this.initTouch()
		},
		methods: {
			async initData(drama_id) {
				let seat_data = await httpUtil('/api/v1/seat-list', 'get', {
					drama_id
				})
				let maxCanvasW = 60 * (seat_data.max_x + 1)
				let maxCanvasH = 60 * (seat_data.max_y + 1)
				if (this.screenWidth < maxCanvasW) {
					this.scaleNum = (this.screenWidth / maxCanvasW).toFixed(3) //缩放比例
					this.scaleNumTwice = (this.screenWidth / 60 / 20).toFixed(3)
				}
				await this.setData({
					drama_id,
					seat_data,
					maxCanvasW,
					maxCanvasH,
					selected_seats: [],
					total_price: '',
					select_grade: ''
				})
				this.creatCanvas()
			},
			async creatCanvas() {
				// #ifdef MP-WEIXIN || MP-TOUTIAO
				if (this.ctx) {
					this.initCanvas(this.ctx)
					return
				}
				wx.createSelectorQuery().select('#myCanvas')
					.fields({
						node: true,
						size: true
					})
					.exec((res) => {
						const canvas = res[0].node
						const ctx = canvas.getContext('2d')
						canvas.width = this.maxCanvasW
						canvas.height = this.maxCanvasH
						this.setData({
							ctx: ctx
						})
						this.initCanvas(ctx)
					})
				// #endif

				// #ifdef MP-ALIPAY || MP-BAIDU
				let ctx = this.ctx || uni.createCanvasContext('myCanvas')
				// #ifdef MP-BAIDU
				ctx.save()
				ctx.scale(this.scaleNum, this.scaleNum)
				// #endif
				this.setData({
					ctx: ctx
				})
				ctx.width = this.maxCanvasW
				ctx.height = this.maxCanvasH
				this.initCanvas(ctx)
				// #endif
			},
			async initCanvas(ctx) {
				let that = this
				ctx.clearRect(0, 0, this.maxCanvasW, this.maxCanvasH)
				this.seat_data.seat_list.forEach((item) => {
					if (this.select_grade != '') {
						if (item.ticket_status === 0 && this.select_grade === item.grade) {
							this.drawSeat(ctx, item.x * 60, item.y * 60, seatImg[item.grade].color)
						} else {
							this.drawSeat(ctx, item.x * 60, item.y * 60, seatImg['00'].color)
						}
					} else {
						if (item.ticket_status === 0) {
							this.drawSeat(ctx, item.x * 60, item.y * 60, seatImg[item.grade].color)
						} else {
							this.drawSeat(ctx, item.x * 60, item.y * 60, seatImg['00'].color)
						}
					}
				})
				if (this.selected_seats.length > 0) {
					this.selected_seats.forEach((v, k) => {
						ctx.clearRect(v.x * 60, v.y * 60, 60, 50)
						this.drawSeat(this.ctx, v.x * 60, v.y * 60, seatImg['01'].color)
						// #ifndef MP-WEIXIN || MP-TOUTIAO
						ctx.draw(true)
						// #endif
					})
				}
				// #ifndef MP-WEIXIN || MP-TOUTIAO
				setTimeout(() => {
					ctx.restore()
					ctx.draw(true);
				}, 200)
				// #endif
			},
			drawSeat(ctx, x, y, fillColor) {
				ctx.beginPath()
				// #ifdef MP-WEIXIN || MP-TOUTIAO
				ctx.fillStyle = fillColor
				ctx.lineWidth = 0.1
				// #endif
				// #ifdef MP-ALIPAY
				ctx.setFillStyle(fillColor)
				ctx.setLineWidth(0.1)
				// #endif
				// #ifdef MP-BAIDU
				ctx.setFillStyle(fillColor)
				// ctx.setLineWidth(0.1)
				// #endif
				ctx.arc(20 + x, 10 + y, 10, Math.PI, 1.5 * Math.PI)
				ctx.lineTo(40 + x, y)
				ctx.arc(40 + x, 10 + y, 10, 1.5 * Math.PI, 2 * Math.PI)
				ctx.lineTo(50 + x, 20 + y)
				ctx.arc(50 + x, 25 + y, 5, 1.5 * Math.PI, 2 * Math.PI)
				ctx.lineTo(55 + x, 45 + y)
				ctx.arc(47 + x, 45 + y, 8, 0, 0.5 * Math.PI)
				ctx.lineTo(13 + x, 53 + y)
				ctx.arc(13 + x, 45 + y, 8, 0.5 * Math.PI, Math.PI)
				ctx.lineTo(5 + x, 25 + y)
				ctx.arc(10 + x, 25 + y, 5, Math.PI, 1.5 * Math.PI)
				ctx.lineTo(10 + x, 10 + y)
				ctx.fill()

				ctx.arc(10 + x, 25 + y, 5, 1.5 * Math.PI, 2 * Math.PI)
				ctx.lineTo(15 + x, 41 + y)
				ctx.arc(17 + x, 41 + y, 2, Math.PI, 0.5 * Math.PI, true)
				ctx.lineTo(43 + x, 43 + y)
				ctx.arc(43 + x, 41 + y, 2, 0.5 * Math.PI, 0, true)
				ctx.lineTo(45 + x, 25 + y)
				ctx.arc(50 + x, 25 + y, 5, Math.PI, 1.5 * Math.PI)
				// #ifdef MP-WEIXIN || MP-TOUTIAO
				ctx.strokeStyle = '#333333'
				// #endif
				// #ifndef MP-WEIXIN || MP-TOUTIAO
				ctx.setStrokeStyle('#333333')
				// #endif

				ctx.stroke()
			},
			canvasToImg() {
				let that = this
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: that.maxCanvasW,
					height: that.maxCanvasH,
					destWidth: that.maxCanvasW * that.scaleNum,
					destHeight: that.maxCanvasW * that.scaleNum,
					canvasId: 'myCanvas',
					success: function(res) {
						that.canvasImg = res.tempFilePath
					}
				})
			},
			cancel_sel(e) {
				let ticket_id = e.currentTarget.dataset.ticket_id
				this.selected_seats.find((v, k) => {
					if (v.ticket_id === ticket_id) {
						this.ctx.clearRect(v.x * 60, v.y * 60, 60, 50)
						if (this.select_grade != '' && v.grade != this.select_grade) {
							this.drawSeat(this.ctx, v.x * 60, v.y * 60, seatImg['00'].color)
						} else {
							this.drawSeat(this.ctx, v.x * 60, v.y * 60, seatImg[v.grade].color)
						}
						// #ifndef MP-WEIXIN || MP-TOUTIAO
						this.ctx.draw(true)
						// #endif
						this.selected_seats.splice(k, 1)
						return true
					}
				})
				this.price_cac(this.selected_seats);
			},
			initTouch() {
				let that = this
				new MinaTouch(this, 'touch1', {
					touchStart: function() {},
					touchMove: function() {},
					touchEnd: function() {},
					touchCancel: function() {},
					//一个手指以上触摸屏幕触发
					multipointStart: function() {
						console.log('multipointStart');
						// clearTimeout(this.timer)
						that.setData({
							scaleListen: true
						})
					},
					//当手指离开，屏幕只剩一个手指或零个手指触发(一开始只有一根手指也会触发)
					multipointEnd: function() {
						console.log('multipointEnd');
						that.setData({
							scaleListen: false
						})
					},
					//点按触发，覆盖下方3个点击事件，doubleTap时触发2次
					tap: function() {
						console.log('Tap');
					},
					//双击屏幕触发
					doubleTap: function() {
						console.log('doubleTap');
						// that.scaleNum = (that.scaleNum * 1.3).toFixed(3)
						// that.move = {
						// 	x: that.move.x *1.3- that.screenWidth / 2 * (1.3 - 1) ,
						// 	y: that.move.y *1.3- (that.screenHeight/ 2 - that.canvasTopGap) * (1.3 - 1)
						// }
						if (that.scaleNum.fixed(1) === that.scaleNumTwice.fixed(1)) {
							return
						}
						let singleZoom = that.scaleNumTwice / that.scaleNum
						that.scaleNum = that.scaleNumTwice
						that.move = {
							x: that.move.x * singleZoom - that.screenWidth / 2 * (singleZoom - 1),
							y: that.move.y * singleZoom - (that.screenHeight / 2 - that.canvasTopGap) * (
								singleZoom - 1)
						}
					},
					//长按屏幕750ms触发
					longTap: function() {
						// console.log('longTap');
						// if (that.maxCanvasW * that.scaleNum > that.screenWidth * 5) {
						// 	return
						// }
						// that.scaleNum = that.scaleNum * 2
					},
					//单击屏幕触发，包括长按
					singleTap: function(e) {
						console.log('singleTap');
						if (!that.tapTimeGap) {
							return
						}
						// #ifdef MP-ALIPAY
						let select_position = {
							x: e.changedTouches[0].x || e.changedTouches[0].pageX,
							y: e.changedTouches[0].y || e.changedTouches[0].pageY
						}
						// #endif
						// #ifndef MP-ALIPAY
						let select_position = {
							x: e.changedTouches[0].pageX,
							y: e.changedTouches[0].pageY
						}
						// #endif
						let cur_seat = {
							x: Math.floor((select_position.x - that.move.x) / 60 / that.scaleNum),
							y: Math.floor((select_position.y - that.canvasTopGap - that.move.y) / 60 / that
								.scaleNum)
						}
						if (that.selected_seats.find((v, k) => {
								if (cur_seat.x == v.x && cur_seat.y == v.y && v.ticket_status === 0) {
									// #ifdef MP-BAIDU									
									that.ctx.save()
									that.ctx.scale(that.scaleNum, that.scaleNum)
									// #endif
									that.ctx.clearRect(v.x * 60, v.y * 60, 60, 50)
									if (that.select_grade != '' && v.grade != that.select_grade) {
										that.drawSeat(that.ctx, v.x * 60, v.y * 60, seatImg['00'].color)
									} else {
										that.drawSeat(that.ctx, v.x * 60, v.y * 60, seatImg[v.grade].color)
									}
									that.ctx.restore()
									// #ifndef MP-WEIXIN || MP-TOUTIAO
									that.ctx.draw(true)
									// #endif
									that.selected_seats.splice(k, 1)
									return true
								}
							})) {
							that.price_cac(that.selected_seats)
							return
						}
						that.seat_data.seat_list.find(v => {
							if (cur_seat.x == v.x && cur_seat.y == v.y && v.ticket_status === 0) {
								// 判断是否超过最大可选
								if (that.selected_seats.length >= that.max_select) {
									uni.showToast({
										title: '单次最多选座6个',
										icon: 'fail',
										duration: 500
									})
									return
								}
								that.selected_seats.push(v);
								// #ifdef MP-BAIDU							
								that.ctx.save()
								that.ctx.scale(that.scaleNum, that.scaleNum)
								// #endif
								that.ctx.clearRect(v.x * 60, v.y * 60, 60, 50)
								that.drawSeat(that.ctx, v.x * 60, v.y * 60, seatImg['01'].color)
								that.ctx.restore()
								// #ifndef MP-WEIXIN || MP-TOUTIAO
								that.ctx.draw(true)
								// #endif
								return true
							}
						})
						that.price_cac(that.selected_seats)
					},
					//evt.angle代表两个手指旋转的角度
					rotate: function(evt) {
						console.log('rotate:' + evt.angle);
					},
					//evt.zoom代表两个手指缩放的比例(多次缩放的累计值),evt.singleZoom代表单次回调中两个手指缩放的比例
					pinch: function(evt) {
						console.log('singleZoom,' + evt.singleZoom);
						that.tapTimeGap = false
						let singleZoom = Math.sqrt(Math.sqrt(evt.singleZoom));
						if (singleZoom > 1.6 || singleZoom < 0.6) {
							return
						}
						if (singleZoom < 1 && that.maxCanvasW * that.scaleNum < that.screenWidth * 7 / 8) {
							return
						} else
						if (singleZoom > 1 && that.maxCanvasW * that.scaleNum > that.screenWidth * 5) {
							return
						}
						that.scaleNum = (that.scaleNum * singleZoom).toFixed(3)
						that.move = {
							x: that.move.x * singleZoom - that.screenWidth / 2 * (singleZoom - 1),
							y: that.move.y * singleZoom - (that.screenHeight / 2 - that.canvasTopGap) * (
								singleZoom - 1)
						}

						this.timer = setTimeout(() => {
							that.tapTimeGap = true
						}, 1000)
					},
					//evt.deltaX和evt.deltaY代表在屏幕上移动的距离,evt.target可以用来判断点击的对象
					pressMove: function(evt) {
						if (evt.deltaX > 100 || evt.deltaY > 100) {
							return
						}
						if (that.move.x > that.screenWidth / 2 && evt.deltaX > 0) {
							return
						} else
						if (that.move.x < 0 && (that.maxCanvasW * that.scaleNum + that.move.x) < that
							.screenWidth / 2 && evt.deltaX < 0) {
							return
						}
						if ((that.move.y + that.canvasBottomGap) > that.screenHeight / 2 && evt.deltaY > 0) {
							return
						} else
						if (that.move.y < 0 && (that.maxCanvasH * that.scaleNum + that.move.y + that
								.canvasTopGap) < that
							.screenHeight / 2 && evt.deltaY < 0) {
							return
						}
						that.setData({
							move: {
								x: that.move.x + evt.deltaX,
								y: that.move.y + evt.deltaY
							}
						})
					},
					//在touch结束触发，evt.direction代表滑动的方向 ['Up','Right','Down','Left']
					swipe: function(evt) {
						console.log('swipe:' + evt.direction);
					}
				});
			},
			select_gradeFun(e) {
				if (e.currentTarget.dataset.num !== 0) {
					this.select_grade = (this.select_grade === e.currentTarget.dataset.select_grade) ? '' : e.currentTarget
						.dataset.select_grade
					this.initCanvas(this.ctx)
					this.scaleNum = (this.screenWidth / this.maxCanvasW).toFixed(3)
					this.move = {
						x: 0,
						y: 0
					}
				}
			},
			// 计算票总价 '含多买折扣'
			price_cac(selected_seats) {
				const p = [];
				const grade_price = [];
				grade_price.push(this.seat_data.grade_price);
				for (var x in grade_price[0]) {
					let a = 0;
					let arr = [];
					for (let i of selected_seats) {
						if (i.grade == x) {
							a++;
							arr.push({
								row: i.row,
								col: i.col,
								floor: i.floor
							});
						}
					}
					if (grade_price[0][x][a]) {
						p.push({
							tkt_grade: x,
							tkt_num: a,
							tkt_pirce: grade_price[0][x][a],
							tkt_loc: arr
						});
					}
				}
				let ii = 0;
				for (let i in p) {
					ii += parseInt(p[i].tkt_pirce);
				}
				this.setData({
					total_price: ii
				});
			},
			getdrama_list(e) {
				let drama_id = e.currentTarget.dataset.drama_id;

				if (drama_id == 0) {
					return
				}
				this.initData(drama_id);
			},
			make_order() {
				var selected_seats = this.selected_seats;
				var tid = '';
				selected_seats.forEach((v, k) => {
					tid = tid + ',' + String(v.ticket_id);
				});
				tid = tid.substring(1);
				uni.navigateTo({
					url: '/pages/make_order/make_order/make_order?tid=' + tid + '&drama_id=' + this.drama_id
				});
			},

		}
	};
</script>
<style>
	.canvasView {
		position: fixed;
		width: 100%;
		height: 100%;
		overflow: hidden;
	}

	#myCanvas {
		position: absolute;
		/* border: 1px solid red; */
	}

	#myCanvas:hover {
		/* border: 1px solid #ffffff; */
	}

	page {
		width: 100%;
		overflow: hidden;
	}


	.seat_grade {
		display: flex;
		flex-wrap: wrap;
		color: #7b7b7b;
		font-size: 24rpx;
		padding: 40rpx 20rpx;
	}

	.seat_grade .seat_grade_info {
		width: 20%;
		margin: 10rpx;
		display: flex;
		padding: 10rpx 5rpx;
		border-radius: 52rpx;
		border: 2rpx solid #d2d2d2;
	}

	.seat_grade .null_tic {
		background: #dddddd;
		border: 2rpx solid #dddddd;
		color: #ffffff;
	}

	.seat_grade .select {
		background: #ffffff;
		border: 2rpx solid #ff1d42;
		color: #181818;
	}

	.direction {
		width: 200rpx;
		margin: 0 auto;
		height: 0;
		border-top: 37rpx solid #dddddd;
		border-radius: 0 0 60rpx 60rpx;
		/* border-right: 74rpx solid transparent;
  border-left: 74rpx solid transparent; */
		text-align: center;
		font-size: 24rpx;
		color: #f8f8f7;
	}

	.bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
	}

	.bottom .seat_tips {
		display: flex;
		flex-wrap: wrap;
		padding: 10rpx 20rpx;
		background: #f8f8f7;
	}

	.bottom .seat_tips .loc {
		width: 260rpx;
		height: 50rpx;
		background: #ffeef3;
		border-radius: 26rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
		margin: 10rpx;
	}

	.bottom .seat_tips .loc .info {
		display: flex;
		align-items: center;
	}

	.bottom .submit {
		border-top: 2rpx solid #dddddd;
		display: flex;
		height: 128rpx;
		align-items: center;
		background: #fff;
	}

	.bottom .submit .cacu {
		display: flex;
		align-items: center;
	}

	.bottom .submit .cacu .text {
		font-size: 36rpx;
		margin: 0 20rpx 0 30rpx;
	}

	.bottom .submit .cacu .info {}

	.bottom .submit .cacu .info .price {
		color: #ff1d42;
		font-size: 32rpx;
	}

	.bottom .submit .cacu .info .num {
		color: #1394f2;
		font-size: 20rpx;
	}

	.bottom .submit .button {
		width: 240rpx;
		height: 72rpx;
		background: linear-gradient(90deg, #ff4284 0%, #ff1d42 100%);
		border-radius: 44rpx;
		margin-left: auto;
		margin-right: 30rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
		color: #ffffff;
	}

	.drma_title {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.drma_title .pic {
		width: 60rpx;
		height: 60rpx;
	}

	.drma_title .pic image {
		width: 100%;
		height: 100%;
	}
</style>
