<!-- html -->
<template>
	<view style="overflow: hidden;">
		<u-checkbox-group @change="checkboxGroupChange" max=9>
			<view class="container">
				<view class="left">
					<view class="posive" v-for="(item,index) in leftList" :key="index">
						<image :src="item.url" alt="" mode="widthFix" @click="previewImg(item)" />
						<view v-if="upload" class="collected">
							<u-checkbox v-model="item.checked" :name="item.img_url" shape="circle" active-color="#3D6EF6" size="16" icon-size="8" />
						</view>
					</view>
				</view>
				<view class="right">
					<view class="posive" v-for="(item,index) in rightList" :key="index">
						<image :src="item.url" alt="" mode="widthFix" @click="previewImg(item)" />
						<view v-if="upload" class="collected">
							<u-checkbox v-model="item.checked" :name="item.img_url" shape="circle" active-color="#3D6EF6" size="16" icon-size="8" />
						</view>
					</view>
				</view>
			<!-- 	<view v-show="!upload" class="fixed" @click="upload = true, clearUp()">
					下载
				</view> -->
				<view v-show="upload" class="fixed2 flexS">
					<view class="left">
						已选择<text>{{  checkUrl.length}}</text>张
					</view>
					<view class="flex">
						<view class="upload" @click="downloadImgs">
							立即下载
						</view>
						<view class="quxiao" @click="upload = false">
							取消
						</view>
					</view>
				</view>
			</view>
			<u-loadmore
				v-if="nomore"
				dashed
			    status="nomore"  
			    nomore-text="没有更多啦~" 
			/>
		</u-checkbox-group>
		<u-overlay :show="show" :opacity="1">
			<view @tap.stop="close()" class="close">
				<image src="../../static/img/close.png" mode="widthFix"></image>
			</view>
			<swiper :autoplay="false"  :duration="350" :current="current" class="swiper">
				<swiper-item v-for="(item,index) in list">
					<movable-area class="image-view-area">
						<movable-view class="image-view-view" direction="all" :scale="true" scale-min="1" scale-max="3">
							<img :src="item.url" alt="" />
						</movable-view>
					</movable-area>
					<view v-if="item.master" class="btn" @tap.stop="showMaster(item, index)">
						查看原图
					</view>
				</swiper-item>
			</swiper>
		</u-overlay>
	</view>
