<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">
			
			<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">按钮</button>
		<!--画图板-->
		<view class="jigsaw-canvasMask" :class="canvasMaskType==true?'jigsaw-canvasMaskAct':''" :style="{'top': albumBoxTop + 'px'}">
			<canvas class="jigsaw-canvas" type="2d" id="myCanvas"></canvas>
		</view>
		<!--脚部模板-->
		<view class="jigsaw-template">
			<view class="template-list template-listAct">
				<image class="list-img" src="../static/album/DIY.png"></image>
			</view>
			<view class="template-list">
				<image class="list-img" src="../static/album/DIY.png"></image>
			</view>
			<view class="template-list">
				<image class="list-img" src="../static/album/DIY.png"></image>
			</view>
		</view>
		<!--脚部购物车-->
		<view class="jigsaw-btoom">
			<view class="bottom-pictureFrame">
				<view class="pictureFrame pictureFrameAct">金属框</view>
				<view class="pictureFrame">木框</view>
				<view class="pictureFrame">无框</view>
			</view>
			<view class="message-trading">
				<view class="trading-btn trading-left">
					<image src="../static/album/icon06.png"></image>
					<view class="trading-num">2</view>
				</view>
				<view class="trading-btn trading-right">购买</view>
			</view>
		</view>
		<!--脚部模板开关-->
		<view class="jigsaw-switch" :class="switchType!=true?'jigsaw-switchAct':''">
			<image v-if="switchType==true" class="jigsaw-switchImg" src="../static/album/icon09.png"></image>
			<image v-else class="jigsaw-switchImg" src="../static/album/icon10.png"></image>
		</view>
		
	</view>
</template>

