<template>
	<view class="app">
		<view class="vacancies">
			<image src="../../static/jifenbeij.png" mode=""></image>
			<view class="lefttext">
				积分余额
			</view>
			<view class="righttext">
				<!-- <image src="../../static/jfgz.png" mode=""></image>
				<view class="">
					积分规则
				</view> -->
			</view>
			<view class="title">
				{{list.integral}}
			</view>
			<view class="centertext">
				<!-- 20积分将于2022.01.01过期 -->
			</view>
			<view class="bottombutton" @tap='gainshow=true'>
				获取积分
			</view>
		</view>
		<view class="titles">
			积分兑换
		</view>
		<view class="items" v-if="goodslist.length>0">
			<view class="item" v-for="(item,index) in goodslist" :key="index">
				<image :src="item.attributePitureUrl" mode=""></image>
				<view class="title">
					{{item.goodsName}}
				</view>
				<view class="text">
					{{item.integralExchangeCount}}{{item.goodsUnit}}
				</view>
				<view class="jifen">
					需使用
					<span style='padding: 0 5rpx;'> {{item.integralExchangeSill}}</span>
					积分兑换
				</view>
				<view class="btn" @tap='buyshowtrue(item)'>
					立即兑换
				</view>
			</view>
		</view>
		<view class="noorder" v-else>
			<u-empty mode="list" icon-size='220' text='暂无可兑换商品'></u-empty>
		</view>
		<u-mask :show="gainshow" @click="gainshow = false">
			<view class="mask" @click.stop="">
				<image class="close" src="../../static/gb.png" mode="" @tap='gainshow=false'></image>
				</image>
				<view class="title">
					获取方式
				</view>
				<view class="maskitems">
					<view class="item">
						<image src="../../static/qiandao.png" mode=""></image>
						<view class="titletext">
							累计签到
							<span style='padding: 0 5rpx;' v-if="list.totalSignInDays"> {{list.totalSignInDays}}</span>
							<span style='padding: 0 5rpx;' v-else>0</span>
							天(当前签到
							<span style='padding: 0 5rpx;' v-if="list.patientSignInCount">
								{{list.patientSignInCount}}</span>
							<span style='padding: 0 5rpx;' v-else>0</span>
							天)
						</view>
						<view class="text">
							＋<span style='padding: 0 5rpx;' v-if="list.signInCount"> {{list.signInCount}}</span>
							<span style='padding: 0 5rpx;' v-else>0</span>积分
						</view>
						<view class="btn" @tap='signIninfo' v-if='list.todaySignInCount==0&&list.totalSignInDays>0'>
							签到
						</view>
						<view class="btn" v-if='list.todaySignInCount==1'>
							已签到
						</view>
					</view>
					<view class="item" style="background-color: #F44B2F;">
						<image src="../../static/yaoqing.png" mode=""></image>
						<view class="titletext">
							每邀请
							<span style='padding: 0 5rpx;'> 1</span>
							位好友
						</view>
						<view class="text">
							＋
							<span style='padding: 0 5rpx;' v-if="list.inviteFriends"> {{list.inviteFriends}}</span>
							<span style='padding: 0 5rpx;' v-else>0</span>
							积分
						</view>
						<view class="btn" style="color: #F44B2F;" @tap='yaoqingshowtrue' v-if='list.inviteFriends>0'>
							去完成
						</view>
					</view>
				</view>
			</view>
		</u-mask>
		<u-mask :show="buyshow" @click="buyshow = false">
			<view class="PurchasePage" @click.stop=''>
				<image class="close" src="../../static/gb.png" mode="" @tap='buyshow=false'></image>
				</image>
				<view class="topcontent" style="width: 96%;">
					<view class="image">
						<image :src="goodsitem.goodsPictureUrl" mode=""></image>
					</view>
					<view class="title" v-if="goodsitem.goodsName">
						{{goodsitem.goodsName}}
					</view>
					<view class="title" v-else>
						暂无
					</view>
					<view class="prices">
						<span class="price">
							{{goodsitem.integralExchangeSill}}积分
						</span>
					</view>
					<view class="goodsStock">
						库存数量:{{goodsitem.goodsStock}}
					</view>
				</view>
				<view class="bodys" @tap='upaddress()'>
					<view class="addressinfo">
						<image src="../../static/locatinsmall.png" mode=""></image>
						<span v-if="loginFlag">
							<view class="namephone" v-if='userid'>
								{{updata.receiver}},{{updata.phone}}
							</view>
							<view class="address" v-if='userid'>
								{{updata.receiveAddress}}
							</view>
						</span>
						<view class="namephone" v-else>
							前往完善个人信息
						</view>
						<view class="picture2">
							<u-icon name="arrow-right" color="black" size="28"></u-icon>
						</view>
					</view>
				</view>
				<view class="centercontent topcontent">
					<view class="header">
						商品规格
					</view>
					<view style="display: flex;justify-content: flex-start;flex-wrap: wrap;">
						<view class="Productmodel productmodel">
							<image :src="goodsitem.attributePitureUrl" mode=""></image>
							<view class="">
								{{goodsitem.integralExchangeCount}}{{goodsitem.goodsUnit}}
							</view>
						</view>
					</view>
				</view>
				<view class="buy" @tap="upbuy">
					立即兑换
				</view>
			</view>
		</u-mask>
		<u-popup v-model="yaoqingshow" mode="center" :closeable='true' :close='yaoqingshowfalse'>
			<view class="yaoqing">
				<r-canvas ref="rCanvas" v-if="yaoqingshow"></r-canvas>
			</view>
			<view class="yaoqbtn" @tap='draw'>
				保存到相册
			</view>
			<view class="yaoqbtn2" @tap='fenx'>
				分享给好友
			</view>
		</u-popup>
		<u-mask :show="usershow" class='masks'>
			<view class="information">
				<image src="../../static/information.png" mode=""></image>
				<view class="title">
					请完善个人信息
				</view>
				<view class="cancel" @tap='usershow=false'>
					取消
				</view>
				<view class="determine" @tap='goinformation'>
					去完善
				</view>
			</view>
		</u-mask>
		<u-toast ref="uToast" />
	</view>