</template>
<script>
	import { GetImgDetail } from '../../api/index.js';
	export default {
			data() {
				return {
					upload: false,
					show: false,
					list: [
						// {
						// 	file_name: "IMG_20220723_185105.jpg",
						// 	url: "http://look.qiniuyun.jiuweiyun.cn/daweiboshi_szy/image_f7b92067678f0f3a29e8aa956214113f.jpg",
						// 	img_url: "http://look.qiniuyun.jiuweiyun.cn/daweiboshi_szy/image_f7b92067678f0f3a29e8aa956214113f.jpg",
						// 	checked: true
						// },
						// {
						// 	file_name: "IMG_20220723_185141.jpg",
						// 	url: "http://look.qiniuyun.jiuweiyun.cn/daweiboshi_szy/image_cc1ba9bc4e3e8e58459ed9daee128c9f.jpg",
						// 	img_url: "http://look.qiniuyun.jiuweiyun.cn/daweiboshi_szy/image_cc1ba9bc4e3e8e58459ed9daee128c9f.jpg",
						// 	checked: true
						// },
						// {
						// 	file_name: "IMG_20220723_185155.jpg",
						// 	url: "http://look.qiniuyun.jiuweiyun.cn/daweiboshi_szy/image_b21151a7aa4edfbc707140adac3d86b9.jpg",
						// 	img_url: "http://look.qiniuyun.jiuweiyun.cn/daweiboshi_szy/image_b21151a7aa4edfbc707140adac3d86b9.jpg",
						// 	checked: false
						// }
					],
					checkUrl: [],
					filename: [],
					nomore: false,
					current: 0,
					leftList: [],// 初始化左右盒子
					rightList: [],
					leftH: 0,// 初始化左右盒子高度
					rightH: 0,
					params: {
						id: '',
					    page_index: 1,
					    page_size: 15,
						type: 1
					},
					totalPage: 0
				}
			},
			onLoad(option) {
				if (option.title) {
					uni.setNavigationBarTitle({
						title: option.title
					});
				}
				this.params.id = option.id
				this.getList()
				this.doList(this.list)
				console.log(this.$u.config.v);
			},
			onReachBottom() {
			   this.more()
			},
			methods: {
				close() {
					this.show = false
					// this.move()
				},
				// 点击放大图片
				previewImg(item) {
					let i = this.list.findIndex(v => v.id == item.id)
					this.current = i
					this.show  = true
					// this.stop()
				},
				showMaster(item, i) {
					this.list[i].url = item.img_url
					setTimeout(()=>{
					    this.list[i].master = false
					},1000)
				},
				//禁止页面滑动
				stop(){
				    var mo=function(e){e.preventDefault();};
				    document.body.style.overflow='hidden';
				    document.addEventListener("touchmove",mo,false);
				},
				/***取消滑动限制***/
				move(){
				    var mo=function(e){e.preventDefault();};
				    document.body.style.overflow='';//出现滚动条
				    document.removeEventListener("touchmove",mo,false);
				},
				//获取列表
				getList(isMore) {
					uni.showLoading()
				    GetImgDetail(this.params).then(res => {
						uni.hideLoading()
				        if (res.code === 200) {
				            const { list, total } = res.data
				            if (list.length === 0) {
								uni.showToast({ title: '暂无内容', icon: 'none' })
								return false
							}
				            this.totalPage = Math.ceil(Number(total) / 15)
							list.forEach(e=> {
								e.checked = false
								e.master = true
							})
							this.doList(list)
				            this.list = isMore ? this.list.concat(list) : list
				        } else {
				            uni.showToast({ title: res.message || '获取列表失败', icon: 'none' })
				        }
				    })
				},
				//加载获取更多
				more() {
				    if (this.params.page_index >= this.totalPage) {
						this.nomore = true
				        return false
				    }
				    this.params.page_index++
				    this.getList(true)
				},
				// 瀑布流
				doList(list) {
					const that = this
					list.forEach(res => {
						// 获取图片宽高
						uni.getImageInfo({
							src: res.url,
							success: (image) => {
								// 计算图片渲染高度
								let showH = (50 * image.height) / image.width
								// 判断左右盒子高度
								if(that.leftH <= that.rightH) {
									that.leftList.push(res)
									that.leftH += showH
								} else {
									that.rightList.push(res)
									that.rightH += showH
								}
							}
						})
					})
				},
				// 下载图片
				downloadImgs() {
					this.filename = []
					if (this.checkUrl.length === 0) {
						uni.showToast({
						   title: '请选择需要保存的图片',
						   icon: 'none'
						})
						return
					}
					let _this = this
					_this.checkUrl.forEach(c => {
					    _this.list.forEach(v => {
					        if (c == v.img_url) {
					            _this.filename.push(v.file_name)
					        }
					    })
					})
					console.log(_this.checkUrl, _this.filename)
					// 调用保存图片promise队列
					_this.queue(_this.checkUrl, _this.filename).then(res => {
						uni.hideLoading()
						// _this.clearUp()
						// _this.checkUrl = []
						// _this.filename = []
					}).catch(err => {
						uni.hideLoading()
					})
				},
				// 队列
				queue(urls, filename) {
					console.log(2, urls, filename)
					let promise = Promise.resolve()
					urls.forEach((url, index) => {
					    promise = promise.then(() => {
							return this.download(url, filename[index], index)
					    })
					})
					return promise
				},
				// 下载
				download(url, filename, index) {
					console.log(url, filename)
					let length = this.checkUrl.length
					    uni.downloadFile({
							url: url,
							success: function(res) {
								var temp = res.tempFilePath
								// var link = document.createElement('a')
								// link.href = temp
								// link.download = filename
								// document.body.appendChild(link)
								// link.click()
								let image = new Image();
								   // 解决跨域 Canvas 污染问题
								     image.setAttribute("crossOrigin", "anonymous");
								     image.onload = function() {
								     let canvas = document.createElement("canvas");
								     canvas.width = image.width;
								     canvas.height = image.height;
								     let context = canvas.getContext("2d");
								     context.drawImage(image, 0, 0, image.width, image.height);
								     let img = canvas.toDataURL("image/png"); //得到图片的base64编码数据
								     let a = document.createElement("a"); // 生成一个a元素
								     let event = new MouseEvent("click"); // 创建一个单击事件
								     a.download = filename|| "photo"; // 设置图片名称，-------------你传递的图片名称
								     a.href = img; // 将生成的URL设置为a.href属性
								     a.dispatchEvent(event); // 触发a的单击事件
								   };
								   image.src = temp;//你的图片地址
							},
							fail: function(err) {
							}
						})
				},
				// 清除已选项
				clearUp() {
					this.leftList.forEach((item, i) => {
						item.checked = false
					})
					this.rightList.forEach((item, i) => {
						item.checked = false
					})
				},
				// 选中任一checkbox时，由checkbox-group触发
				checkboxGroupChange(e) {
					this.checkUrl = e
				},
			}
		}