<script>
export default {
  data() {
    return {
      screenWidth:0,//屏幕宽度
      statusBarHeight: 0,//状态栏高度
      capsule: 0,// 胶囊大小、位置数据
      navHeight: 0,// 导航栏高度
      albumBoxTop:0,//顶部高度
			
      pictureJigsawPosition:[//图片框位置
        {
          id:'img1',
          url:'http://lx.pangdly.com/img/sodao.1cdf287.jpg',
          width:'299',
          height:'384',
          top:'184',
          left:'74',
          radius:'0',
        },
        {
          id:'img2',
          url:'http://lx.pangdly.com/img/liangjiang.097258e.jpg',
          width:'299',
          height:'384',
          top:'184',
          left:'387',
          radius:'0',
        },
        {
          id:'img3',
          url:'http://lx.pangdly.com/img/huiguan.c00da69.jpg',
          width:'299',
          height:'384',
          top:'640',
          left:'74',
          radius:'0',
        },
      ],
			
      transpositionStartMes:{},
      transpositionStartIndex:0,
			
      textCanvas: null,		// 初始化 canvas 值
      canvasMaskNum:0, //渲染次数
      canvasMaskType:false,
			
      switchType:true,//模板开关按钮
    }
  },
  onLoad(option) {
    this.recordDeviceInfo()//记录设备信息
    //获取当前view的宽度
    const query = uni.createSelectorQuery().in(this)
    query.select('.jigsaw-picture').boundingClientRect(res => {
      this.screenWidth = res.width
    }).exec()
		
  },
  methods: {
    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 imgList = JSON.parse(JSON.stringify(res[0]))//用于图片自裁剪
        var promiseArrayNum= promiseArray[promiseArray.length-1].top
        
        for(let i=0;i<promiseArray.length;i++){
          let type = 'image'
          let src= promiseArray[i].dataset.src
          let posX = parseInt(promiseArray[i].dataset.tailorx/750*this.screenWidth) //如果向左位移则需要用框的
          let posY = parseInt(promiseArray[i].dataset.tailory/750*this.screenWidth)//parseInt(promiseArray[i].dataset.tailory/750*this.screenWidth)
          let tailorx = parseInt(promiseArray[i].dataset.tailorx/750*this.screenWidth)-promiseArray[i].left
          if(tailorx<0){//因为用的parseInt 是直接舍去，当出现负数的时候 则算为0
            tailorx = 0
          }
          let tailory = parseInt(promiseArray[i].dataset.tailory/750*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/750*this.screenWidth)///750*this.screenWidth
          let sheight = parseInt(promiseArray[i].dataset.heightonce/750*this.screenWidth)///750*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; i++){
            const tx = textCanvas.createImage()
            tx.src = promiseArray[i].src									// 线上地址或者本地地址都可以
            tx.width = promiseArray[i].width	
            tx.height = promiseArray[i].height	
            tx.onload = () => {
              // 图片  裁剪 ：X  Y   宽度 高度
              //promiseArray[i].tailorx,promiseArray[i].tailory,promiseArray[i].swidth, promiseArray[i].sheight-1,  
              if(i==promiseArray.length-1){
                textCtx.drawImage(tx, promiseArray[i].posX, promiseArray[i].posY,promiseArray[i].swidth, promiseArray[i].sheight)
              }else{
                textCtx.drawImage(tx,promiseArray[i].tailorx,promiseArray[i].tailory,promiseArray[i].swidth, promiseArray[i].sheight*1.72, promiseArray[i].posX, promiseArray[i].posY,promiseArray[i].swidth, promiseArray[i].sheight)	
              }
              
            }
          }
        })
    },
  }
}
</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: 750rpx;
		height: 1100rpx;
		margin-top: 86rpx;
		position: relative;
		.picture-backgrounImg{
			width: 750rpx;
			height: 1100rpx;
		}
		.picture-position{
			border:solid 1px #333333;
			overflow: auto;
			position: absolute;
			image{
				display: block;
				height: 100%;
			}
		}
		.picture-positionBox{
			width: 750rpx;
			height: 1100rpx;
			position: absolute;
			top: 0;
			left: 0;
		}
	}
	.jigsaw-canvas{
		display: block;
		width: 750rpx;
		height: 1100rpx;
		
	}
	.jigsaw-canvasMask{
		display: block;
		width: 750rpx;
		padding-top: 86rpx;
		position: absolute;
		left: 0;
		z-index: -10;
	}
	.jigsaw-canvasMaskAct{
		z-index: 100;
	}
	.jigsaw-template{
		display: flex;
		width: 100%;
		height: 180rpx;
		padding: 20rpx;
		background-color: #fff;
		overflow: auto;
		position: fixed;
		bottom: 100rpx;
		left: 0;
		z-index: 110;
		.template-list{
			width: 108rpx;
			height: 160rpx;
			border-radius: 9rpx;
			border: 3rpx solid #EDEDED;
			box-sizing: border-box;
			margin-right: 20rpx;
			position: relative;
			.list-img{
				display: block;
				width: 92rpx;
				height: 138rpx;
				margin: auto;
				position: absolute;
				top: 0;
				right: 0;
				bottom: 0;
				left: 0;
			}
		}
		.template-listAct{
			border: 3rpx solid #FE6600;
		}
	}
	.jigsaw-btoom{
		display: flex;
		justify-content: space-between;
		width: 100%;
		height: 100rpx;
		padding: 18rpx 32rpx 0 20rpx;
		background-color: #fff;
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 110;
		.bottom-pictureFrame{
			display: flex;
			width: 324rpx;
			padding-top: 6rpx;
			overflow: auto;
			.pictureFrame{
				width: 108rpx;
				height: 48rpx;
				font-weight: 400;
				font-size: 24rpx;
				color: #999999;
				line-height: 48rpx;
				text-align: center;
			}
			.pictureFrameAct{
				background: #F7F8FA;
				border-radius: 24rpx;
				color: #333333;
				font-weight: 600;
			}
		}
		.message-trading{
			display: flex;
			position: relative;
			.trading-btn{
				width: 160rpx;
				height: 64rpx;
				position: relative;
			}
			.trading-left{
				background: #FF9F43;
				border-radius: 200rpx 0rpx 0rpx 200rpx;
				image{
					width: 40rpx;
					height: 40rpx;
					margin: auto;
					position: absolute;
					top: 0;
					right: 0;
					bottom: 0;
					left: 0;
				}
			}
			.trading-num{
				width: 42rpx;
				height: 44rpx;
				border-radius: 50%;
				background: #FFFFFF;
				line-height: 44rpx;
				text-align: center;
				font-weight: bold;
				font-size: 28rpx;
				color: #FE6600;
				position: absolute;
				right: 12rpx;
				top: -22rpx;
			}
			.trading-right{
				background: #FE6600;
				border-radius: 0rpx 200rpx 200rpx 0rpx;
				text-align: center;
				line-height: 64rpx;
				font-size: 28rpx;
				font-weight: 600;
				text-align: center;
				color: #FFFFFF;
			}
		}
	}
	.jigsaw-switch{
		width: 52rpx;
		height: 52rpx;
		position: fixed;
		bottom: 220rpx;
		right: 32rpx;
		z-index: 110;
		image{
			display: block;
			width: 52rpx;
			height: 52rpx;
		}
	}
	.jigsaw-switchAct{
		bottom: 144rpx;
	}
	
</style>
