<template>
<view>
    <!-- 二维码 -->
    <tkiQrcode style="position:fixed;left:-9999px;top:0;" ref="qrcode" :val="qrcodeVal" :size="90" unit="px" background="#fff" foreground="#000" pdground="#000" lv="3" @result="onResultQrCode" icon="/static/imgs/avatar-login.png" iconSize="15" />
    <!-- 海报 -->
    <canvas v-if="refreshCanvas" canvas-id="myCanvas" class="myCanvas" style="width:375px;height:500px;position:fixed;left:-9999px;top:0;" />
</view>
</template>

<script>
import { canvasTextAutoLine, circleImgOne } from '../utils/tools'
import tkiQrcode from 'tki-qrcode'
const app = getApp()
try{
	const $router = app.globalData.$router
} catch (error) {

}

export default {
  name: 'createShareImage',
  props: {
		goodsParams: {
			type: Object,
			default: () => ({})
		},
		isJdGoods: {
			type: Boolean,
			default: () => false
		},
    isPddGoods: {
      type: Boolean,
      default: () => false
    },
    isDyGoods : {
      type: Boolean,
      default: () => false
    }
	},
	components: {
		tkiQrcode,
	},
  data() {
    return {
			search_goods:{},
			search_con: '',
			show:false,

			isLogin: false,
			isShowTbAuth: false, // 控制是否展示淘宝授权弹框
			refreshCanvas: true, // 更新canvas
			canvasImg: '', // 海报图片
			qrcodeVal: '', // 二维码链接
			qrcodeImg: '', // 二维码图片
			posterInfo: {}, // 海报信息
		}
  },
  mounted(){
		this.handleShareGoods()
  },
  methods:{
		// 分享商品海报
		async handleShareGoods() {
			try {
				// 获取商品海报参数
				if (this.isJdGoods) { // 京东商品 => 构造京东海报参数
					this.posterInfo = await this.handleGetJdPosterInfo()
					// 获取二维码图片
					this.handleGetQrCodeImg(this.posterInfo.url_info.shortURL)
				} else if(this.isPddGoods){//拼多多
          this.posterInfo = await this.handleGetPddPosterInfo()
          // 获取二维码图片
          this.handleGetQrCodeImg(this.posterInfo.url_info.short_url)
        }  else if (this.isDyGoods) { // 抖音
          this.posterInfo = await this.handleGetDyPosterInfo()
          // 获取二维码图片
          this.handleGetQrCodeImg(this.posterInfo.url_info.share_link)
        }else {
					this.posterInfo = await this.handleGetPosterInfo()
					// 获取二维码图片
					this.handleGetQrCodeImg(this.posterInfo.url)
				}

			} catch (error) {
				console.log('error => ', error)
			}
		},
    // 获取分享商品海报的参数信息(拼多多)
    handleGetPddPosterInfo() {
      const { goods_id } = this.goodsParams
      return new Promise(async (resolve, reject) => {
        try {
          const url = this.$api_pdd.shareCommonGoods;
          const params = { goods_id }
          uni.showLoading({ title: '加载中...', mask: true })
          const { data: res } = await this.$postJSON(url, params)
          uni.hideLoading()
          if (res && res.errno == 0) {
            let data = res.rst.data;
            data.small_images = data.small_images.map((v)=>{
              return v
            })
            resolve({ ...data })
          } else {
            uni.showToast({ title: res.err || '操作失败', icon: 'none' })
            reject(res.err || '操作失败')
          }
        } catch (error) {
          reject(error)
        }
      })
    },

    // 获取分享商品海报的参数信息(抖音)
    handleGetDyPosterInfo() {
      const { goods_id } = this.goodsParams
      return new Promise(async (resolve, reject) => {
        try {
          const url = this.$api_dy.shareCommonGoods;
          const params = { product_id: goods_id }
          uni.showLoading({ title: '加载中...', mask: true })
          const { data: res } = await this.$postJSON(url, params)
          uni.hideLoading()
          if (res && res.errno == 0) {
            let data = res.rst;
            data.small_images = data.small_images.map((v)=>{
              return v
            })
            resolve({ ...data })
          } else {
            uni.showToast({ title: res.err || '操作失败', icon: 'none' })
            reject(res.err || '操作失败')
          }
        } catch (error) {
          reject(error)
        }
      })
    },
		// 获取分享商品海报的参数信息(京东)
		handleGetJdPosterInfo() {
			const { goods_id } = this.goodsParams
			return new Promise(async (resolve, reject) => {
				try {
					const url = this.$api_jd.jdShareCommonGoods;
					const params = { goods_id }
					uni.showLoading({ title: '加载中...', mask: true })
					const { data: res } = await this.$postJSON(url, params)
					uni.hideLoading()
					if (res && res.errno == 0) {
						let data = res.rst.data;
						data.small_images = data.small_images.map((v)=>{
							return v.url
						})
						resolve({ ...data })
					} else {
						uni.showToast({ title: res.err || '操作失败', icon: 'none' })
						reject(res.err || '操作失败')
					}
				} catch (error) {
					reject(error)
				}
			})
		},
		// 获取分享商品海报的参数信息
		handleGetPosterInfo() {
			const { goods_id, is_coupon, coupon_price, price, discount_price, commission_rate, coupon_end_time, coupon_start_time } = this.goodsParams
			return new Promise(async (resolve, reject) => {
				try {
					const url = this.$api.goodsItem_shareCommonGoods;
					const params = { goods_id, is_coupon, coupon_price, price, discount_price, commission_rate, coupon_end_time, coupon_start_time }
					uni.showLoading({ title: '加载中...', mask: true })
					const { data: res } = await this.$postJSON(url, params)
					uni.hideLoading()
					if (res && res.errno == 0 && res.rst.data.goods_id) {
						resolve({ ...res.rst.data })
					} else {
						uni.showToast({ title: res.err || '操作失败', icon: 'none' })
						reject(res.err || '操作失败')
					}
				} catch (error) {
					reject(error)
				}
			})
		},
		// 根据url链接生成二维码图片
		async handleGetQrCodeImg(url) {
			try{
				this.qrcodeVal = url
				await this.$nextTick()
				this.$refs.qrcode._makeCode()
			}catch(e){
				// 绘制二维码图片失败
				this.$emit('getCanvasImage', {image: '', posterInfo: this.posterInfo})
			}
		},
		// 监听二维码生成完毕
		onResultQrCode(res){
			this.qrcodeImg = res
			// 开始绘制海报
			this.handleDrawPoster(this.posterInfo)
		},
		// 重新挂载canvas组件(刷新canvas内容)
		async handleRefreshCanvas() {
			this.refreshCanvas = false
			await this.$nextTick()
			this.refreshCanvas = true
		},
		// 绘制海报
		async handleDrawPoster(posterInfo) {
			const shopTypeLogos = {
				4: '/static/imgs/jd-icon.png',
				1: '/static/imgs/icon-tmall.png',
				0: '/static/imgs/icon-tb.png',
				6: '/static/imgs/pdd-icon.png',
				5: '/static/imgs/icon-dy.png',
			}
			try {
				const goodsTitle = posterInfo.title
				const shopTypeLogo = shopTypeLogos[posterInfo.shop_type]
				const goodsImg = posterInfo.img
				const discountPrice = posterInfo.discount_price
				const price = posterInfo.price
				const userAvatar = posterInfo.userinfo.headimg
				const userName = posterInfo.userinfo.nickname
				const userCode = posterInfo.userinfo.invite_code
				const qrcodeImg = this.qrcodeImg

				uni.showLoading({ title: '加载中...', mask: true })
				this.handleRefreshCanvas() // 强制更新canvas内容

				const myCanvas = uni.createCanvasContext('myCanvas', this)
				myCanvas.beginPath();
				const canvasW = 375
				const canvasH = 500
				myCanvas.width = canvasW
				myCanvas.height = canvasH
				myCanvas.clearRect(0, 0, canvasW, canvasH);
				myCanvas.setFillStyle("#ffffff"); // 背景色
				myCanvas.fillRect(0, 0, canvasW, canvasH);
				myCanvas.closePath();

				// 店铺类型logo
				myCanvas.beginPath()
				myCanvas.drawImage(shopTypeLogo, 20, 8, 14, 14)
				myCanvas.closePath()

				// 商品名称
				myCanvas.beginPath()
				myCanvas.setFillStyle("#333");
				myCanvas.font = '13px Arial'
				canvasTextAutoLine(
					myCanvas,
					`    ${goodsTitle}`,
					20, // x轴坐标位置（视实际情况而定）
					20, // y轴坐标位置（视实际情况而定）
					260, // 文字显示最大宽度（视实际情况而定）
					20 // 文字行高（视实际情况而定）
				)
				myCanvas.closePath()

				// 商品主图
				myCanvas.beginPath()
				const goodsImgRes = await uni.getImageInfo({ src: goodsImg })
        if (goodsImgRes[1] && goodsImgRes[1].errMsg === 'getImageInfo:ok') {
					myCanvas.drawImage(goodsImgRes[1].path, 30, 55, canvasW - 60, canvasW - 60)
				}
				myCanvas.closePath()

				// 券后价
				myCanvas.beginPath()
				const priceTop = 55 + canvasW - 60 + 30
				myCanvas.setFillStyle("#EC0B00");
				myCanvas.font = '14px Arial'
				myCanvas.fillText(`券后 ￥${discountPrice}`, 20, priceTop)
				myCanvas.closePath()

				// 原价
				myCanvas.beginPath()
				const discountPriceWidth = myCanvas.measureText(`券后 ￥${discountPrice}`).width + 40
				const priceWidth = myCanvas.measureText(price).width + 20
				myCanvas.setFillStyle("#333");
				myCanvas.font = '14px Arial'
				myCanvas.fillText(`￥${price}`, discountPriceWidth, priceTop)
				myCanvas.rect(discountPriceWidth, priceTop - 5, priceWidth, 1)
				myCanvas.setFillStyle('#333')
				myCanvas.fill()
				myCanvas.closePath()

				// 二维码
				const qrcodeRes = await uni.getImageInfo({ src: qrcodeImg })
				if (qrcodeRes[1] && qrcodeRes[1].errMsg === 'getImageInfo:ok') {
					myCanvas.drawImage(qrcodeRes[1].path, 270, priceTop - 10, 90, 90)
				}

				// 用户昵称
				myCanvas.beginPath()
				const userNameTop = priceTop + 20 + 16
				myCanvas.setFillStyle("#333");
				myCanvas.font = '13px Arial'
				myCanvas.fillText(userName, 20 + 12 + 12 + 10, userNameTop)
				myCanvas.closePath()

				// 邀请码
				myCanvas.beginPath()
				const userCodeTop = userNameTop + 34
				myCanvas.setFillStyle("#333");
				myCanvas.font = '13px Arial'
				myCanvas.fillText(`邀请码：${userCode}`, 20, userCodeTop)
				myCanvas.closePath()

				// 用户头像
				myCanvas.beginPath()
				const userAvatarTop = priceTop + 20
				const userAvatarRes = await uni.getImageInfo({ src: userAvatar })
				if (userAvatarRes[1] && userAvatarRes[1].errMsg === 'getImageInfo:ok') {
					circleImgOne(myCanvas, userAvatarRes[1].path, 20, userAvatarTop, 12)
				}
				myCanvas.closePath()

				myCanvas.draw(false, async () => {
					await this.$nextTick()
					uni.canvasToTempFilePath({
						fileType: 'png',
						canvasId: 'myCanvas',
						success: (res) => {
							this.canvasImg = res.tempFilePath
							this.$emit('getCanvasImage', {image: this.canvasImg, posterInfo: this.posterInfo})
							// wx.showShareImageMenu({
							// 	path: this.canvasImg
							// })
						},
						fail: (err) => {
							this.$emit('getCanvasImage', {image: this.canvasImg, posterInfo: this.posterInfo})
						}
					}, this)
				})
			} catch (error) {
				this.$emit('getCanvasImage', {image: this.canvasImg, posterInfo: this.posterInfo})
			} finally {
				uni.hideLoading()
			}
		},
  }
}
</script>

