<template>
	<view class="imgDetail">
		<image class="main-img" :src="detailMsg.imgUrl" mode=""></image>
		<view class="toolbar">
			<view class="toolbar-box">
				<image v-if="detailMsg.isHot ==='0'" src="../../static/hot-not.png" mode=""></image>
				<image v-else src="../../static/hot-yes.png" mode=""></image>
			</view>
			<view class="toolbar-box" @click="download(detailMsg.imgUrl)">
				<image v-if="isDownload" src="../../static/download-select.png" mode=""></image>
				<image v-else src="../../static/download.png" mode=""></image>
				<text>下载</text>
			</view>
			<view class="toolbar-box" @click="likeCollect('isLike')">
				<image v-if="isLike" src="../../static/like-select.png" mode=""></image>
				<image v-else src="../../static/like.png" mode=""></image>
				<text>喜欢</text>
			</view>
			<view class="toolbar-box" @click="likeCollect('isCollect')">
				<image v-if="isCollect" src="../../static/collect-select.png" mode=""></image>
				<image v-else src="../../static/collect.png" mode=""></image>
				<text>收藏</text>
			</view>
			<view class="toolbar-box share-box">
				<button open-type="share">
					<image src="../../static/share.png" mode=""></image>
					<text>分享</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		detailsTiktokImg, // 获取图片详情
		judgeTiktokLike, // 查询是否点赞过
		judgeTiktokCollect, // 查询是否收藏过
		tiktokLike, // 点赞
		tiktokUnLike, // 取消点赞
		tiktokCollect, // 收藏
		tiktokUnCollect, // 取消收藏
		queryCreatorScanCodeById, //获取艺术家搜索码
		insertOrUpdatePreAdProfit, //新增/更新艺术家即将入账广告收益
		insertOrUpdatePreInviteProfit, // 新增/更新艺术家即将入账邀请收益
		checkUserCanDownload // 检查某平台用户当日下载次数是否超标
	} from '@/api/creator.js'
	export default {
		data() {
			return {
				detailMsg: {}, // 图片信息
				userInfo: {}, // 登录用户信息
				isDownload: false, // 是否已下载
				isLike: false, // 是否点赞/喜欢
				isCollect: false, // 是否收藏,
				scanCode: undefined, //艺术家搜索码
				canDownload: false //能否下载 false为能下载

			}
		},
		created() {
			const detailId = uni.getStorageSync('detailId')
			if (detailId) {
				this.getImgDetail(detailId)
			} else {
				this.getImgDetail(detailId)
			}
		},
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				console.log(res)
			}
			return {
				title: '来看看艺术家[' + this.scanCode + ']精心准备的图片吧~',
				path: `/pages/creator/imgDetail?id=${this.userInfo.id}`,
				bgImgUrl: `${this.detailMsg.imgUrl}`
			}
			uni.showToast({
				title: '分享成功',
				icon: 'none'
			})
		},
		methods: {
			// 图片详情
			async getImgDetail(id) {
				const res = await detailsTiktokImg(id)
				console.log('res', res)
				if (res.data.code === 200) {
					this.detailMsg = res.data.data
					console.log('图片详情', res)
					const result = await queryCreatorScanCodeById(this.detailMsg.creatorId)
					if (result.data.code === 200) {
						this.scanCode = result.data.data.scanCode
					} else {
						uni.showToast({
							title: '该艺术家不存在!',
							icon: 'none'
						})
					}
					uni.getStorage({
						key: 'userInfo',
						success: res => {
							this.userInfo = res.data
							console.log('userInfo', this.userInfo)
							this.searchIsLike()
							this.searchisCollect()
							this.checkUserDownload()
						}
					})
				} else {
					uni.showToast({
						title: '请输入艺术家代号',
						icon: 'none'
					})
				}
			},
			// 查询是否点赞
			async searchIsLike() {
				const params = {
					imgId: this.detailMsg.id,
					userId: this.userInfo.id
				}
				console.log('params', this.detailMsg, params)
				const res = await judgeTiktokLike(params)
				if (res.data.code === 200) {
					this.isLike = res.data.data
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
				}
			},
			// 查询是否收藏过
			async searchisCollect() {
				const params = {
					imgId: this.detailMsg.id,
					userId: this.userInfo.id
				}
				const res = await judgeTiktokCollect(params)
				if (res.data.code === 200) {
					this.isCollect = res.data.data
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
				}
			},
			// 点赞/收藏
			async likeCollect(val) {
				const params = {
					imgId: this.detailMsg.id,
					userId: this.userInfo.id
				}
				if (val === 'isLike') {
					this.isLike = !this.isLike
					console.log('this.isLike', this.isLike)
					if (this.isLike) {
						//点赞
						console.log('点赞')
						const res = await tiktokLike(params)
						if (res.data.code === 200) {} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					} else {
						//取消点赞
						console.log('取消点赞')
						const res = await tiktokUnLike(params)
						if (res.data.code === 200) {} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					}
				} else if (val === 'isCollect') {
					this.isCollect = !this.isCollect
					if (this.isCollect) {
						//收藏
						console.log('收藏')
						const res = await tiktokCollect(params)
						if (res.data.code === 200) {} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					} else {
						//取消收藏
						console.log('取消收藏')
						const res = await tiktokUnCollect(params)
						if (res.data.code === 200) {} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					}
				}


			},
			//写入图片广告收益
			async insertPreAdProfit() {
				const params = {
					imgId: this.detailMsg.id,
					creatorId: this.detailMsg.creatorId,
					scanCode: this.scanCode,
					userId: this.userInfo.id,
					appType: '0',
					platform: '0'
				}
				const res = await insertOrUpdatePreAdProfit(params);
				if (res.data.code === 200) {
					console.log("写入广告收益成功!")
					this.adResult = res.data.code;
				} else {
					uni.showToast({
						title: '图片下载失败!',
						icon: 'none'
					})
				}
			},

			//写入图片邀请收益
			async insertPreInviteProfit() {
				const params = {
					imgId: this.detailMsg.id,
					creatorId: this.detailMsg.creatorId,
					scanCode: this.scanCode,
					appType: '0',
					platform: '0'
				}
				const res = await insertOrUpdatePreInviteProfit(params)
				if (res.data.code === 200) {
					console.log("写入邀请收益成功");
					this.inviteResult = res.data.code;
				} else {
					uni.showToast({
						title: '图片下载失败!',
						icon: 'none'
					})
				}
			},

			//检查某平台用户当日下载次数是否超标
			async checkUserDownload() {
				const params = {
					userId: this.userInfo.id,
					appType: '0',
					platform: '0'
				}
				const res = await checkUserCanDownload(params);
				if (res.data.code === 200) {
					console.log("当日下载结果为", res.data.data)
					this.canDownload = res.data.data;
				} else {
					uni.showToast({
						title: '检查下载状态失败!',
						icon: 'none'
					})
				}
			},



			// 下载
			download(url) {
				let that = this;
				if (this.canDownload != true) {
					//满足可下载条件
					this.isDownload = true
					uni.showLoading({
						title: '正在保存图片...'
					});
					//获取用户的当前设置。获取相册权限
					uni.getSetting({
						success: (res) => {
							//如果没有相册权限
							if (!res.authSetting["scope.writePhotosAlbum"]) {
								//向用户发起授权请求
								tt.authorize({
									scope: "scope.album",
									success: () => {
										//授权成功保存图片到系统相册
										uni.downloadFile({
											url,
											success: (res) => {
												console.log('下载路径', res)
												if (res.statusCode === 200) {
													uni.saveImageToPhotosAlbum({
														//图片路径，不支持网络图片路径
														filePath: res
															.tempFilePath,
														success: (res) => {
															console.log(
																'success',
																res)

														},
														fail: (res) => {
															console.log(
																'fail',
																res)
															return uni
																.showToast({
																	title: res
																		.errMsg,
																	icon: 'none'
																});
														},
														complete: (res) => {
															uni
														.hideLoading();
															if (res
																.errMsg !==
																"saveImageToPhotosAlbum:ok"
															) {
																return uni
																	.showToast({
																		title: "下载失败！",
																		icon: 'none'
																	});
															} else {
																return uni
																	.showToast({
																		title: "下载成功！",
																		icon: 'none',
																		success() {
																			that.insertPreAdProfit();
																			that.insertPreInviteProfit();
																		}
																	});
															}
														},
													});
												} else {
													uni.showToast({
														title: "下载失败！",
														icon: 'none'
													});
												}
											}
										})
									},
									//授权失败
									fail: () => {
										uni.hideLoading();
										uni.showModal({
											title: "您已拒绝获取相册权限",
											content: "是否进入权限管理，调整授权？",
											success: (res) => {
												if (res.confirm) {
													//调起客户端小程序设置界面，返回用户设置的操作结果。（重新让用户授权）
													uni.openSetting({
														success: (
															res) => {
															console
																.log(
																	res
																	.authSetting
																);
														},
													});
												} else if (res.cancel) {
													return uni.showToast({
														title: "已取消！",
														icon: 'none'
													});
												}
											},
										});
									},
								});
							} else {
								//如果已有相册权限，直接保存图片到系统相册
								uni.saveImageToPhotosAlbum({
									filePath: url,
									success: (res) => {
										uni.hideLoading();
										return uni.showToast({
											title: "保存成功！",
											icon: 'none'
										});
									},
									fail: (res) => {
										uni.hideLoading();
										console.log(res.errMsg);
										return uni.showToast({
											title: res.errMsg,
											icon: 'none'
										});
									},
									//无论成功失败都走的回调
									complete: (res) => {
										uni.hideLoading();
									},
								});
							}
						},
						fail: (res) => {},
					});
				} else {
					//不满足可下载条件 canDownload为true状态
					uni.showToast({
						title: '当日下载次数已用完,请明日再来!',
						icon: 'none'
					})
				}

			},
			// 分享
			share() {
				uni.showToast({
					title: '分享',
					icon: 'none'
				})
			},
		}
	}
</script>

<style lang="less">
	.imgDetail {
		height: 100vh;
		width: 100vw;
		overflow: hidden;
		position: relative;

		.main-img {
			width: 100%;
			height: 100%;
		}

		.toolbar {
			width: 60px;
			background-color: rgba(255, 255, 255, 0.2);
			position: absolute;
			bottom: 76px;
			right: 10px;
			border-radius: 60px;
			padding-top: 40rpx;

			.share-box {

				>button {
					line-height: 0 !important;
					padding: 0;
					outline: none;
					background: none;
					border: none;

				}

				>button::after {
					border: none;
				}
			}

			.toolbar-box {
				height: 60px;
				text-align: center;
				margin-bottom: 40rpx;

				text {
					display: block;
					text-align: center;
					line-height: 60rpx;
					font-size: 12px;
				}

				image {
					width: 50rpx;
					height: 50rpx;
					margin: 0 auto;
				}
			}

			.toolbar-box:first-child {
				line-height: 40rpx;
				height: 40rpx;
			}

		}
	}
</style>