</script>
<style lang="scss" scoped>
	* { touch-action: pan-y; }
	page {
		background-color: #fff;
		padding-top: 20rpx;
	}
	.close {
		position: fixed;
		top: 20rpx;
		right: 20rpx;
		background: #6f727699;
		width: 80rpx;
		height: 80rpx;
		line-height: 88rpx;
		text-align: center;
		border-radius: 50%;
		z-index: 20000;
		image {
			width: 30rpx;
		}
	}
	.swiper {
		position: relative;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		overflow: hidden;
		.image-view-area, .image-view-view {
		    position: absolute;
		    left: 0;
		    top: 0;
		    width: 100%;
		    height: 100%;
		}
		img {
			position: absolute;
			left: 50%;
			top: 50%;
			-webkit-transform: translate(-50%,-50%);
			transform: translate(-50%,-50%);
			max-height: 100%;
			max-width: 100%;
			width: 100%;
		}
		.btn {
			position: absolute;
			bottom: 60rpx;
			left: 285rpx;
			width: 180rpx;
			height: 60rpx;
			line-height: 60rpx;
			border-radius: 36rpx 36rpx 36rpx 36rpx;
			// border: 1rpx #FFFFFF solid;
			color: #FFFFFF;
			text-align: center;
			background-color: #333;
		}
	}
	.container {
			padding: 0 24rpx;
			font-size: 14rpx;
			line-height: 24rpx;
			display: flex;
			justify-content: space-between;
		.right, .left{
			display: inline-block;
			width: 340rpx;
			vertical-align: top;
		}
		.left image, .right image{
			border-radius: 16rpx;
			width: 100%;
			margin-bottom: 24rpx;
		}
		.posive {
			position: relative;
		}
		.collected {
			border: 2rpx solid #3D6EF6;
			position: absolute;
			background-color: rgba(0, 0, 0, 0.4);
			border-radius: 50%;
			bottom: 40rpx;
			right: 16rpx;
			z-index: 10;
		}
		.fixed {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			text-align: center;
			line-height: 80rpx;
			background: #3D6EF6;
			position: fixed;
			right: 24rpx;
			bottom: 40rpx;
			color: #fff;
			z-index: 100;
			font-size: 28rpx;
		}
		.fixed2 {
			position: fixed;
			right: 0;
			bottom: 0;
			width: 684rpx;
			height: 96rpx;
			background: #000000;
			border-radius: 0px 0px 0px 0px;
			// opacity: 0.5;
			background-color: rgba(000,000,000,0.5);
			padding: 0 32rpx;
			color: #FFFFFF;
			font-size: 28rpx;
			z-index: 100;
			.left {
				font-size: 32rpx;
				font-weight: bold;
				text {
					color: #3D6EF6;
					margin: 0 10rpx;
				}
			}
			.upload {
				width: 176rpx;
				height: 64rpx;
				background: #3D6EF6;
				border-radius: 32rpx 32rpx 32rpx 32rpx;
				text-align: center;
				line-height: 64rpx;
			}
			.quxiao {
				width: 120rpx;
				height: 64rpx;
				margin-left: 24rpx;
				border-radius: 32rpx 32rpx 32rpx 32rpx;
				opacity: 1;
				border: 2rpx solid #F5F5F5;
				text-align: center;
				line-height: 64rpx;
			}
		}
	}	
</style>