<template>
	<view class="albumBox" :style="{'padding-top': albumBoxTop + 'px' }">
		<!--头部 我的相片-->
		<view class="nav-bar"	:style="{'display': 'flex','top': statusBarHeight + 'px', 'height': navHeight + 'px','line-height': navHeight + 'px'}">
			<u-icon name="arrow-left" color="#333" @click="returnClick"></u-icon>
			我的相片
		</view>
		<!--图片拼图-->
		<view class="jigsaw-picture" data-type="view" id="jigsawPicture" ref="jigsawPicture" v-if="textCanvasType==true">
			
			<template v-for="(item,index) in pictureJigsawPosition">
				<view class="picture-position" @scroll="onScroll($event,index)" :key="index" :style="{'width': item.width + 'rpx' ,'height': item.height + 'rpx' ,'top': item.top + 'rpx' ,'left': item.left + 'rpx' ,'border-radius': item.radius + 'rpx' ,}">
					<image class="queryInfo" 
						data-type="image" :data-src="item.url" :data-widthonce="item.width" :data-heightonce="item.height" :src="item.url" 
						:data-tailorx="item.left" :data-tailory="item.top" :data-id="item.id"
						:class="item.id"
						@touchstart="handleTouchStart($event,index)" @touchmove="handleTouchMove($event,index)" @touchend="handleTouchEnd($event,index)"></image>
				</view>
			</template>
			<image class="picture-backgrounImg queryInfo"
				data-type="image" data-src="../static/album/backgroundImgTo.png" data-widthonce="750" data-heightonce="1100" 
				data-tailorx="0" data-tailory="0"
				src="../static/album/backgroundImgTo.png"></image>
		</view>
		<button @click="toCanvas" style="top:0rpx;position: absolute;">按钮</button>
		<!--画图板-->
		<view class="jigsaw-canvasMask" :class="canvasMaskType==true?'jigsaw-canvasMaskAct':''" :style="{'top': albumBoxTop + 'px'}">
			<canvas class="jigsaw-canvas" type="2d" id="myCanvas"></canvas>
		</view>
		
		<!--脚部选择相片、加入购物车、直接购买 v-if="pictureFrameListNum>0"-->
		<view class="myPhoto-bottom" v-if="bottomCheckType==true">
			<view class="bottom-tips">相片保留10天, 请尽快下载, 下载保存</view>
			<view class="bottom-feature">
				<!--单张 宫格切换-->
				<view class="myPhoto-title">
					<view class="title-click" :class="titleclick==1?'title-clickAct':''" @click="clickActFun(1)">
						单照片
						<view class="click-line"></view>
					</view>
					<view class="title-click" :class="titleclick==2?'title-clickAct':''" @click="clickActFun(2)">
						二宫格
						<view class="click-line"></view>
					</view>
					<view class="title-click" :class="titleclick==3?'title-clickAct':''" @click="clickActFun(3)">
						三宫格
						<view class="click-line"></view>
					</view>
					<view class="title-click" :class="titleclick==4?'title-clickAct':''" @click="clickActFun(4)">
						六宫格
						<view class="click-line"></view>
					</view>
				</view>
				<!--宫格照片数量不够-创建失败-->
				<view class="feature-warn">
					<view class="warn-pattern">
						<image class="pattern-img" src="../static/album/DIY.png"></image>
					</view>
					<view class="warn-pattern warn-patternAct">
						<image class="pattern-img" src="../static/album/DIY.png"></image>
					</view>
				</view>
				<!--选中的张数、加入购物车、立即购买、开始拼图   titleclick等于1显示购物车和立即购买  等于其他 显示开始拼图 进入拼图界面-->
				<view class="feature-message">
					<view class="message-inPhoto">
						<image class="inPhoto-img" src="../static/album/icon13.png"></image>
						<view class="inPhoto-text">购物车</view>
						<view class="inPhoto-num">2</view>
					</view>
					<!-- v-if="titleclick==1" -->
					<view class="message-trading">
						<view class="trading-btn trading-left">
							加入购物车
						</view>
						<view class="trading-btn trading-right">立即购买</view>
					</view>
				</view>
			</view>
		</view>
		<view class="myPhoto-bottom myPhoto-bottomAct" v-else>
			<view class="bottom-tips">相片保留10天, 请尽快下载, 下载保存</view>
			<view class="bottom-checkCase">
				<view class="checkCase-title">
					编辑图片
					<image src="../static/album/photoCheck01.png"></image>
				</view>
				<view class="checkCase-btn">
					<view class="btn-list">
						<image src="../static/album/photoCheck02.png"></image>
						<view>替换</view>
					</view>
					<view class="btn-list">
						<image src="../static/album/photoCheck03.png"></image>
						<view>旋转90°</view>
					</view>
					<view class="btn-list">
						<image src="../static/album/photoCheck04.png"></image>
						<view>水平翻转</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
  data() {
    return {
      screenWidth:0,//屏幕宽度
      statusBarHeight: 0,//状态栏高度
      capsule: 0,// 胶囊大小、位置数据
      navHeight: 0,// 导航栏高度
      albumBoxTop:0,//顶部高度
			
      titleclick:1,//1单照片 2二宫格 3三宫格 4六宫格
			
      pictureJigsawPosition:[//图片框位置
        {
          id:'img1',
          url:'http://lx.pangdly.com/img/sodao.1cdf287.jpg',
          width:'243',
          height:'320',
          top:'151',
          left:'61',
          radius:'0',
        },
        {
          id:'img2',
          url:'http://lx.pangdly.com/img/liangjiang.097258e.jpg',
          width:'243',
          height:'320',
          top:'151',
          left:'312',
          radius:'0',
        },
        {
          id:'img3',
          url:'http://lx.pangdly.com/img/huiguan.c00da69.jpg',
          width:'346',
          height:'266',
          top:'530',
          left:'61',
          radius:'0',
        },
      ],
			
      transpositionStartMes:{},
      transpositionStartIndex:0,
			
      textCanvas: null,		// 初始化 canvas 值
      canvasMaskNum:0, //渲染次数
      canvasMaskType:false,
			
      textCanvasType:true,//临时控制画布显隐
      bottomCheckType:false,//控制脚部按钮切换
    }
  },
  onLoad(option) {
    this.recordDeviceInfo()//记录设备信息
    //获取当前view的宽度
    const query = uni.createSelectorQuery().in(this)
    query.select('.jigsaw-picture').boundingClientRect(res => {
      this.screenWidth = res.width
    }).exec()
		
  },
  methods: {
    clickActFun(num){//宫格选择
		  this.titleclick = num
    },
    onScroll(event) {// event.detail 包含了滚动位置信息
      console.log('滚动位置：', event.detail)
    },
    recordDeviceInfo() { //---记录设备信息
      this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight // 状态栏高度
      this.capsule = uni.getMenuButtonBoundingClientRect() // 胶囊大小、位置数据
      this.navHeight = (this.capsule.top - this.statusBarHeight) * 2 + this.capsule.height // 导航栏高度
      this.albumBoxTop = this.statusBarHeight+this.navHeight
    },
    returnClick() {//头部 点击返回
      uni.navigateBack({
        delta: 1
      })
    },
    //基础换位逻辑
    //1.获取当前位置。确定开始位置的图片值
    //2.获取终点位置
    //3.循环终点位置。确实终点位置是否再开始位置，若不在，则将开始位置和终点位置图片互换
    handleTouchMove(event,index) {
    },
    handleTouchStart(event,index) {//changedTouches[0]  pageX横向 pageY属相  //rect (top, right, bottom, left)
      this.transpositionStartMes = event.changedTouches[0]
      this.transpositionStartIndex = index
    },
    handleTouchEnd(event,index) {//点击图片是否切换
      //距离头部高度 
      var navHeight = this.pxToRpx(this.albumBoxTop)
      //获取终点位置
      var endEvent = event.changedTouches[0]
      //参数重组  将参数从当前参数转换为 750rpx的数值
      var newScale = parseInt(endEvent.pageX/this.screenWidth*750)//换算 满宽在哪
      var newRemain = parseInt((endEvent.pageY-navHeight)/this.screenWidth*750)//换算 满宽在哪  pageY-navHeight  当前手指位置-导航栏高度 为现在手指再DIV内的高度
      endEvent.pageX = newScale
      endEvent.pageY = newRemain
      //循环是否在某个元素框里面
      var newInIndex = null
      this.pictureJigsawPosition.forEach((item,index)=>{
        var overWidth = parseInt(item.width)+parseInt(item.left)
        var overHeight = parseInt(item.height)+parseInt(item.top)
        if(endEvent.pageX>=item.left&&endEvent.pageX<=overWidth&&endEvent.pageY>=item.top&&endEvent.pageY<=overHeight){
          newInIndex = index
        }
      })
      //确定进入其他元素框内时 图片对换
      if(this.transpositionStartIndex!==newInIndex&&newInIndex!==null){
        var indexOne = JSON.parse(JSON.stringify(this.pictureJigsawPosition[this.transpositionStartIndex].url))
        var indexNew = JSON.parse(JSON.stringify(this.pictureJigsawPosition[newInIndex].url))
        this.pictureJigsawPosition[this.transpositionStartIndex].url = JSON.parse(JSON.stringify(indexNew))
        this.pictureJigsawPosition[newInIndex].url = JSON.parse(JSON.stringify(indexOne))
      }
    },
    // px转rpx  将头部导航栏PX转换为RPX
    pxToRpx(px) {
      //计算比例
      let scale = uni.upx2px(100)/100
      return px/scale
    },
    toCanvas(){
      let that = this
      this.canvasMaskType = true
      let promiseArray = []
      // 1.先查询要绘制的image相关属性数据
      // 这里我将需要查询的所有image的类名都设置为queryInfo
      uni.createSelectorQuery().selectAll('.queryInfo').boundingClientRect().exec((res)=>{
        promiseArray = JSON.parse(JSON.stringify(res[0]))
        var promiseArrayNum= promiseArray[promiseArray.length-1].top
        console.log('获取到信息头部：', res[0])
        console.log(this.screenWidth)
        for(let i=0;i<=promiseArray.length-1;i++){
          if(i==promiseArray.length-1){//处理背景图
            let type = 'image'
            let src= promiseArray[i].dataset.src
            let posX = parseInt(promiseArray[i].dataset.tailorx/750*this.screenWidth) //图片所在画板的X轴数据
            let posY = parseInt(promiseArray[i].dataset.tailory/750*this.screenWidth) //图片所在画板的Y轴数据
            let width = promiseArray[i].width//图片原始的宽度
            let height = promiseArray[i].height//图片原始的高度
            let swidth = promiseArray[i].width//要使用的图像的宽度
            let sheight = promiseArray[i].height//要使用的图像的高度
            promiseArray[i]={
						  type:'image',
						  src: src,
						  width:width,
						  height: height,
						  swidth,
						  sheight,
						  posX:posX,
						  posY:posY,
            }
          }else{//处理置入的图片
            let type = 'image'
            let src= promiseArray[i].dataset.src
            let posX = parseInt(promiseArray[i].dataset.tailorx/606*this.screenWidth) //图片所在画板的X轴数据
            let posY = parseInt(promiseArray[i].dataset.tailory/606*this.screenWidth) //图片所在画板的Y轴数据
            //截图的初始X和Y轴
            let tailorx = parseInt(promiseArray[i].dataset.tailorx/606*this.screenWidth)-promiseArray[i].left
            if(tailorx<0){//因为用的parseInt 是直接舍去，当出现负数的时候 则算为0
						  tailorx = 0
            }
            let tailory = parseInt(promiseArray[i].dataset.tailory/606*this.screenWidth)-(promiseArray[i].top-promiseArrayNum)
            if(tailory<0){//因为用的parseInt 是直接舍去，当出现负数的时候 则算为0
						  tailory = 0
            }
            let width = promiseArray[i].width//图片原始的宽度
            let height = promiseArray[i].height//图片原始的高度
            let swidth = parseInt(promiseArray[i].dataset.widthonce/606*this.screenWidth)//要使用的图像的宽度
            let sheight = parseInt(promiseArray[i].dataset.heightonce/606*this.screenWidth)//要使用的图像的高度
            promiseArray[i]={
						  type:'image',
						  src: src,
						  width:width,
						  height: height,
						  swidth,
						  sheight,
						  posX:posX,
						  posY:posY,
						  tailorx:tailorx,
						  tailory:tailory,
            }
          }
          
        }
        console.log('获取到信息：', promiseArray)
        this.drowImg(promiseArray)
      })
    },
    drowImg(promiseArray){ //绘制图片
      let that = this
      // uni-app 中，不管是小程序，app，h5 在获取元素实例时，都是统一的方法,只要获取元素的宽高
      uni.createSelectorQuery().select('#myCanvas').fields({ node: true, size: true })
        .exec((res) => {
          
          // 微信小程序绘制
          let textCanvas = that.textCanvas = res[0].node				// 获取元素实例
          let textCtx = textCanvas.getContext('2d')				// 创建二维绘图
          // 获取设备设备像素比
          const dpr = uni.getSystemInfoSync().pixelRatio
          textCanvas.width = res[0].width * dpr					// 设置canvas像素宽
          textCanvas.height = res[0].height * dpr				// 设置canvas像素高
          textCtx.clearRect(0, 0, res[0].width, res[0].height)	// 设置画布大小
          textCtx.scale(dpr, dpr)
         
						
          // 这里开始绘制canvas内容，绘制的过程当中，不知道是小程序的问题，还是什么问题在绘制有背景图片的内容时，
          // 文字内容必须要延迟绘制，也就是要定时器延迟一定时间才能绘制，要不然就会将文字覆盖在图片下方。
          // 图片的绘制
          for(let i = 0; i <= promiseArray.length-1; i++){
            const tx = textCanvas.createImage()
            tx.src = promiseArray[i].src									// 线上地址或者本地地址都可以
            tx.width = promiseArray[i].width	
            tx.height = promiseArray[i].height	
            tx.onload = () => {
              // 图片  裁剪 ：X  Y   宽度 高度 
              if(i==promiseArray.length-1){//背景
                console.log('123456')
                textCtx.drawImage(tx, promiseArray[i].posX, promiseArray[i].posY,promiseArray[i].swidth, promiseArray[i].sheight)
              }else{//插入的图片
                //promiseArray[i].tailorx,promiseArray[i].tailory,promiseArray[i].swidth, promiseArray[i].sheight*1.72, 
                textCtx.drawImage(tx,promiseArray[i].tailorx,promiseArray[i].tailory,promiseArray[i].swidth*1.03, promiseArray[i].sheight*1.4, promiseArray[i].posX, promiseArray[i].posY,promiseArray[i].swidth, promiseArray[i].sheight)	
              }
              
            }
          }
          this.textCanvasType=false
        })
    },
  }
}
</script>

