<template>
  <view>
    <view class="imgDetail">
      <image class="main-img" :src="detailMsg.imgUrl" mode="widthFix"></image>
    </view>
    <view class="toolbar" v-if="detailMsg.imgUrl">
      <view class="toolbar-box">
        <uni-icons v-if="detailMsg.isHot ==='0'" class="tool-bar-icon" custom-prefix="iconfont" :type="'icon-hot'" size="24"  ></uni-icons>
        <uni-icons v-else class="tool-bar-icon" custom-prefix="iconfont" :type="'icon-hot'" size="24" :color="likeColor"></uni-icons>
      </view>
      <view class="toolbar-box" @click="download(detailMsg.imgUrl)">
        <uni-icons v-if="isDownload" class="tool-bar-icon" custom-prefix="iconfont" :type="'icon-xiazai'" size="24" ></uni-icons>
        <uni-icons v-else class="tool-bar-icon" custom-prefix="iconfont" :type="'icon-xiazai'" size="24" ></uni-icons>
        <text>下载</text>
      </view>
      <view class="toolbar-box" @click="likeCollect('isLike')">
        <uni-icons v-if="isLike" class="tool-bar-icon" custom-prefix="iconfont" :type="'icon-yixihuan'" size="24" :color="likeColor"></uni-icons>
        <uni-icons v-else class="tool-bar-icon" custom-prefix="iconfont" :type="'icon-weixihuan'" size="24" ></uni-icons>
        <text>喜欢</text>
      </view>
      <view class="toolbar-box" @click="likeCollect('isCollect')">
        <uni-icons v-if="isCollect" class="tool-bar-icon" custom-prefix="iconfont" :type="'icon-yishoucang'" size="24" :color="collectColor"></uni-icons>
        <uni-icons v-else class="tool-bar-icon" custom-prefix="iconfont" :type="'icon-weishoucang'" size="24" ></uni-icons>
        <text>收藏</text>
      </view>
      <view class="toolbar-box share-box">
        <button open-type="share">
          <uni-icons class="tool-bar-icon" custom-prefix="iconfont" :type="'icon-fenxiang1'" size="24" ></uni-icons>
          <text>分享</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
	import {
		detailsTiktokImg, // 获取图片详情
		judgeTiktokLike, // 查询是否点赞过
		judgeTiktokCollect, // 查询是否收藏过
		tiktokLike, // 点赞
		tiktokUnLike, // 取消点赞
		tiktokCollect, // 收藏
		tiktokUnCollect, // 取消收藏
		queryCreatorScanCodeById, //获取艺术家搜索码
		insertOrUpdatePreAdProfit, //新增/更新艺术家即将入账广告收益
		insertOrUpdatePreInviteProfit, // 新增/更新艺术家即将入账邀请收益
		checkUserCanDownload // 检查某平台用户当日下载次数是否超标
	} from '@/api/creator.js'
  import {loginTiktok} from '@/api/auth.js'
	export default {
		data() {
			return {
				detailMsg: {}, // 图片信息
				userInfo: undefined, // 登录用户信息
				isDownload: false, // 是否已下载
				isLike: false, // 是否点赞/喜欢
				isCollect: false, // 是否收藏,
				scanCode: undefined, //艺术家搜索码
        artist: {},
				canDownload: false, //能否下载 false为能下载
        whiteColor: '#FFFFFF',
        primaryColor: '#1a94bc',
        likeColor: '#ef223c',
        collectColor: '#dcaa04',
			}
		},
		created() {
			const detailId = uni.getStorageSync('detailId')
			if (detailId) {
				this.getImgDetail(detailId)
			} else {
				this.getImgDetail(detailId)
			}
		},
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				// console.log(res)
			}
      uni.showToast({
        title: '分享成功',
        icon: 'none'
      })
			return {
				title: '来看看艺术家[' + this.scanCode + ']精心准备的图片吧~',
				path: `/pages/creator/imgDetail?id=${this.userInfo.id}`,
				bgImgUrl: `${this.detailMsg.imgUrl}`
			}
		},
		methods: {
			// 图片详情
			async getImgDetail(id) {
				const res = await detailsTiktokImg(id)
				if (res.data.code === 200) {
				  if (!res.data?.data){
            uni.showToast({
              title: '获取图片信息失败',
              icon: 'none'
            })
          }
					this.detailMsg = res.data.data
					const result = await queryCreatorScanCodeById(this.detailMsg.creatorId)
					if (result.data.code === 200) {
					  this.artist = result.data.data;
						this.scanCode = result.data.data.scanCode
					} else {
						uni.showToast({
							title: '该艺术家不存在!',
							icon: 'none'
						})
					}
					uni.getStorage({
						key: 'userInfo',
						success: res => {
							this.userInfo = res.data
							this.searchIsLike()
							this.searchisCollect()
							this.checkUserDownload()
						}
					})
				} else {
					uni.showToast({
						title: '请输入艺术家代号',
						icon: 'none'
					})
				}
			},
			// 查询是否点赞
			async searchIsLike(token) {
				const params = {
					imgId: this.detailMsg.id,
					userId: this.userInfo.id
				}
				const res = await judgeTiktokLike(params, token)
				if (res.data.code === 200) {
					this.isLike = res.data.data
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
				}
			},
			// 查询是否收藏过
			async searchisCollect(token) {
				const params = {
					imgId: this.detailMsg.id,
					userId: this.userInfo.id
				}
				const res = await judgeTiktokCollect(params, token)
				if (res.data.code === 200) {
					this.isCollect = res.data.data
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
				}
			},
      async lickRequest(token) {
        const params = {
          imgId: this.detailMsg.id,
          userId: this.userInfo.id
        }
        let isLike = this.isLike
        if (!isLike) {
          //点赞
          const res = await tiktokLike(params, token)
          if (res.data.code === 200) {
            this.isLike = !isLike
          } else {
            uni.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        } else {
          //取消点赞
          const res = await tiktokUnLike(params, token)
          if (res.data.code === 200) {
            this.isLike = !isLike
          } else {
            uni.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      },
      async collectRequest(token) {
        const params = {
          imgId: this.detailMsg.id,
          userId: this.userInfo.id
        }
        let isCollect = this.isCollect
        if (!isCollect) {
          //收藏
          const res = await tiktokCollect(params, token)
          if (res.data.code === 200) {
            this.isCollect = !isCollect
          } else {
            uni.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        } else {
          //取消收藏
          const res = await tiktokUnCollect(params, token)
          if (res.data.code === 200) {
            this.isCollect = !isCollect
          } else {
            uni.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      },
      async lickOrCollect(val, token) {
        if (val === 'isLike') {
          await this.lickRequest(token);
        } else if (val === 'isCollect') {
          await this.collectRequest(token);
        }
      },
			// 点赞/收藏
			likeCollect(val) {
			  if (!this.userInfo) {
			    this.getUserInfoLogin((token) => {
			      this.lickOrCollect(val, token)
			    })
        } else {
          this.lickOrCollect(val)
        }
			},
      async loginFunc(res, userInfo, callBack) {
        const params = {
          code: res.code,
          encryptedData: userInfo.encryptedData,
          iv: userInfo.iv
        }
        // 用户授权登录
        await loginTiktok(params).then(res => {
          if (res.data.code === 200) {
            uni.setStorage({
              key: 'userInfo',
              data: res.data.data.userInfo,
            })
            this.userInfo = res.data.data.userInfo;
            uni.setStorage({
              key: 'token',
              data: res.data.data.access_token
            })
            let headers = {
              TiktokAuthorization: res.data.data.access_token
            }
            this.checkUserDownload(headers)
            callBack && callBack(headers)
            this.searchIsLike(headers)
            this.searchisCollect(headers)
          } else {
            uni.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }).catch(res => {})
      },
      // 获取用户信息
      async getUserInfoLogin(callBack) {
        uni.getSetting({
          success: (settingObj) => {
            if (settingObj.authSetting['scope.userInfo'] === undefined || settingObj.authSetting['scope.userInfo']) {
              uni.login({
                force: true,
                success: (res) => {
                  uni.getUserInfo({
                    withCredentials: true,
                    success: async (userInfo) => {
                      await this.loginFunc(res, userInfo, callBack)
                    },
                    complete: () => {

                    },
                    fail: (errMsg) => {

                    }
                  })
                },
                complete: () => {

                },
                fail: (errMsg) => {

                }
              })
            } else {
              uni.showModal({
                title: '您已拒绝授权用户信息',
                content: '是否进入权限管理，调整授权？',
                success: function (res) {
                  if (res.confirm) {
                    uni.openSetting({
                      success: (settingRes) => {
                        if (settingRes.authSetting['scope.userInfo']) {
                          uni.login({
                            force: true,
                            success: (res) => {
                              uni.getUserInfo({
                                withCredentials: true,
                                success: async (userInfo) => {
                                  await this.loginFunc(res, userInfo, callBack)
                                },
                                complete: () => {

                                },
                                fail: (errMsg) => {

                                }
                              })
                            },
                            complete: () => {

                            },
                            fail: (errMsg) => {

                            }
                          })
                        }
                      },
                      fail: () => {

                      }
                    })
                  } else if (res.cancel) {
                    console.log('用户点击取消');
                  }
                }
              });
            }
          }
        })
      },
			//写入图片广告收益
			async insertPreAdProfit(token) {
				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, token);
				if (res.data.code === 200) {
					console.log("写入广告收益成功!")
					this.adResult = res.data.code;
				} else {
					uni.showToast({
						title: '图片下载失败!',
						icon: 'none'
					})
				}
			},

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

			//检查某平台用户当日下载次数是否超标
			async checkUserDownload(token) {
				const params = {
					userId: this.userInfo.id,
					appType: '0',
					platform: '0'
				}
				const res = await checkUserCanDownload(params, token);
				if (res.data.code === 200) {
					console.log("当日下载结果为", res.data.data)
					this.canDownload = res.data.data;
				} else {
					uni.showToast({
						title: '检查下载状态失败!',
						icon: 'none'
					})
				}
			},
      authDownload(url) {
        if (!this.userInfo) {
          this.getUserInfoLogin((token) => {
            this.download(url, token)
          })
        } else {
          this.download(url)
        }
      },
			// 下载
			download(url, token) {
				let that = this;
				if (that.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) => {
												if (res.statusCode === 200) {
													uni.saveImageToPhotosAlbum({
														//图片路径，不支持网络图片路径
														filePath: res.tempFilePath,
														success: (res) => {

														},
														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(token);
																			that.insertPreInviteProfit(token);
																		}
																	});
															}
														},
													});
												} else {
													uni.showToast({
														title: "下载失败！",
														icon: 'none'
													});
												}
											}
										})
									},
									//授权失败
									fail: () => {
										uni.hideLoading();
										uni.showModal({
											title: "您已拒绝获取相册权限",
											content: "是否进入权限管理，调整授权？",
											success: (res) => {
												if (res.confirm) {
													//调起客户端小程序设置界面，返回用户设置的操作结果。（重新让用户授权）
													uni.openSetting({
														success: (res) => {

														},
													});
												} 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();
										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="scss">
	.imgDetail {
		height: 100vh;
		width: 100vw;
		overflow: auto;
		position: relative;
    display: flex;
    align-items: center;
    justify-content: center;

		.main-img {
			width: 100%;
			height: 100%;
      box-shadow: 2rpx 4rpx 8rpx rgba(0, 0, 0, 0.25);
		}
  }

  .toolbar {
    width: 60px;
    background-color: rgba(248, 248, 248, 0.5);
    /* 模糊大小就是靠的blur这个函数中的数值大小 */
    backdrop-filter: blur(4rpx);
    position: fixed;
    bottom: 120rpx;
    right: 40rpx;
    border-radius: 60px;
    padding-top: 40rpx;
    box-shadow: 2rpx 4rpx 8rpx rgba(0, 0, 0, 0.25);

    .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>
