<template>
	<view>
		<view style="color: #000000;">
			<tn-nav-bar backgroundColor="#ffffff" :bottomShadow="false">{{commission_alias}}</tn-nav-bar>
			<view :style="{height: tobheight+'px'}"></view>
		</view>
		<view style="width:100%;height: 100%;padding-right: 30rpx;">

			<view class="commission-wrap" :class="{ blur: !hasAuth }">
				<!-- 用户资料 -->
				<view class="user-card">
					<view class="card-top u-flex u-row-between">
						<view class="u-flex">
							<view class="head-img-box">
								<image class="head-img" :src="userInfo.avatar?userInfo.avatar:'/static/images/head.jpg'"
									mode=""></image>
							</view>
							<view class="u-flex-col">
								<view class="user-name">{{ userInfo.nickname }}</view>
								<view class="user-info-box u-flex">
									<view class="tag-box u-flex">
										<!-- <image v-if="commissionLv.image" class="tag-img" :src="commissionLv.image" mode=""></image> -->
										<text class="tag-title">{{ commissionLv.name }}</text>
										<!-- <view v-show="showLv" class="u-iconfont uicon-arrow-right" style="color: #fff;font-size: 28rpx;"></view> -->
									</view>
								</view>
							</view>
						</view>
						<view class="u-flex-col">
							<view class="u-flex-col u-col-center">
								<button class="u-reset-button log-btn u-m-b-20" @tap="toTeam">明细</button>
								<button class="u-reset-button look-btn" @tap="showMoney = !showMoney">
									<!-- <view class="u-iconfont" :class="showMoney ? 'uicon-eye-fill' : 'uicon-eye-off'" style="color: #fff;font-size: 50rpx;"></view> -->
									<u-icon :name="showMoney ? 'eye-fill':'eye-off'" color="#fff" size="22"></u-icon>
								</button>
							</view>
						</view>
					</view>
					<!-- 收益 -->
					<view class="card-bottom u-flex">
						<view class="u-flex-1 ">
							<view class="item-title">累计收入</view>
							<view class="item-detail">{{showMoney? money_total || 0.00:'****'}}</view>
						</view>
						<view class="u-flex-1 u-col-center">
							<view class="item-title">待入账佣金</view>
							<view class="item-detail">{{showMoney? on_cashout_money || 0.00:'****'}}</view>
						</view>
					</view>
				</view>

				<!-- 滚动明细 -->
				<view class="commission-log">
					<scroll-view scroll-y="true" @scrolltolower="loadMore" class="scroll-box log-scroll">
						<view class="log-item-box u-flex u-row-between" v-for="item in commissionLog" :key="item.id"
							@tap="$u.toast(item.remark)">
							<view class="log-item-wrap">
								<view class="log-item u-flex u-ellipsis-1 u-col-center">
									<view class="u-flex u-col-center ">
										<!-- <image
											class="log-img"
											:src="item.oper_type !== 'user' ? logMap[item.oper_type] : item.oper ? item.oper.avatar : logMap['admin']"
											mode=""
										></image> -->
										<!-- <image class="log-img" :src="appInfo.site_logo_path" mode=""></image> -->
										<image class="log-img" :src="item.oper" mode=""></image>
									</view>
									<view class="log-text u-ellipsis-1">{{ item.remark }}</view>
								</view>
							</view>
							<text class="log-time">{{ item.createtime }}</text>
						</view>
						<!-- 更多 -->
						<!-- <view class="loadmore-wrap" v-if="commissionLog.length"><u-loadmore :status="loadStatus" icon-type="flower" color="#f6f6f6" /></view> -->
					</scroll-view>
				</view>

				<!-- 功能菜单 -->
				<view class="menu-box u-flex">
					<view class="menu-item u-flex-col u-col-center" v-for="(menu, index) in menuList"
						v-if="!menu.isAgentFrom" :key="index" @tap="jump(menu.path)">
						<image class="item-img" :src="menu.img" mode=""></image>
						<view class="item-title">{{ menu.title }}</view>
					</view>
					<!-- #ifdef H5 -->
					<view @click="createPoster" class="menu-item u-flex-col u-col-center">
						<image class="item-img" src="https://file.shopro.top/imgs/commission/commission_icon5.png"
							mode=""></image>
						<view class="item-title">分享海报</view>
					</view>


					<view @click="sharelink" class="menu-item u-flex-col u-col-center">
						<image class="item-img" src="https://file.shopro.top/imgs/commission/commission_icon7.png"
							mode=""></image>
						<view class="item-title">分享链接</view>
					</view>
					<!-- #endif -->
				</view>
				<!-- #ifdef H5 -->
				<!-- <view class="bill">
					<u-button @click="createPoster" color="#ffc107" type="primary" shape="circle" text="推广海报"></u-button>
				</view> -->
				<!-- #endif -->


			</view>

			<!-- 佣金中心权限验证 -->
			<u-popup class="auth-box" :mask="false" v-model="showAuthModal" mode="center" :mask-close-able="false"
				close-icon-pos="top-left" border-radius="20">
				<view class="notice-box">
					<view class="img-wrap">
						<image class="notice-img" :src="authNotice.img" mode=""></image>
					</view>
					<view class="notice-title">{{ authNotice.title }}</view>
					<view class="notice-detail">{{ authNotice.detail }}</view>
					<button class="u-reset-button notice-btn"
						@tap="onAuthBtn(authNotice.btnPath)">{{ authNotice.btnText }}</button>
					<button class="u-reset-button back-btn" @tap="$Router.back()" v-if="!authNotice.hideBtn">返回</button>
					<button class="u-reset-button back-btn" @tap="hasAuth = true" v-else>取消</button>
				</view>
			</u-popup>

			<!-- 成为分销商条件 -->
			<u-popup v-if="showTerm" class="into-agent-modal" :bgStyle="{
					background: 'none'
				}" v-model="showTerm" mode="center" :mask="false" :mask-close-able="false">
				<view class="condition-box u-flex u-row-center u-col-center">
					<!-- 金额人数 -->
					<view class="goods-condition u-flex u-row-between" v-if="showMoneyTerm">

						<view class="btn-box u-flex-col u-p-20 u-col-center">
							<button class="u-reset-button buy-btn u-m-b-10" @tap="$Router.back()">知道了</button>
							<view class="tips">* 满足指定消费金额即可成为分销商</view>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
		<u-popup :show="showPoster" mode="bottom" @close="showPoster = false">
			<!-- <view :style="{height: tobheight+'px'}"></view> -->
			<scroll-view scroll-y="true" :style="{maxHeight: posterheight +'px'}">



				<view class="haibaoBox">
					<image :src="genBgHaibaoUrl" mode="" class="haibao"></image>

					<view class="bgList">
						<image
							@click="currBgIndex=index;poster_bg_img_path=info.poster_bg_img_path[index];createPoster();"
							:src="item" mode="" class="item" :class="[currBgIndex==index?'item_a':'']" v-for="(item,index) in info.poster_bg_img_path