<style scoped lang="scss">
	.albumBox{
		// display: flex;
		// flex-direction:column;
		height: 100VH;
		background: #F5F7FA;
		overflow: auto;
	}
	.nav-bar {
		width: 100%;
		justify-content:center;
		font-size: 36rpx;
		font-weight: 700;
		padding: 0 24rpx 0 24rpx;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 10;
		/deep/ .u-icon{
			margin: auto;
			position: absolute;
			left: 24rpx;
			top: 0;
			bottom: 0;
		}
	}
	.jigsaw-picture{
		width: 606rpx;
		height: 910rpx;
		margin: 38rpx auto 0 auto;
		position: relative;
		.picture-backgrounImg{
			width: 606rpx;
			height: 910rpx;
		}
		.picture-position{
			border:solid 1px #333333;
			overflow: auto;
			position: absolute;
			image{
				display: block;
			}
		}
		.picture-positionBox{
			width: 750rpx;
			height: 1100rpx;
			position: absolute;
			top: 0;
			left: 0;
		}
	}
	.jigsaw-canvas{
		display: block;
		width: 606rpx;
		height: 910rpx;
		
	}
	.jigsaw-canvasMask{
		display: block;
		width: 606rpx;
		padding-top: 38rpx;
		margin: auto;
		position: absolute;
		left: 0;
		right: 0;
		z-index: -10;
	}
	.jigsaw-canvasMaskAct{
		z-index: 100;
	}
	.myPhoto-title{
		width: 100%;
		height: 100rpx;
		padding: 32rpx 40rpx 0 40rpx;
		background-color: #fff;
		display: flex;
		justify-content: space-between;
		.title-click{
			height: 68rpx;
			font-weight: 600;
			font-size: 28rpx;
			color: #999999;
			line-height: 28rpx;
			position: relative;
			.click-line{
				display: none;
				width: 100%;
				height: 6rpx;
				background: #000000;
				border-radius: 4rpx;
				position: absolute;
				bottom: 18rpx;
				left: 0;
			}
		}
		.title-clickAct{
			font-size: 30rpx;
			color: #333333;
			.click-line{
				display: block;
			}
		}
	}
	.myPhoto-bottom{
		width: 100%;
		height: 464rpx;
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 30;
		.bottom-tips{
			width: 726rpx;
			height: 64rpx;
			background: #FFEFC9;
			border-radius: 8rpx 8rpx 0rpx 0rpx;
			box-sizing: border-box;
			font-weight: 400;
			font-size: 24rpx;
			color: #9A5500;
			padding: 0 26rpx;
			line-height: 64rpx;
			margin: 0 auto;
		}
		.bottom-feature{
			width: 100%;
			height: 400rpx;
			background-color: #fff;
			padding: 0rpx 0rpx 0 0rpx;
			.feature-message{
				display: flex;
				justify-content: space-between;
				border-top: 2rpx solid #F5F5F5;
				padding: 0 40rpx 0 40rpx;
				height: 120rpx;
				.message-trading{
					display: flex;
					position: relative;
					margin-top: 20rpx;
					.trading-btn{
						width: 220rpx;
						height: 80rpx;
						position: relative;
					}
					.trading-left{
						background: #FFB143;
						border-radius: 40rpx 0rpx 0rpx 40rpx;
						text-align: center;
						line-height: 80rpx;
						font-size: 28rpx;
						font-weight: 600;
						text-align: center;
						color: #FFFFFF;
					}
					.trading-right{
						background: #FE6600;
						border-radius: 0rpx 200rpx 200rpx 0rpx;
						text-align: center;
						line-height: 80rpx;
						font-size: 28rpx;
						font-weight: 600;
						text-align: center;
						color: #FFFFFF;
					}
				}
				.message-inPhoto{
					width: 60rpx;
					margin-top: 24rpx;
					position: relative;
					.inPhoto-img{
						display: block;
						width: 44rpx;
						height: 44rpx;
						margin: 0 auto 4rpx auto;
					}
					.inPhoto-text{
						font-weight: 400;
						font-size: 20rpx;
						color: #666666;
						text-align: center;
						line-height: 20rpx;
					}
					.inPhoto-num{
						width: 24rpx;
						height: 24rpx;
						background: #FFFFFF;
						border-radius: 12rpx;
						border: 2rpx solid #FE6600;
						font-size: 18rpx;
						color: #FE6600;
						line-height: 20rpx;
						text-align: center;
						position: absolute;
						right: -2rpx;
						top: -4rpx;
					}
				}
			}
			.feature-warn{
				display: flex;
				width: 750rpx;
				height: 180rpx;
				padding: 0 40rpx 20rpx 40rpx;
				overflow-x: scroll;
				white-space: nowrap;
				.warn-pattern{
					flex: 0 0 auto;
					width: 108rpx;
					height: 160rpx;
					background: #FFFFFF;
					border-radius: 9rpx;
					border: 3rpx solid #EDEDED;
					position: relative;
					.pattern-img{
						display: block;
						width: 91rpx;
						height: 133rpx;
						margin: auto;
						position: absolute;
						top: 0;
						right: 0;
						bottom: 0;
						left: 0;
					}
				}
				.warn-patternAct{
					border: 3rpx solid #FE6600;
				}
			}
		}
	}
	.myPhoto-bottomAct{
		height: 384rpx;
		.bottom-checkCase{
			height: 320rpx;
			background-color: #fff;
			.checkCase-title{
				padding-top: 40rpx;
				font-weight: 600;
				font-size: 28rpx;
				color: #333333;
				line-height: 40rpx;
				text-align: center;
				position: relative;
				image{
					display: block;
					width: 40rpx;
					height: 40rpx;
					position: absolute;
					top: 40rpx;
					right: 24rpx;
				}
			}
			.checkCase-btn{
				padding: 70rpx 120rpx 0 120rpx;
				display: flex;
				justify-content: space-between;
				.btn-list{
					image{
						display: block;
						width: 60rpx;
						height: 60rpx;
						margin: 0 auto 16rpx auto;
					}
					view{
						font-weight: 600;
						font-size: 24rpx;
						color: #333333;
						line-height: 34rpx;
					}
				}
			}
		}
	}
</style>
