<template>
	<!-- :style="{paddingTop: showFlag ? '0' : '60rpx'}" -->
	<view class="container" :style="{paddingTop: showFlag ? '0' : '60rpx'}">
		<view class="homeHeader" v-if="showFlag">
			<view class="one">
				<text style="font-size: 80rpx;">01</text>
				<view class="titleTxt">
					<text >分享商品</text>
					<text class="iconfont icon-shuangyoujiantou iconOne" ></text>
				</view>
			</view>
			<view class="two">
				<text>02</text>
				<view class="titleTxt">
					<text >好友购买</text>
					<text class="iconfont icon-shuangyoujiantou iconOne" ></text>
				</view>
			</view>
			<view class="three">
				<text>03</text>
				<view class="titleTxt lastTxt">
					<text>首页佣金</text>
					<text>查看收益</text>
				</view>
			</view>
		</view>
		<view class="productBox">
			<view class="productList" :style="{marginTop}">
				<view class="tabBox">
					<!-- @click="courseClassify=4;courseList()" -->
					<view :class="{'actived': courseClassify==4}" @click="transform('consult')"><text>咨询产品</text></view>
					<!-- @click="courseClassify=3;courseList()" -->
					<view :class="{'actived': courseClassify==3}" @click="transform('plan')"><text>规划产品</text></view>
				</view>
				<view class="productItem" v-for="item in localCourseInfos" :key="item.fileId" >
					<view class="top" @click="goDetail(item)">
						<view class="left">
							<image class="productImg" :src="item.displayImage" alt="" mode="widthFix"></image>
						</view>
						<view class="right">
							<view class="one">
								{{item.fileSynopsis}}
							</view>
							<view class="two">
								{{item.fileTitle}}
							</view>
							<view class="three">
								<text style="font-size: 28rpx;color: rgba(32, 39, 155, 1);">￥{{Number(item.coursePrice).toFixed(2)}}</text>
							</view>
						</view>
					</view>
					<view class="bottom">
						<view class="bottomCon">
							<view class="left" >
								最高可赚￥{{item.income || '0.00'}}
							</view>
							<view class="right" @click="gotoShare(item)">
								去分享
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<BootPage 
		    loginSource="产品中心"
			ref="sharelogin" 
			v-if="sharelogin" 
			@close="closeLogin"
		>
		</BootPage>
		<uni-popup ref="popup" type="center" background-color="#fff">
			<view class="descriptionBox">
				<view class="imageBox">
					<text>关注公众号</text>
					<text class="subTit">通知实时提醒，及时接收下单和提现通知</text>
				</view>
				<view class="codeBox">
					<image v-if="sourceType == '1'" src="@/static/cffpCode.jpg" mode="widthFix" style="width:250rpx !important;"></image>
					<image v-if="sourceType == '4'" src="@/static/ydCode.jpg" mode="widthFix" style="width:250rpx !important;"></image>
					<image v-if="sourceType == '3'" src="@/static/ydHomeOfficeCode.jpg" mode="widthFix" style="width:250rpx !important;"></image>
				</view>
				<view class="description">
					扫一扫，关注公众号
				</view>
			</view>
			
		</uni-popup>
		<!-- 添加合伙人提示弹窗组件 -->
		  <partner-tip-popup 
		    ref="partnerTipPopup"
		    @join="gotoJoinPartner"
		    @continue="continueShare"
		  />
		<uni-share-wx ref="sharewx"></uni-share-wx>
		<view class="markBox" @click="shareTipsFlag=false" v-if="shareTipsFlag">
			<view class="guideImgBox">
				<image src="../../static/Group132.png" mode="widthFix"></image>
				<view class="tips">
					<view style="margin-bottom:30rpx">请点击右上角菜单</view>
					<view>分享给朋友</view>
				</view>
			</view>
		</view>
		
	</view>
	<!-- <tabBar :currentPage="currentPage" v-if="onlyShowList!=0"></tabBar> -->
</template>