<style scoped lang='scss'>
  .clipboard-container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 648rpx;
	min-height: 400rpx;
    padding: 52rpx 28rpx;
    border-radius: 120rpx 120rpx 32rpx 32rpx;
	background-color: #FFFFFF;
	z-index: 999;
	.clipbpard_bg{
		border-radius: 120rpx 120rpx 0 0;
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
	}
	.content{
		position: relative;
		z-index: 9;
	}
	.mask-title{
		display: flex;
		align-items: center;
		justify-content: center;
		color: #181818;
		font-size: 40rpx;
		line-height: 56rpx;
		font-weight: bold;
		letter-spacing: 2rpx;
		.clipbpard_title_img{
			width: 30rpx;
			height: 30rpx;
			margin: 0 16rpx;
		}
	}
    .close {
      position: absolute;
      bottom: -100rpx;
	  left: 0;
	  right: 0;
	  margin: auto;
      width: 60rpx;
      height: 60rpx;
    }
    .goods-container{
		display: flex;
		align-items: center;
		margin-top: 84rpx;
		.goods-img{
			width: 200rpx;
			height: 200rpx;
			border-radius: 18rpx;
		}
		.goods-info{
			flex: 1;
			margin-left: 20rpx;
			.goods-title{
				font-size: 28rpx;
				color: #181818;
				line-height: 40rpx;
				/* // 超出两行省略号 */
				word-break: break-all;
				overflow: hidden;
				-webkit-line-clamp: 2;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-box-orient: vertical;
			}
			.goods-price{
				color: #FF4040;
				font-size: 36rpx;
				line-height: 50rpx;
				margin-top: 14rpx;
			}
			.goods-quan{
				display: flex;
				align-items: center;
				margin-top: 14rpx;
				.coupon-wrap {
				  margin-right: 30rpx;
				  display: flex;
				  align-items: center;
				  width: 155rpx;
				  height: 36rpx;
				  background-image: url("/static/imgs/quan.png");
				  background-repeat: no-repeat;
				  background-size: 100% 100%;
				  color: #FF4040;
				  font-size: 26rpx;
				  &.coupon-fan{
					  background-image: url("/static/imgs/fan.png");
					  color: #AE4300;
				  }
				  .label {
				    width: 48rpx;
				    text-align: center;
				  }
				  .value {
				    flex: 1;
				    text-align: center;
				  }
				}
			}
		}
	}

	.clipbpard-buttones{
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 70rpx;
		.clipbpard-button{
			width: 252rpx;
			height: 80rpx;
			background: linear-gradient(90deg, #FF9048 0%, #FB3F3C 100%);
			border-radius: 40rpx;
			color: #FFFFFF;
			font-size: 32rpx;
			line-height: 80rpx;
			text-align: center;
			margin: 0 10rpx;
			&.share{
				background: #FFEED9;
				color: #AE4300;
			}
			text{
				margin-left: 10rpx;
			}
		}
	}
	.search_con{
		color: #181818;
		font-size: 28rpx;
		line-height: 40rpx;
		padding: 90rpx 24rpx 0;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 6;
		overflow: hidden;
		/*! autoprefixer: off */
		-webkit-box-orient: vertical;
		/*! autoprefixer: on */
		word-break: break-all ;
	}
  }
</style>