"></image>
					</view>
					<view style="height: 78px;"></view>
					<view class="dygbhg">
						<view class="whole" @click="showPoster = false">取消</view>
						<view class="distinguish" @click="toSave">保存/分享</view>
					</view>
				</view>
			</scroll-view>
		</u-popup>
		<wike-painter :board="posterObj" style="height: 1px;margin-top: -99999999999999999999999px;"
			@done="posterSuccess" ref="painter"></wike-painter>
		<wike-loading-page :isLoading="isLoading"></wike-loading-page>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapActions,
		mapState,
		mapGetters
	} from 'vuex';
	export default {
		data() {
			return {
				currBgIndex: 0,

				isLoading: true,
				tobheight: 45,
				platform: this.$platform.get(),
				showAuthModal: true,
				empty: false,
				team: [{
					headimg: 'https://dev.iduomi.cc/attachment/headimg_2.jpg?time=1673514485',
					nickname: '多级火箭好',
					times: '2020/12/24'
				}, {
					headimg: 'https://dev.iduomi.cc/attachment/headimg_2.jpg?time=1673514485',
					nickname: '多级火箭好',
					times: '2020/12/24'
				}, {
					headimg: 'https://dev.iduomi.cc/attachment/headimg_2.jpg?time=1673514485',
					nickname: '多级火箭好',
					times: '2020/12/24'
				}],
				pages: 1,
				currentTab: 0,
				navbar: [{
						name: "下一级",
						type: 'shareuid'
					}, {
						name: "下下级",
						type: 'shareuid_grandpa'
					},
					// {
					// 	name: "下三级",
					// 	type:'shareuid_great_grandpa'
					// },
				],
				showShare: false, //是否显示分享海报
				showMoney: true, //是否显示金额
				hasAuth: true, //是否有权限
				commissionLv: {
					name: '合伙人'
				},
				//合伙人等级
				commissionWallet: null, //合伙人钱包
				agentFrom: null, //是否显示我的资料
				showLv: true,
				commissionLog: [{
					id: 1,
					oper_type: 'gf',
					// oper: 'https://file.shopro.top/imgs/commission/commission_icon1.png',
					oper: require('@/static/images/fanyunLogo.png'),
					remark: '恭喜您成为了合伙人',
					createtime: 1676428876
				}], //动态
				loadStatus: 'loadmore', //loadmore-加载前的状态，loading-加载中的状态，nomore-没有更多的状态
				currentPage: 1,
				lastPage: 1,
				logMap: {
					system: this.$IMG_URL + '/imgs/commission/commission_base_notice.png',
					admin: this.$IMG_URL + '/imgs/commission/commission_base_avatar.png'
				},
				showTerm: true, //条件弹窗
				showGoodsTerm: false, //商品条件
				showMoneyTerm: false, //金额条件
				goodsTermList: [],
				moneyTermNum: 0,
				authNotice: {},
				menuList: [
					//menu
					{
						img: 'https://file.shopro.top/imgs/commission/commission_icon1.png',
						title: '我的团队',
						path: '/pages/user/commission/team'
					},
					{
						img: 'https://file.shopro.top/imgs/commission/commission_icon2.png',
						title: '佣金明细',
						path: '/pages/user/commission/commission-log'
					},
					{
						img: 'https://file.shopro.top/imgs/commission/commission_icon4.png',
						title: '推广套餐',
						path: '/pages/user/commission/goods',

					},
					{
						img: 'https://file.shopro.top/imgs/commission/commission_icon3.png',
						title: '提现佣金',
						path: '/pages/user/commission/withdraw',

					},


					// {
					// 	img: 'https://file.shopro.top/imgs/commission/commission_icon6.png',
					// 	title: '排行榜',
					// 	path: '/pages/user/commission/rankings'
					// },
					{
						img: 'https://file.shopro.top/imgs/commission/commission_icon8.png',
						title: '提现记录',
						path: '/pages/user/commission/withdraw-log',

					},
					// {
					// 	img: 'https://file.shopro.top/imgs/commission/commission_icon5.png',
					// 	title: '分享海报',
					// 	path: '/pages/user/commission/withdraw',
					// },
					// {
					// 	img: 'https://file.shopro.top/imgs/commission/commission_icon7.png',
					// 	title: '分享记录',
					// 	path: '/pages/app/commission/share-log',

					// }
				],
				money_total: '0.00',
				on_cashout_money: '0.00',
				showPoster: false,
				posterObj: {},
				posterfff: '您好，我是AI语言模型，可以帮助你做很多事情。例如:\n- 回答你的问题\n- 给你提供某些信息\n- 帮你搜索网页\n- 聊天和闲聊\n- 玩一些小游戏\n- 计算数学题\n- 翻译语言\n- 生成文本\n等等.....\n如果你有任何问题或需要帮助，请随时告诉我。',
				spmplatform: 0,
				is_examine: 1,
				commission_price: 0,
				info: {},
				posterheight: 0,
				poster_bg_img_path: '',
				commission_alias: '',



				genBgHaibaoUrl: ''
			}
		},
		computed: {
			...mapGetters(['appInfo', 'isLogin', 'userInfo'])
		},
		onLoad() {
			// this.getInviteList()

			const that = this;

			if (this.platform == 'wxMiniProgram') {
				var menumtop = uni.getMenuButtonBoundingClientRect().top - uni.getSystemInfoSync().statusBarHeight
				var paddingtop = uni.getSystemInfoSync().statusBarHeight + menumtop
				this.tobheight = (menumtop + paddingtop + uni.getMenuButtonBoundingClientRect().height)
			}
			this.posterheight = uni.$u.sys().windowHeight - this.tobheight
			this.spmplatform = ['H5', 'wxOfficialAccount', 'wxMiniProgram', 'App'].indexOf(this.platform) + 1;

			this.commonqrcodePath()
			// console.log('http://vmoushivideomerge.oss-cn-shanghai.aliyuncs.com/20230422/96f1f662dcfc68cb3eff1dcbf660ed92.jpg');
			// that.$base64.imageUrlToBase64('http://vmoushivideomerge.oss-cn-shanghai.aliyuncs.com/20230422/96f1f662dcfc68cb3eff1dcbf660ed92.jpg')

		},
		onShow() {

			this.islogin();


		},
		methods: {
			islogin() {
				var that = this;
				if (!this.isLogin) {
					uni.navigateTo({
						url: '../user/signin'
					});
				} else {
					this.commission()
					// this.getCheck()
				}

			},
			commission() {
				let that = this;
				that.$http('conf.getGroupConf', {
					group: 'system.commission'
				}).then(res => {
					if (res.code === 0) {
						// res.data.poster_bg_img_path = [
						// 	"https://face.cdn.zhishuyun.com/attachments/1133012400174534792/1204009950465101866/0d47db66-1faf-42df-a732-22cf18697a65_ins.png?ex=65d32ca5&is=65c0b7a5&hm=7219a0f250453314cfbf9eefaf2e927ba8d6adea944774b3fe32e67c0787a877&",
						// 	"https://face.cdn.zhishuyun.com/attachments/1133012400174534792/1204010768786526248/a38d536d-7950-400c-bbc7-b37cd86c8de1_ins.png?ex=65d32d68&is=65c0b868&hm=fd5db147a0eb2e6b13719e1acc3f240a3a5ab8e81358df06c86808b68d0b0923"
						// ]
						that.info = res.data
						that.poster_bg_img_path = res.data.poster_bg_img_path[0]
						// uni.showToast({
						// 	title: that.poster_bg_img_path
						// })
						console.log('生成海报需要的info信息=============', that.info);
						that.commission_alias = res.data.commission_alias ? res.data.commission_alias : '分销中心'
						if (res.data.is_examine) {
							that.is_examine = res.data.is_examine
							// console.log(that.is_examine);
						}
						if (res.data.commission_price) {
							that.commission_price = res.data.commission_price
						}
						if (res.data.is_ranking == 1) {
							if (that.menuList.length == 5) {
								let obj = {
									img: 'https://file.shopro.top/imgs/commission/commission_icon6.png',
									title: '排行榜',
									path: '/pages/user/commission/rankings'
								};
								that.menuList.splice(2, 0, obj);
							}
						}
						that.getCheck()
					}
				});
			},
			commonqrcodePath() {
				let spm = this.userInfo.id + '.1.0.' + this.spmplatform + '.1';
				// console.log(spm);
				this.$http('common.qrcodePath', {
					spm: spm
				}).then(res => {
					if (res.code == 0) {
						this.qrcode = res.data;
						console.log('二维码需要包含的信息======', this.qrcode);

						// setTimeout(() => {
						// 	this.createPoster()
						// }, 2000)
					}
				});
			},
			sharelink() {
				let spm = this.userInfo.id + '.1.0.' + this.spmplatform + '.1';
				// #ifdef MP-WEIXIN
				let url = '/pages/index/index?' + 'spm=' + spm
				uni.setClipboardData({
					data: url,
					success: function() {
						uni.showToast({
							title: '复制链接成功'
						});
					}
				});
				// #endif
				// #ifdef H5
				let uniacid = uni.getStorageSync('uniacid');
				if (uniacid) {
					let url = window.location.href.split('/h5')[0] + '/h5/?uniacid=' + uniacid + '&spm=' + spm;
					uni.setClipboardData({
						data: url,
						success: function() {
							uni.showToast({
								title: '复制链接成功'
							});
						}
					});
				} else {
					uni.showToast({
						title: '复制链接失败',
						icon: 'none'
					})
				}
				// #endif

			},
			getdownload(e) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: e,
						method: 'GET',
						responseType: 'arraybuffer',
						success: ress => {
							let base64 = wx.arrayBufferToBase64(ress.data);
							base64 = 'data:image/jpeg;base64,' + base64
							resolve(base64);
						},
						fail: (e) => {
							resolve('fail');
						}
					})
				});
			},
			posterSuccess() {
				uni.hideLoading();
			},
			async createPoster(e) {
				let that = this;
				let httpsurl = '';
				uni.showLoading({
					title: '海报渲染中'
				});

				// that.poster_bg_img_path =
				// 	"https://mjcdn.iduomi.cc/attachments/1124768570157564029/1132713072260292789/oreynolds_Portrait_retouching_DSLR_effect_green_small_and_fresh_98e8b936-ca9b-45e4-89cd-3d3cd7fd8a60.png"
				console.log('that.poster_bg_img_path', that.poster_bg_img_path);
				// if (that.poster_bg_img_path.indexOf("https") < 0) {
				// 	httpsurl = await that.getdownload(that.poster_bg_img_path.replace("http:", "https:"));
				// } else {
				httpsurl = await that.getdownload(that.poster_bg_img_path);
				// }


				if (httpsurl == 'fail') {
					uni.hideLoading();
					uni.showToast({
						title: '生成失败',
						icon: 'none'
					})
					return;
				}
				let proportionally = this.info.poster_bg_width / uni.$u.sys().windowWidth;
				(this.posterObj = {
					width: (this.info.poster_bg_width / proportionally) + 'px',
					height: (this.info.poster_bg_height / proportionally) + 'px',
					background: '#fff',
					borderRadius: '16rpx',

					views: [{
							src: httpsurl,
							type: "image",
							css: {
								width: (this.info.poster_bg_width / proportionally) + 'px',
								height: (this.info.poster_bg_height / proportionally) + 'px',
							}
						},
						{
							type: 'view',
							css: {
								left: ((this.info.poster_qrcode_x / proportionally) + 40) + 'px',
								top: ((this.info.poster_qrcode_y / proportionally)) + 'px',
								position: 'fixed',

							},
							views: [{
									type: 'qrcode',
									text: this.qrcode,
									css: {
										width: (this.info.poster_qrcode_width / proportionally) + 'px',
										height: (this.info.poster_qrcode_width / proportionally) + 'px',
										background: '#fff'
									}
								},
								// {
								// 	src: '/static/images/fanyunLogo.png',
								// 	type: "image",
								// 	css: {
								// 		position: 'absolute',
								// 		width: 30 + 'rpx',
								// 		height: 30 + 'rpx',

								// 		left: '60rpx',
								// 		top: '50rpx',

								// 	}
								// }
							],
						},
					]
				}),
				(
					setTimeout(() => {
						that.$refs.painter.canvasToTempFilePathSync({
							// 在nvue里是jpeg
							fileType: 'jpg',
							quality: 1,
							success: res => {
								console.log('res.tempFilePath', res.tempFilePath);
								this.genBgHaibaoUrl = res.tempFilePath
								uni.hideLoading();
							}
						})
						that.showPoster = true
					}, 1000)
				);
			},

			is_weixin() {
				var ua = window.navigator.userAgent.toLowerCase();
				if (ua.match(/MicroMessenger/i) == 'micromessenger') {
					console.log('微信浏览器');
					return true;
				} else {
					console.log("不是微信浏览器");
					return false;
				}
			},

			toSave() {
				let _this = this
				if (!this.is_weixin()) {
					return uni.showModal({
						showCancel: false,
						title: '提示',
						content: '请在微信内置浏览器打开，长按图片下载/分享',
						confirmColor: '#207CF7'
					})
				}
				uni.showModal({
					confirmColor: '#207CF5',
					confirmText: '查看图片',
					title: '提示',
					content: '查看图片后长按图片即可保存或分享',
					success(src) {
						if (src.confirm) {
							_this.showPoster = false
							uni.previewImage({
								urls: [_this.genBgHaibaoUrl]
							});
						} else if (src.cancel) {
							// this.showPoster = true;
						}
					}
				});
				return

				uni.showLoading({
					title: '海报生成中'
				});
				this.$refs.painter.canvasToTempFilePathSync({
					// 在nvue里是jpeg
					fileType: 'jpg',
					quality: 1,
					success: res => {
						wx.showShareImageMenu({
							path: res.tempFilePath
						})
						this.showPoster = false;
						uni.hideLoading();
						// #ifdef H5
						this.showPoster = false;
						uni.hideLoading();
						uni.showModal({
							confirmColor: '#26B3A0',
							confirmText: '查看图片',
							title: '提示',
							content: '查看图片后长按图片即可保存或分享',
							success(src) {
								if (src.confirm) {
									uni.previewImage({
										urls: [res.tempFilePath]
									});
								} else if (src.cancel) {
									this.showPoster = true;
								}
							}
						});
						// #endif
					}
				});
			},
			getCheck() {
				var that = this;
				that.$http('commission.auth').then(res => {
					if (res.code == 0) {
						this.isLoading = false
						uni.setNavigationBarTitle({
							title: this.appInfo.site_name
						});

						that.money_total = res.data.money_total > 0 ? res.data.money_total : '0.00'
						that.on_cashout_money = res.data.on_cashout_money > 0 ? res.data.on_cashout_money : '0.00'
						that.commissionLog[0].createtime = res.data.create_time
						if (res.data.status == 0 && that.is_examine == 1) {
							uni.showModal({
								confirmText: '确定',
								showCancel: false,
								confirmColor: '#5e49c3',
								content: '分销商申请已提交，等待后台审核通过',
								title: '提示',
								success(res) {
									if (res.confirm) {
										uni.navigateBack()
									}
								}
							})
						}
						if (res.data.status == 2) {
							uni.showModal({
								confirmText: '联系客服',
								confirmColor: '#5e49c3',
								content: '已被禁用，有疑问请咨询客服',
								title: '提示',
								success(res) {
									if (res.confirm) {
										uni.navigateTo({
											url: '/pages/user/public/kefu'
										})
									} else if (res.cancel) {
										uni.navigateBack()
									}
								}
							})
						}
					} else {
						// uni.showModal({
						// 	confirmText:'申请',
						// 	confirmColor:'#5e49c3',
						// 	content:'立即申请成为合伙人',
						// 	title:'提示',
						// 	success(res) {
						// 		if(res.confirm){
						// 			that.commissionapply()
						// 		}else if(res.cancel){
						// 			uni.navigateBack()
						// 		}
						// 	}
						// })
						uni.redirectTo({
							url: '/pages/user/commission/apply'
						})
					}
				});
			},
			commissionapply() {
				var that = this;
				that.$http('commission.apply').then(res => {
					if (res.code == 0) {
						uni.showToast({
							title: '申请成功'
						})
						that.getCheck()
					} else {
						uni.showModal({
							confirmText: '重新申请',
							confirmColor: '#5e49c3',
							content: '合伙人申请失败',
							title: '提示',
							success(res) {
								if (res.confirm) {
									that.commissionapply()
								} else if (res.cancel) {
									uni.navigateBack()
								}
							}
						})
					}
				});
			},
			// 我的团队
			getInviteList() {
				var that = this;
				that.$api('distribution.ulist', {
					uid: this.userInfo.id,
					type: this.navbar[this.currentTab].type
				}).then(res => {
					// console.log(res)
					if (res.data.length > 0) {
						if (that.team.length > 0) {
							var dd = this.team;
							this.team = dd.concat(res.data);
							this.pages++;
						} else {
							this.team = res.data;
							this.pages++;
						}
					} else {
						// this.empty = true
					}
				});
			},
			jump(e) {
				uni.navigateTo({
					url: e
				})
			},
			change(index) {
				this.currentTab = index;
				this.team = [];
				this.pages = 1;
				this.getInviteList()
			},
			toTeam() {
				// uni.navigateTo({
				// 	url:'/pages/user/commission/team'
				// })
				uni.navigateTo({
					url: '/pages/user/commission/commission-log'
				})
			}
		},
		onPullDownRefresh() {
			var that = this;
			// setTimeout(function() {
			// 	this.pages = 1;
			// 	this.team = [];
			// 	that.getInviteList();
			// 	uni.stopPullDownRefresh();
			// }, 1000);
		},
		onReachBottom() {
			// this.getInviteList();
		},
	}
</script>

<style lang="scss" scoped>
	@import './index.scss';
</style>