</template>
<script>
	import {
		signIn,
		selectPatientSignIn,
		selectExchangeGoods,
		integralGoodsOrder
	} from '@/api/integral/index.js'
	import {
		inviteFriends
	} from '@/api/Personal/Personal.js';
	import {
		goodPatientInfo
	} from '@/api/modifyAddress/modifyAddress.js';
	import {
		AppIdentification
	} from '@/api/AppIdentification/index.js'
	import baseurl from '../../api/baseurl';
	import rCanvas from "@/components/r-canvas/r-canvas.vue"
	export default {
		components: {
			rCanvas
		},
		data() {
			return {
				timer: null,
				baseurl: '',
				patientId: null,
				integral: 0,
				usershow: false, //go完善
				gainshow: false, //积分邀请
				buyshow: false, //兑换购买
				yaoqingshow: false,
				yaoqingimg: null,
				yapqingbeijingimg: null,
				list: {
					integral: 0
				},
				inviteimg: null, //邀请二维码
				pageNum: 1,
				pageSize: 10,
				goodstotal: 0,
				goodslist: [],
				goodsitem: null,
				userid: null,
				updata: {
					"orderChannel": 'WECHAT_APPLET',
					"originalTotalPrice": null,
					"integralExchangeSill": null,
					"integralExchangeCount": null,
					"orderType": "INTEGRAL_EXCHANGE",
					"buySource": "SHOPPING_MALL",
					"integralDeductionCount": null,
					"attributeDetailsId": null,
					"discountPrice": null,
					"giveIntegral": null,
					"goodsAttributeContent": null,
					"goodsAttributeDetailsId": null,
					"goodsAttributeId": null,
					"goodsAttributeName": null,
					"goodsCount": null,
					"goodsName": null,
					"goodsPrice": null,
					"goodsStock": null,
					"nurseStationId": null,
					"patientId": null,
					"phone": "18963146613",
					"receiveAddress": null,
					"receiver": null,
				},
				loginFlag: false,
			};
		},
		onLoad(options) {},
		onShow() {
			this.baseurl = baseurl
			this.pageNum = 1
			this.selectExchangeGoodsinfo();
			this.baseurl = baseurl
			this.yapqingbeijingimg = baseurl + '/profile/appletPicture/inviteFriendsTwo.png'
			var that = this
			const value = uni.getStorageSync('patientId');
			if (value) {
				that.patientId = value
				that.updata.patientId = value
				that.selectPatientSignInifo();
				that.user();
				AppIdentification(value).then(res => {
					if (res.code == 200) {
						if (res.data.loginFlag) {
							that.loginFlag = true
						}
					}
				})
				goodPatientInfo(value).then(res => {
					if (res.code == 200) {
						if (res.data.length > 0) {
							var user = res.data.filter(e => e.id == that.userid)
							if (user.length >= 1) {
								that.updata.receiver = user[0].receiveName
								that.updata.receiveAddress = user[0].areaName + user[0].receiveAddress
								that.updata.phone = user[0].receivePhone
								that.userid = user[0].id
							} else {
								that.updata.receiver = res.data[0].receiveName
								that.updata.receiveAddress = res.data[0].areaName + res.data[0].receiveAddress
								that.updata.phone = res.data[0].receivePhone
								that.userid = res.data[0].id
							}
						}
					}
				})
			} else {}
			let useritem = null
			uni.$on('updata', function(data) {
				if (data.useritem) {
					useritem = JSON.parse(data.useritem)
					that.updata.receiver = useritem.receiveName
					that.updata.phone = useritem.receivePhone
					that.updata.receiveAddress = useritem.areaName + useritem.receiveAddress
					that.userid = useritem.id
				}
			})
		},
		methods: {
			yaoqingshowtrue() {
				this.yaoqingshow = true
				this.$nextTick(async () => {
					await inviteFriends(this.patientId).then(res => {
						this.inviteimg = res.msg
					})
					uni.showLoading({
						title: '加载中'
					});
					// 初始化
					await this.$refs.rCanvas.init({
						canvas_id: "rCanvas"
					})
					// 画图
					await this.$refs.rCanvas.drawImage({
						url: this.yapqingbeijingimg,
						x: 0,
						y: 0,
						w: 300,
						h: 530
					}).catch(err_msg => {
						uni.showToast({
							title: err_msg,
							icon: "none"
						})
					})
					await this.$refs.rCanvas.drawImage({
						url: baseurl + this.inviteimg,
						x: 85,
						y: 340,
						w: 130,
						h: 130
					}).catch(err_msg => {
						uni.showToast({
							title: err_msg,
							icon: "none"
						})
					})
					// 画文字
					await this.$refs.rCanvas.drawText({
						text: "智慧康养泉城，医护关怀到家",
						x: 150,
						y: 300,
						font_color: "#444444",
						font_size: 12,
						font_weight: 600,
						text_align: 'center'
					}).catch(err_msg => {
						uni.showToast({
							title: err_msg,
							icon: "none"
						})
					})
					await this.$refs.rCanvas.drawText({
						text: "超多福利，快来体验吧！",
						x: 150,
						y: 320,
						font_color: "#444444",
						font_size: 12,
						font_weight: 600,
						text_align: 'center'
					}).catch(err_msg => {
						uni.showToast({
							title: err_msg,
							icon: "none"
						})
					})
					await this.$refs.rCanvas.drawText({
						text: "泉医到家小程序",
						x: 150,
						y: 500,
						font_color: "#444444",
						font_size: 10,
						text_align: 'center'
					}).catch(err_msg => {
						uni.showToast({
							title: err_msg,
							icon: "none"
						})
					})
					await this.$refs.rCanvas.drawText({
						text: "（长按识别二维码开启健康之旅）",
						x: 150,
						y: 515,
						font_color: "#444444",
						font_size: 7,
						text_align: 'center'
					}).catch(err_msg => {
						uni.showToast({
							title: err_msg,
							icon: "none"
						})
					})
					// 生成海报
					await this.$refs.rCanvas.draw((res) => {
						this.yaoqingimg = res.tempFilePath
						uni.hideLoading();
						//res.tempFilePath：生成成功，返回base64图片
						// 保存图片
						// this.$refs.rCanvas.saveImage(res.tempFilePath)
					})
				})
			},
			//保存
			draw() {
				// 保存图片
				this.$refs.rCanvas.saveImage(this.yaoqingimg).then(res => {
					uni.showToast({
						title: '保存成功',
						duration: 2000
					});
				}).catch(err => {
					uni.showToast({
						icon: 'error',
						title: '保存失败',
						duration: 2000
					});
				})
			},
			//分享
			fenx() {
				wx.showShareImageMenu({
					path: this.yaoqingimg,
				})
			},
			yaoqingshowfalse() {
				this.yapqingshow = false;
				this.$nextTick(async () => {
					await this.$refs.rCanvas.clearCanvas((res) => {})
					await this.$refs.rCanvas.setCanvasWidth(0)
					await this.$refs.rCanvas.setCanvasHeight(0)
				})
			},
			//兑换
			upbuy() {
				var that = this
				this.updata.goodsCount = this.updata.integralExchangeCount
				const value = uni.getStorageSync('patientId');
				const value2 = uni.getStorageSync('openid');
				if (value && value2) {
					AppIdentification(value).then(res => {
						if (res.code == 200) {
							if (res.data.loginFlag) {
								integralGoodsOrder(that.updata).then(res => {
									if (res.code == 200) {
										that.selectPatientSignInifo();
										that.$refs.uToast.show({
											title: '兑换商品成功',
											type: 'success',
											url: `/pages/orderDetails/orderDetails?goodsOrderId=${res.data.id}`
										})
										that.buyshow = false
									} else {
										that.$refs.uToast.show({
											title: res.msg,
											type: 'error'
										})
									}
								})
							} else {
								that.usershow = true
							}
						} else {
							that.$refs.uToast.show({
								title: '请先登录',
								type: 'error',
								duration: '2000',
								url: '/pages/login/login'
							})
						}
					})
				} else {
					that.$refs.uToast.show({
						title: '请先登录',
						type: 'error',
						duration: '2000',
						url: '/pages/login/login'
					})
				}
			},
			//跳转到全部收货地址
			upaddress() {
				if (this.updata.receiver) {
					uni.navigateTo({
						url: `/pages/modifyAddress/modifyAddress?updata=${JSON.stringify(this.updata)}`
					})
				} else {
					const value = uni.getStorageSync('openid');
					const value2 = uni.getStorageSync('patientId');
					if (value && value2) {
						uni.navigateTo({
							url: '/pages/information/information'
						})
					} else {
						this.$refs.uToast.show({
							title: '未登录,请先登录',
							type: 'error',
							url: '/pages/login/login'
						})
					}
				}
			},
			///兑换
			buyshowtrue(item) {
				this.buyshow = true
				this.goodsitem = item
				this.updata.nurseStationId = item.nurseStationId
				this.updata.goodsAttributeName = this.goodsitem.attributeDetailsName
				this.updata.goodsAttributeId = this.goodsitem.goodsAttributeId
				this.updata.goodsAttributeDetailsId = this.goodsitem.attributeDetailsId
				this.updata.integralExchangeSill = this.goodsitem.integralExchangeSill
				this.updata.integralExchangeCount = this.goodsitem.integralExchangeCount
				this.updata.originalTotalPrice = 0
				this.updata.goodsStock = this.goodsitem.goodsStock
				this.updata.goodsName = this.goodsitem.goodsName
				this.updata.goodsPrice = this.goodsitem.goodsPrice
				this.updata.goodsCount = 1
			},
			//可兑换商品
			selectExchangeGoodsinfo() {
				this.pageNum = 1
				selectExchangeGoods(this.pageNum, this.pageSize).then(res => {
					if (res.code == 200) {
						res.rows.forEach(e => {
							e.goodsPictureUrl = baseurl + e.goodsPictureUrl
							e.attributePitureUrl = baseurl + e.attributePitureUrl
						})
						this.goodslist = res.rows
						this.goodstotal = res.total
					} else if (res.code == 9999) {
						this.$refs.uToast.show({
							title: '未登录,请先登录',
							type: 'error',
						})
					}
				})
			},
			//积分
			selectPatientSignInifo() {
				selectPatientSignIn(this.patientId).then(res => {
					this.list = res.data
				})
			},
			//点击签到
			signIninfo() {
				var that = this
				const value = uni.getStorageSync('patientId');
				const value2 = uni.getStorageSync('openid');
				if (value && value2) {
					AppIdentification(value).then(res => {
						if (res.code == 200) {
							if (res.data.loginFlag) {
								signIn(value).then(res => {
									if (res.code == 200) {
										that.selectPatientSignInifo();
										that.$refs.uToast.show({
											title: '今日签到成功',
											type: 'success',
											duration: '1000',
										})
									} else {
										that.$refs.uToast.show({
											title: '签到失败',
											type: 'error',
											duration: '1000',
										})
									}
								})
							} else {
								that.usershow = true
							}
						} else {
							that.$refs.uToast.show({
								title: '请先登录',
								type: 'error',
								duration: '2000',
								url: '/pages/login/login'
							})
						}
					})
				} else {
					that.$refs.uToast.show({
						title: '请先登录',
						type: 'error',
						duration: '2000',
						url: '/pages/login/login'
					})
				}
			},
			// 收件人
			user() {
				goodPatientInfo(this.patientId).then(res => {
					if (res.data.length > 0) {
						var list = res.data.filter(e => e.defaultAddressFlag == 1)
						if (list.length >= 1) {
							this.updata.receiver = list[0].receiveName
							this.updata.receiveAddress = list[0].areaName + list[0].receiveAddress
							this.updata.phone = list[0].receivePhone
							this.userid = list[0].id
						} else {
							this.updata.receiver = res.data[0].receiveName
							this.updata.receiveAddress = res.data[0].areaName + res.data[0].receiveAddress
							this.updata.phone = res.data[0].receivePhone
							this.userid = res.data[0].id
						}
					}
				})
			},
			//跳转完善页面
			goinformation() {
				this.usershow = false
				uni.navigateTo({
					url: '/pages/information/information'
				})
			},
		},
		onReachBottom() { //下滑加载
			if (this.goodslist.length >= this.goodstotal) {} else {
				this.pageNum++;
				selectExchangeGoods(this.pageNum, this.pageSize).then(res => {
					res.rows.forEach(e => {
						e.goodsPictureUrl = baseurl + e.goodsPictureUrl
						this.goodslist.push(e)
					})
				})
			}
		},
		onPullDownRefresh() { //下拉刷新
			this.pageNum = 1;
			this.selectExchangeGoodsinfo();
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
	}
</script>

<style lang="scss">
	@import "./integral.scss";
</style>