<script>
	
	import BootPage from "@/components/bootpage/bootpage.vue";
	import PartnerTipPopup from "@/components/commonPopup/PartnerTipPopup.vue";
	import api from "../../api/api";
	import courseItem from "@/components/courseItem/courseItem.vue";
	import tabBar from '../../components/tabBar/tabBar.vue';
	import carousel from '@/components/carousel/carousel.vue';
	import search from '@/components/search/search.vue';
	import {baseURL,apiURL,cffpURL,companyInfo,shareURL} from "@/environments/environment";
	import dataHandling from "@/util/dataHandling";
	import {hshare,setWechatShare,initJssdkShare} from '@/util/fiveshare';
	import UniShareWx from "@/uni_modules/uni-share-wx/index.vue";
	import {nanoid} from 'nanoid';
	export default{
		name:'courselist',
		props:{
			showFlag:{
				type:Boolean,
				default:true
			},
			 cffpCourseInfos: {
			    type: Array,
			    default: () => []
			  }
		},
		components:{
			courseItem,
			tabBar,
			carousel,
			search,
			UniShareWx,
			BootPage,
			PartnerTipPopup
		},
		watch: {
		  // 监听 prop 变化，更新本地副本
		  cffpCourseInfos: {
		    immediate: true, // 立即执行一次
		    handler(newVal) {
		      this.localCourseInfos = [...newVal]; // 深拷贝（如果是简单数组，浅拷贝也行）
		    },
		  },
		},
		data(){
			return{
				 localCourseInfos: [], // 本地副本
				currentPage:'courselist',
				fileUploadItemCFFPList:[],
				queryName:null,
				userId: uni.getStorageSync('cffp_userId'),
				userInfo:{},
				runEnv:dataHandling.getRuntimeEnv(), //运行的环境  browser、app、h5
				shareTipsFlag:false,
				sourceType:'1',//根据来源展示二维码 默认是cffp,
				env:dataHandling.getRuntimeEnv2(),
				shareItem:{},//分享的产品
				sharelogin: false,
				courseClassify:4,
			}
		},
		
		
		onLoad() {
		    this.queryName = uni.getStorageSync('queryName') || '';
			 this.sourceType = uni.getStorageSync('addSystemType') || '1';
		  },
		  onShow() {
		    this.queryName = uni.getStorageSync('queryName') || '';
		    this.courseList();
			this.sourceType = uni.getStorageSync('addSystemType') || '1';
			if(uni.getStorageSync('cffp_userInfo')){
				this.userInfo = JSON.parse(uni.getStorageSync('cffp_userInfo'))
			}
			this.userId = uni.getStorageSync('cffp_userId')
			// #ifdef H5
			initJssdkShare(() => {
			  setWechatShare();
			}, window.location.href);
			// #endif
		  },
		  created(){
			this.queryName = uni.getStorageSync('queryName') || '';
			this.courseList();
			 // 初始化本地副本
			  this.localCourseInfos = [...this.cffpCourseInfos];
			this.sourceType = uni.getStorageSync('addSystemType') || '1';
			if(uni.getStorageSync('cffp_userInfo')){
				this.userInfo = JSON.parse(uni.getStorageSync('cffp_userInfo'))
			}  
		  },
		  computed:{
			  marginTop(){
				  if(this.env.device.isMobile){
					  return '-5%'
				  }else {
					  return '-1.5%'
				  }
			  }
		  },
		methods:{
			transform(value){
				if(value == 'consult'){
					this.courseClassify = 4
				}else if(value == 'plan'){
					this.courseClassify = 3
				}
				this.$emit('changeCourseClassify',this.courseClassify)
				this.courseList()
			},
			gotoJoinPartner(){
				dataHandling.pocessTracking(
				  '点击',
				  `用户在产品中心未加盟时点击了加盟按钮`,
				  '点击',
				  2,
				  '产品中心',
				  'pages/courselist/courselist'
				)
				uni.navigateTo({
					url: '/myPackageA/applyFranchise/applyFranchise'
				})
				this.$refs.partnerTipPopup.close()
			},
			gotoShare(item){
				if(uni.getStorageSync('cffp_userInfo')){
					this.userInfo = JSON.parse(uni.getStorageSync('cffp_userInfo'))
				}
				this.shareItem = JSON.parse(JSON.stringify(item))
				// 未登录去登录
				if(uni.getStorageSync('loginType')!=='codelogin'){
					dataHandling.pocessTracking(
					  '点击',
					  `用户在产品中心未登录时点击产品分享按钮`,
					  '点击',
					  2,
					  '产品中心',
					  'pages/courselist/courselist'
					)
					this.sharelogin = true
					return
				}
				if(this.runEnv == 'browser'){
					dataHandling.pocessTracking(
					  '点击',
					  `用户在产品中心浏览器端点击产品分享按钮`,
					  '点击',
					  2,
					  '产品中心',
					  'pages/courselist/courselist'
					)
					this.$refs.popup.open()
					return
				}
				// 已登录，未成为合伙人
				if(this.userInfo&&!this.userInfo['partnerType']) {
					dataHandling.pocessTracking(
					  '点击',
					  `用户在产品中心未加盟时点击产品分享按钮`,
					  '点击',
					  2,
					  '产品中心',
					  'pages/courselist/courselist'
					)
					 this.$refs.partnerTipPopup.open()
					return
				}
				this.continueShare()
			},
			continueShare(){
				this.userId = uni.getStorageSync('cffp_userId')
				const shareCode = nanoid() + this.userId
				const jumptime = Date.parse(new Date()) / 1000
				//app分享 
				// #ifdef APP-PLUS
				let dataWXform = {
					href: shareURL + "/pages/courseDetail/courseDetail?fileId=" + this.shareItem.fileId +
						'&coursesharing=1' + '&serialsNo=' + nanoid() + '&shareCode=' + shareCode + '&shareUserId=' +
						this.userId + '&jumpUrl=' + jumptime + "&",
					title:  this.shareItem.fileTitle,
					summary:  this.shareItem.fileSynopsis,
					imageUrl:  this.shareItem.displayImage,
					fileId:  this.shareItem.fileId,
					shareCode: shareCode
				}
				this.$refs.sharewx.open(dataWXform)
				dataHandling.pocessTracking(
				  '点击',
				  `用户在产品中心点击分享按钮，分享${this.shareItem.fileTitle}`,
				  '点击',
				  2,
				  '产品中心',
				  'pages/courselist/courselist'
				)
				// #endif
				
				//#ifdef H5
				this.shareTipsFlag = true;
				this.getshareData2(shareCode,jumptime, this.shareItem)
				// #endif
				this.$refs.partnerTipPopup.close()
			},
			
			getshareData2(shareCode,jumptime,item) {
				let data = {
					title: item.fileTitle,
					// desc: '加入我们开启学习之旅',
					desc:item.fileSynopsis,
					link: shareURL + "/pages/courseDetail/courseDetail?fileId=" + item.fileId +
						'&coursesharing=1' + '&serialsNo=' + nanoid() + '&shareCode=' + shareCode + '&shareUserId=' +
						this.userId + '&jumpUrl=' + jumptime+ "&", //分享链接
					imgUrl: item.displayImage, //图片
				}
				//安卓机型获取当前页面路径
				let url = window.location.href.split('#')[0];
				
				//ios机型获取当前页面路径
				let ua = navigator.userAgent.toLowerCase();
				let isWeixin = ua.indexOf('micromessenger') !== -1;
				if (isWeixin) {
					let isiOS = /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent); //ios终端
				    if (isiOS && window.sessionStorage.getItem('firstEntryUrl')) {
				        url = window.sessionStorage.getItem('firstEntryUrl').split('#')[0];
				    }
				}
				setTimeout(()=>{
					initJssdkShare(() => {
					  setWechatShare(data);
					}, url);
				},500)
				
				// hshare(data, url)
				
				this.submitsuessc(shareCode,jumptime,item)
				dataHandling.pocessTracking(
				  '点击',
				  `用户在产品中心点击分享按钮，分享${item.fileTitle}`,
				  '点击',
				  2,
				  '产品中心',
				  'pages/courselist/courselist'
				)
				
			},
			submitsuessc(shareCode,jumptime,item){
				let platform = uni.getSystemInfoSync().platform
				let UserShareRequestVO = {
					systemType: platform == 'ios'? '1': '0',
					userId: uni.getStorageSync('cffp_userId'),
					businessType: '1', // 分享类型
					businessId:item.fileId, // 课程Id
					shareUrl: shareURL + "/pages/courseDetail/courseDetail?fileId=" + item.fileId +
						'&coursesharing=1' + '&serialsNo=' + nanoid() + '&shareCode=' + shareCode + '&shareUserId=' +
						this.userId + '&jumpUrl=' + jumptime + "&", // 分享链接
					shareType: '2', // 分享类型(1:图片分享; 2:链接分享)
					shareToWhere: 3, //分享到哪儿（1好友 2朋友圈）
					shareCode: shareCode
				}
				api.userShare(UserShareRequestVO).then(res => {
					if (res['success']) {
						// #ifdef H5
							initJssdkShare(() => {
							  setWechatShare();
							}, window.location.href);
						// #endif
						// uni.showToast({
						// 	title: '分享成功',
						// 	duration: 2000
						// });
					}
				})
			},
			closeLogin(val1,val2,val3){
				if(val3){
					this.sharelogin=false
					return
				}
				if(uni.getStorageSync('cffp_userInfo')){
					this.userInfo = JSON.parse(uni.getStorageSync('cffp_userInfo'))
				}
				this.sharelogin=false
				if(this.runEnv == 'browser'){
					dataHandling.pocessTracking(
					  '点击',
					  `用户在产品中心浏览器端点击产品分享按钮`,
					  '点击',
					  2,
					  '产品中心',
					  'pages/courselist/courselist'
					)
					this.$refs.popup.open()
					return
				}else{
					// 已登录，未成为合伙人
					if(!this.userInfo['partnerType']) {
						dataHandling.pocessTracking(
						  '点击',
						  `用户在产品中心未加盟时点击产品分享按钮`,
						  '点击',
						  2,
						  '产品中心',
						  'pages/courselist/courselist')
						 this.$refs.partnerTipPopup.open()
						return
					}
					this.continueShare()
				}
			},
			goDetail(item){
				dataHandling.pocessTracking(
				  '点击',
				  `用户在产品中心点击${item.fileTitle},查看产品详情`,
				  '点击',
				  2,
				  '产品中心',
				  'pages/courselist/courselist'
				)
				uni.navigateTo({
					url: `/pages/courseDetail/courseDetail?fileId=${item.fileId}`
				});
			},
			courseList(){
				const param = {
					queryName:this.queryName,
					courseClassify:this.courseClassify
				}
				api.courseList(param).then(res=>{
					if(res['success']){
						 this.localCourseInfos = res['data']['data']; // 修改本地副本
					}
				})
			},
			
			queryAreaCenterInfo() {
				api.queryAreaCenterInfo({
					userId: uni.getStorageSync('cffp_userId'),
					companyType: `${companyInfo.companyType}`
				}).then((res) => {
					if (res['success']) {
						uni.setStorageSync('fileUploadItemCFFPList', res['data']['fileUploadItemCFFPList'])
						const cffp_userInfo = {
							name: res['data']['userReName'],
							mobile: res['data']['mobile'],
							partnerType:res['data']['partnerType'],
							levelCode:res['data']['levelCode'],
						}
						uni.setStorageSync('cffp_userInfo', JSON.stringify(cffp_userInfo));
						this.fileUploadItemCFFPList = uni.getStorageSync('fileUploadItemCFFPList');
					}
				})
			},
		},
		mounted() {
			this.fileUploadItemCFFPList = uni.getStorageSync('fileUploadItemCFFPList');
			if(!this.fileUploadItemCFFPList){
				this.queryAreaCenterInfo();
			}
			// this.courseList();
		},
		onTabItemTap() {
		    // 通过tabbar切换时清空storage
		    uni.removeStorageSync('queryName');
		  },
		onHide() {
			this.queryName = ''
			uni.removeStorageSync('queryName')
		}
	}
</script>

<style lang="scss" scoped>
	.container{
		background-color: rgba(235, 239, 247, 1);
		display: flex;
		flex-direction: column;
		width: 100%;
		height: auto;
		box-sizing: border-box;
		.tabBox{
			    display: flex;
			    align-items: center;
			    height: 88rpx;
			    margin-bottom: 20rpx;
				background: #fafafa;
				border-bottom: 1px solid #262088;
				view{
					color: #000;
					width: 160rpx;
					height: 100%;
					text-align: center;
					margin-right:30rpx ;
					line-height: 88rpx;
					&.actived{
						background-color: #262088;
						color: #fff;
					}
				}
		}
		.homeHeader{
			box-sizing: border-box;
			width: 100%;
			background: linear-gradient(225deg, rgba(65, 69, 188, 1) 0%, rgba(29, 30, 125, 1) 100%);
			padding: 30rpx 0 100rpx 0;
			color: rgba(255,255,255,.3);
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 80rpx;
			height: 300rpx;
			view{
				width: 33%;
				display: flex;
				align-items: center;
				justify-content: center;
				position: relative;
				.titleTxt{
					box-sizing: border-box;
					position: absolute;
					width: 100%;
					left: 50%;
					transform: translate(-50%);
					bottom: -20%;
					font-size: 28rpx;
					color: #fff;
					.icon-shuangyoujiantou{
						font-size: 26rpx;
						position: absolute;
						right:0;
						
					}
				}
				.lastTxt{
					display: flex;
					align-items: center;
					flex-direction: column;
					bottom: -40%;
					line-height: 1.3;
				}
			}
			
		}
		.productBox{
			flex: 1;
			width: 100%;
			padding: 0rpx 15rpx;
			box-sizing: border-box;
			.productList{
				width: 100%;
				box-sizing: border-box;
				background-color: #fff;
				padding: 20rpx;
				border-radius: 10rpx;
				margin-bottom: 150rpx;
				.productItem{
					padding-bottom: 15rpx;
					border-bottom: 1rpx solid rgba(238, 238, 240, 1);
					margin-bottom: 20rpx;
					.top{
						display: flex;
						justify-content: flex-start;
						.left {
						    width: 220rpx;
						    flex-shrink: 0; /* 防止左侧被压缩 */
						    margin-right: 20rpx;
						    .productImg {
						      border-radius: 20rpx;
						      width: 100%;
						      height: 180rpx; /* 固定图片高度 */
							  display: block;
						    }
						  }
						.right{
							flex: 1; /* 右侧占据剩余空间 */
							min-width: 0; /* 允许文本截断 */
							display: flex;
							flex-direction: column;
							.one{
								font-size: 30rpx;
								font-weight: 500;
								display: -webkit-box;
								 -webkit-line-clamp: 1;
								 -webkit-box-orient: vertical;
								 overflow: hidden;
								 text-overflow: ellipsis;
								 white-space: nowrap; /* 确保不会换行 */
							}
							.two{
								font-size: 24rpx;
								margin: 10rpx 0;
							}
							.three{
								font-size: 28rpx;
								color: rgba(32, 39, 155, 1);
								margin-top: auto; /* 关键代码：自动顶部边距，推到底部 */
							}
						}
					}
					.bottom{
						box-sizing: border-box;
						margin: 10rpx 0;
						width: 100%;
						padding-left: 240rpx;
						.bottomCon{
							box-sizing: border-box;
							width: 100%;
							background: rgba(54, 57, 169, 0.05);
							border-radius: 10rpx;
							display: flex;
							align-items: center;
							justify-content: space-between;
							.left{
								padding: 15rpx  0rpx 15rpx 20rpx;
								font-size: 26rpx;
								color: rgba(34, 35, 133, 1);
							}
							.right{
								
								display: flex;
								align-items: center;
								justify-content: center;
								padding: 15rpx  10rpx 15rpx 15rpx;
								background: rgba(36, 37, 137, 1);
								width: 20%;
								font-size: 27rpx;
								color: #fff;
								border-radius: 0 10rpx 10rpx 0rpx; /* 左上 右上 右下 左下 */
							}
						}
					}
				}
				.productItem:last-child{
					border: none;
				}
			}
			/* 电脑端 */
			 @media (min-width: 768px) {
				.productList{
					// padding-top: 60rpx;
				}
			 }
		}
		.descriptionBox {
			width: 510rpx;
			padding: 40rpx;
			.popupClose{
				display: flex;
				align-items: center;
				justify-content: flex-end;
				.icon-guanbi{
					font-size: 28rpx;
					
				}
			}
			.imageBox{
				display: flex;
				align-items: center;
				justify-content: center;
				flex-direction: column;
				font-size: 32rpx;
				font-weight: 600;
				.subTit{
					font-size: 28rpx;
					color: #919094;
					margin: 15rpx 0;
					font-weight: 400;
				}
			}
			.codeBox{
				display: flex;
				align-items: center;
				justify-content: center;
				height: 250rpx;
			}
			.description{
				color: rgba(56, 56, 56, 1);
				font-size: 28rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
		.markBox {
			position: fixed;
			left: 0;
			top: 0;
			bottom: 0;
			right: 0;
			width: 100%;
			height: 100%;
			color: #fff;
			display: flex;
			justify-content: flex-end;
			z-index: 100000;
			background: rgba(0, 0, 0, 0.8);
			.guideImgBox {
				margin: 20px auto;
				uni-image {
					width: 25% !important;
					position: absolute;
					right: 0;
					top: 0;
				}
			}
			
			.tips {
				margin-top: 30%;
				padding: 0 30px;
			}
		}
		.joinContent{
			width: 600rpx;
			border-radius: 30rpx;
			background-color: #ffff;
			padding: 30rpx;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			flex-direction: column;
			.joinHeader{
				width: 60rpx;
				height: 60rpx;
				border-radius: 50%;
				background: rgba(54, 57, 169, 1);
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 20rpx;
			}
			.joinCon{
				margin-bottom: 20rpx;
				.one{
					font-size: 28rpx;
					color: rgba(38, 41, 44, 1);
					
					text-align: center;
				}
				.two{
					color: rgba(145, 144, 148, 1);
					font-size: 26rpx;
					text-align: center;
					margin-top: 10rpx;
					margin-bottom: 20rpx;
				}
			}
			.joinFotter{
				width: 100%;
				color: #fff;
				display: flex;
				align-items: center;
				justify-content: space-between;
				box-sizing: border-box;
				padding: 10rpx 0;
				font-size: 24rpx;
				view{
					background: rgba(54, 57, 169, 1);
					border-radius: 10rpx;
					padding: 10rpx;
				}
			}
		}
	}
	.container {
	  padding-top: 60rpx;
	  
	  .homeHeader {
	    padding-bottom: 100rpx;
	    position: relative;
	    z-index: 1;
	  }
	  
	  .productBox {
	    position: relative;
	    z-index: 2;
	    
	    .productList {
	      padding-top: 30rpx; // 改用padding-top
	      margin-top: 0;
	      
	      .productItem {
	        &:first-child {
	          margin-top: 0;
	        }
	      }
	    }
	  }
	}
	
	/* iPad横屏特定适配 */
	@media only screen 
	  and (min-device-width: 768px) 
	  and (max-device-width: 1024px) 
	  and (orientation: landscape) {
	  .container {
	    .homeHeader {
	      padding-bottom: 120rpx;
	    }
	    .productBox {
	      .productList {
	        padding-top: 50rpx;
	      }
	    }
	  }
	}
</style>