<template>
	
	<view class="navbox">
       <view class="status_bar"></view>
       <uni-nav-bar
      left-icon="left"
      :title="'我的福利'"
      @clickLeft="goBack"
    
      color="#8B2316"
     
      :border="false"
      backgroundColor="#eeeeee"
    >
      <template v-slot:right>
        <view class="nav-right" @click="goRules" >
            规则
        </view>
      </template>
    </uni-nav-bar>
     </view>
	<view class="benefits-page">
		

		<!-- 头部导航栏 -->
	
		<!-- 分段控制器 -->
		<view class="segmented-control">
			<view 
				class="tab-item" 
				:class="{ active: activeTab == 0 }"
				@click="switchTab(0)"
			>
				<text class="tab-text">领取福利</text>
			</view>
			<view class="divider"></view>
			<view 
				class="tab-item" 
				:class="{ active: activeTab == 1 }"
				@click="switchTab(1)"
			>
				<text class="tab-text">使用福利</text>
			</view>
			<view class="divider"></view>
			<view 
				class="tab-item" 
				:class="{ active: activeTab == 2 }"
				@click="switchTab(2)"
			>
				<text class="tab-text">兑福利卡</text>
			</view>
		</view>
		<!-- v-if="(benefit.name != 'upan') || (getFirstNum(benefit.left_result) > 0 && benefit.name == 'upan')" -->
		<!-- 福利卡片列表 -->
			<scroll-view class="scrollbox" scroll-y="true" :show-scrollbar="false">
				<view 
					class="benefit-card" 
					v-show="(benefit.name != 'upan') || (getFirstNum(benefit.left_result) > 0 && benefit.name == 'upan')"
					v-for="(benefit, index) in benefitsList" 
					:key="index"
					:class="fotmatType(benefit)"
					
					
				>
				   <view class="card-title" :class="fotmatType(benefit)">{{ benefit.title }}</view>
					<!-- <view class="card-bg">
						
					</view> -->
					<view class="card-content" >
						<image :src="jifenBgImg" mode="widthFix" class="card-img" v-if="benefit.name == 'jifen'"></image>
						<image :src="videoImg" mode="widthFix" class="card-img" v-if="benefit.name == 'video'"></image>
						<image :src="kejianImg" mode="widthFix" class="card-img" v-if="benefit.name == 'kejian'"></image>
						<image :src="upanImg" mode="widthFix" class="card-img" v-if="benefit.name == 'upan' && (!(benefit.right_tip =='已领取' || benefit.right_result =='已领取') || activeTab == 1)"></image>
						<image :src="upanNoimg" mode="widthFix" class="card-img" v-if="benefit.name == 'upan' && ((benefit.right_tip =='已领取' || benefit.right_result =='已领取') && activeTab == 0)"></image>
						<image :src="wanfangImg" mode="widthFix" class="card-img" v-if="benefit.name == 'wanfang'"></image>
						<image :src="wenxianImg" mode="widthFix" class="card-img" v-if="benefit.name == 'daicha'"></image>
						<view class="card-details">
							<view class="left-section">
								<text class="condition">{{ benefit.left_tip }}</text>
								<text class="requirement">{{ benefit.left_result }}</text>
							</view>
							<view class="right-section" @click="claimBenefit(benefit)">
								<text class="reward-type">{{ benefit.right_tip }}</text>
								<text class="reward-value" v-if="activeTab == 0 && !benefit.flag && benefit.name != 'upan'">{{ benefit.right_result }}</text>
								<text class="reward-value" v-else-if="activeTab == 0 && benefit.name == 'upan' && !(benefit.right_tip =='已领取' || benefit.right_result =='已领取') &&  benefit.right_result !='立即领取'">{{ benefit.right_result }}</text>
								<!-- <text class="reward-value" v-if="activeTab == 1">{{ benefit.right_result }}个</text> -->
							</view>
						</view>
						<view class="panbox" :class="{'disabled': ((benefit.right_tip =='已领取' || benefit.right_result =='已领取') && activeTab== 0)}" v-if="benefit.name == 'upan'">知识U盘</view>
						
					</view>
				</view>
			</scroll-view>
		
        
		<!-- 底部导航栏 -->
		<view class="bottom-nav">
			<view class="nav-item" @click="goPointsDetail">
				<up-image  :src="jifenImg" width="34rpx" height="34rpx" ></up-image>
				<text class="nav-text">积分详情</text>
			</view>
			<view class="nav-item" @click="gofuliDetail">
				 <up-image  :src="fuliImg" width="34rpx" height="34rpx" ></up-image>
				<text class="nav-text">福利详情</text>
			</view>
			<view class="nav-item" @click="goAddPatient">
				<up-image  :src="addImg" width="34rpx" height="34rpx" ></up-image>
				<text class="nav-text">添加患者</text>
			</view>
			
		</view>
	</view>
	<unidialog :visible="showDialog" :content="content" @close="showDialog=false" :showCancel="false" @confirm="confirmDialog"></unidialog>
</template>

<script setup>
	import { ref, onMounted } from 'vue';
	import {onShow,onBackPress,onLoad,onHide} from '@dcloudio/uni-app';
	import docUrl from '@/utils/docUrl.js';
	const from = ref('');
	onBackPress(() => {
		if(!from.value){
			plus.runtime.quit();
		   return true;
		}
	});
	//import jifenImg from "@/static/duihuan.png"
	import api from '@/api/api';
	import unidialog from '@/components/dialog/dialog.vue'
	import navTo  from "@/utils/navTo.js";
	import navBar from '@/components/navBar/navBar.vue'
	import fuliImg from "@/static/fulidetail.png"
	import jifenImg from "@/static/jifendetail.png"
	import addImg from "@/static/tianjiapatient.png"
	import jifenBgImg from "@/static/fljifen_big.png"
	import videoImg from "@/static/flshipin_big.png"
	import kejianImg from "@/static/flkejian_big.png"
	import upanImg from "@/static/flupan_big2.png"
	import wanfangImg from "@/static/flwanfang_big.png"
	import wenxianImg from "@/static/flwen_big.png"
	import upanNoimg from "@/static/flupannull_big.png"
	const showDialog = ref(false);
	const content = ref('肝胆相照平台协助查找文献次数已经用完，谢谢您的支持！');
	const confirmDialog = () => {
		showDialog.value = false;
	}
	// 当前选中的标签页
	const activeTab = ref(0);

	// 福利列表数据
	const benefitsList = ref([
		{
			type: 'points',
			title: '肝胆积分 (5个新随访)',
			condition: '赠送积分',
			requirement: '200积分',
			rewardType: '立即领取',
			rewardValue: '',
			flag: true, // 表示是否可领取
			num: 0 // 需要的新随访数量
		},
		{
			type: 'video',
			title: '肝胆视频',
			condition: '再新增随访',
			requirement: '1个',
			rewardType: '赠送下载',
			rewardValue: '2集',
			flag: true,
			num: 1
		},
		{
			type: 'courseware',
			title: '肝胆课件',
			condition: '再新增随访',
			requirement: '6个',
			rewardType: '赠送下载',
			rewardValue: '1篇',
			flag: true,
			num: 6
		},
		{
			type: 'usb',
			title: '知识U盘',
			condition: '再新增随访 (年度计算)',
			requirement: '96个',
			rewardType: '赠送U盘',
			rewardValue: '1个',
			flag: true,
			num: 96
		}
	]);

	// 方法
	const goBack = () => {
		if(!from.value){
			plus.runtime.quit();
		}else{
			uni.navigateBack();
		}
	};

	const showRules = () => {
		uni.showToast({
			title: '福利规则',
			icon: 'none'
		});
	};
    const fotmatType = (benefit) => {
		let  name = benefit.name;
		let name1 = benefit.right_tip;
		let name2 = benefit.right_result;
		if(name == 'video'){
			return 'video';
		}else if(name == 'kejian'){
			return 'kejian';
		}else if(name == 'upan'){
			if((name1 == '已领取' &&  name2 == '已领取') && activeTab.value == 0){
				return 'upan_disabled';
			}else{
				return 'upan';
				
			}
		}else if(name == 'wanfang'){
			return 'wanfang';
		}else if(name=='jifen'){
			return 'jifen';
		}else if(name=='daicha'){
			return 'wenxian';
		}
	}
	const switchTab = (index) => {
		

		if (index == 0) {
			activeTab.value = index;
			getWelfarePage();
		} else if (index == 1) {
			activeTab.value = index;
			useWelfarePage();
		} else if (index == 2) {
			uni.setStorageSync('lookWelfare', '');
			navTo({
				url: '/pages_app/myWelfareCard/myWelfareCard?from=myWelfare'
			});
		}
	};
  onLoad((options) => {
	
	if(options.from){
		from.value = options.from;
	}
	uni.sendNativeEvent("portraitReport",{
      msg:{
        event_nickname: "list_page",
        page_type: "我的福利",
      },
    });
	getWelfarePage();
  });
  onHide(() => {
	uni.setStorageSync('lookWelfare', '');
  });
  onShow(() => {
	let lookWelfare = uni.getStorageSync('lookWelfare');
	if(lookWelfare){
		activeTab.value =1;
		switchTab(activeTab.value);
	}
  });
	const claimBenefit = (benefit) => {
		console.log(benefit);
		console.log(activeTab.value);
		if(activeTab.value == 1){
			if(benefit.name == 'jifen'){
				navTo({
					url: '/pages_goods/pointMall/pointMall'
				});
			}else if(benefit.name == 'video'){
				navTo({
					url: '/pages_app/video/video?from=myWelfare'
				});
			}else if(benefit.name == 'kejian'){
				navTo({
					url: '/pages_app/ppt/ppt'
				});
			}else if(benefit.name == 'upan'){
				let num = getFirstNum(benefit.left_result) || benefit.num;
				navTo({
					url: '/pages_app/buyUpan/buyUpan?restNum='+num
				});

			}else if(benefit.name == 'wanfang'){
				navTo({
					url: '/pages_app/zhinan/zhinan'
				});
			}else if(benefit.name == 'daicha'){
				// if(benefit.num == 0){
				// 	showDialog.value = true;
				// }else{
					plus.share.getServices(res => {
	const wechat = res.find(i => i.id === 'weixin')
	if (wechat) {
		wechat.openCustomerServiceChat({
			corpid: 'wwc72af5440141e84e',//第三步获取
			url: 'https://work.weixin.qq.com/kfid/kfceb116f7032dbbb91',
		}, src => {
			console.log("success:")
		}, err => {
			console.log("error:")
		})
	} else {
		uni.showToast({
			title: '当前环境不支持',
			icon: "error"
		});
	}
});

				//}
			}
		}else if(activeTab.value == 0){
			if(benefit.flag){
				receiveWelfare(benefit.name);
			}
			
		}
	};

	const goPointsDetail = () => {
		navTo({
			url: '/pages_app/myPoint/myPoint'
		})
	};

	const gofuliDetail = () => {
		navTo({
			url: '/pages_app/myWelfare/welfareDetail'
		})
	};

	const goAddPatient = () => {
		// uni.sendNativeEvent('goExpertQrcodePage', {
		// 	msg: "expertQrcodePage"
		// },ret => {

		// 	console.log(ret);
		// })
		navTo({
			url: '/pages_app/myCode/myCode?from=myWelfare'
		})
	};
   const goRules = () => {
	
		navTo({
			url: '/pages_app/webview/webview?url='+encodeURIComponent('https://doc.igandan.com/app/integral/integral_welfare.html')+'&title=福利规则'
		})
	};

	const receiveWelfare = (name) => {
		let type = '';
		if(name == 'jifen'){
			type = 0;
		}else if(name == 'video'){
			type = 1;
		}else if(name == 'kejian'){
			type = 2;
		}else if(name == 'upan'){
			type = 5;
		}else if(name == 'wanfang'){
		   return false;
		}else if(name == 'daicha'){
			return false;
		}
		
		api.receiveWelfare({
			type: type
		}).then(res => {
			if(res.code == 200){
				uni.showToast({
					title:'领取成功',
					icon: 'success'
				});
				getWelfarePage();
			}
		})
	}
	const getFirstNum = (str) => {
		if(!str) return '';
		let num = str.substring(0,1);
		return Number(num);
	}
	const useWelfarePage = () => {
		api.useWelfarePage().then(res => {
			if (res.code === '200' && res.data) {
				// 更新福利列表数据
				res.data.forEach(item => {
					item.name = item.name.replace(' ', '');
				});
				
				// 定义排序顺序：肝胆积分、肝胆视频、肝胆课件、查找文献、知识U盘
				const sortOrder = ['jifen', 'video', 'kejian', 'daicha', 'upan'];
				
				// 对列表进行排序
				benefitsList.value = res.data.sort((a, b) => {
					const indexA = sortOrder.indexOf(a.name);
					const indexB = sortOrder.indexOf(b.name);
					
					// 如果找不到对应的排序索引，放在最后
					if (indexA === -1 && indexB === -1) return 0;
					if (indexA === -1) return 1;
					if (indexB === -1) return -1;
					
					return indexA - indexB;
				});
			}
		});
	};


	const getWelfarePage = () => {
		api.getWelfarePage().then(res => {
			console.log(res);
			if (res.code === '200' && res.data) {
				
				// 更新福利列表数据
				benefitsList.value = res.data;
			}
		}).catch(err => {
			console.error('获取福利数据失败:', err);
			uni.showToast({
				title: '获取福利数据失败',
				icon: 'none'
			});
		});
	};

	
</script>

<style lang="scss" scoped>
	// 变量定义
	$bg-color: #f5f6f7;
	$text-primary: #333333;
	$text-secondary: #666666;
	$text-light: #999999;
	$border-color: #e5e5e5;
	$white: #ffffff;
	$theme-color: #e74c3c;
	$divider-color: #cccccc;
	$nav-height: 140rpx; // 导航栏高度
	$segmented-height: 80rpx; // 分段控制器高度
	$bottom-nav-height: 120rpx; // 底部导航高度


	.benefits-page {
		height: 100vh;
		background-color: $bg-color;
		
	}

	.status-bar {
		height: 44rpx;
		background-color: $white;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 30rpx;
		font-size: 24rpx;
		color: $text-primary;

		.status-left {
			display: flex;
			align-items: center;
			gap: 10rpx;

			.time {
				font-weight: 500;
			}

			.butterfly {
				font-size: 20rpx;
			}
		}

		.status-right {
			display: flex;
			align-items: center;
			gap: 20rpx;

			.network-info,
			.signal,
			.wifi,
			.battery {
				font-size: 22rpx;
			}
		}
	}

	.header {
		height: 88rpx;
		background-color: $white;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 30rpx;
		border-bottom: 1rpx solid $border-color;

		.header-left {
			.back-btn {
				font-size: 48rpx;
				color: $theme-color;
				font-weight: bold;
			}
		}

		.header-center {
			.title {
				font-size: 36rpx;
				color: $text-primary;
				font-weight: bold;
			}
		}

		.header-right {
			.rules-btn {
				font-size: 28rpx;
				color: $text-primary;
			}
		}
	}

	.segmented-control {
		position: fixed;
		top: calc(var(--status-bar-height) + 44px);
		left: 0;
		right: 0;
		z-index: 10;
		height: 80rpx;
		background-color: $white;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		border-bottom: 1rpx solid #eee;

		.tab-item {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			height: 100%;
			position: relative;

			.tab-text {
				font-size: 28rpx;
				color: $text-secondary;
				transition: all 0.3s ease;
			}

			&.active {
				.tab-text {
					color: #8B2316;
					
					font-size: 30rpx;
				}
			}
		}

		.divider {
			width: 2rpx;
			height: 40rpx;
			background-color:#eee;
		}
	}
  .scrollbox{
	  position: fixed;
	  width:100%;
	  top: calc(var(--status-bar-height) + 44px + 82rpx);
		height:calc(100vh - var(--status-bar-height) - 44px - 82rpx - 100rpx);
	  box-sizing: border-box;
	//   bottom: 100rpx;
	padding-bottom: 50rpx;
	  margin: 30rpx 0  0;
	
  }
	
		

		.benefit-card {
			background: $white;
			border-radius: 20rpx;
			padding: 30rpx;
			margin:0 30rpx 30rpx;
			
			position: relative;
			overflow: hidden;
			border:2rpx solid #fff;
            &.jifen{
				border:2rpx solid #ef828f;
				background:#feeae9;
			}
			&.wenxian{
				border:2rpx solid #33c966;
				background:#efffe9;
			}
			&.video{
				border:2rpx solid #ff951d;
				background:#fefbea;
			}
			&.kejian{
				border:2rpx solid #f17dff;
				background:#fdeafe;
			}
			&.upan{
				border:2rpx solid #40cdc5;
				background:#eafffa;
			}
			&.wanfang{
				border:2rpx solid #4aa2fe;
				background:#fff;
			}
			.disabled-text {
				color: $text-light !important;
			}

			.card-bg {
				position: absolute;
				top: 0;
				right: 20rpx;
				left:20rpx;
			    z-index:0;
			}
			.card-title {
					font-size: 32rpx;
					
					margin-bottom: 30rpx;
					line-height: 1.4;
					&.jifen{
						color: #ef828f;
					}
					&.video{
						color: #ff951d;
					}
					&.kejian{
						color: #f17dff;
					}
					&.upan{
						color: #40cdc5;
					}
					&.upan_disabled{
						color: #cccccc;
					}
					&.wanfang{
						color: #4aa2fe;
					}
					&.wenxian{
						color: #33c966;
					}
				}
			.card-content {
				margin-top: 30rpx;
				position: relative;
				min-height: 220rpx;
				z-index: 1;
				.card-img{
					position: absolute;
					top: 0;
					left: 0;
					z-index: 0;
					width: 100%;
					height: 100%;
				}

				
				.panbox{
				
					margin-top: 20rpx;
					font-size: 32rpx;
					color: #fff;
					font-weight: 600;
					height: 84rpx;
					line-height: 84rpx;
					background: #40cdc5;
					border-radius: 10rpx;
					padding: 0 20rpx;
					text-align: center;
					&.disabled{
						background: #cccccc;
					}
				}
				.card-details {
					position: relative;
					z-index: 2;
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding:0 40rpx;
                    height: 220rpx;
					.left-section{
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: flex-start;
						.condition,
						.reward-type {
							font-size: 32rpx;
							color: rgba(255, 255, 255, 11);
						}

						.requirement,
						.reward-value {
							margin-top: 8rpx;
							font-size: 42rpx;
							color: $white;
							font-weight: bold;
						}
						.requirement{
							margin-top: 40rpx;
						}
					}
					.right-section {
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: center!important;
						

						.condition,
						.reward-type {
							font-size: 32rpx;
							color: rgba(255, 255, 255, 11);
						}

						.requirement,
						.reward-value {
							margin-top: 8rpx;
							font-size: 42rpx;
							color: $white;
							font-weight: bold;
						}
						.requirement{
							margin-top: 40rpx;
						}
					}

					.right-section {
						align-items: flex-end;
					}
				}
			}

			.status-indicator {
				position: absolute;
				top: 10rpx;
				right: 10rpx;
				background-color: #4CAF50;
				border-radius: 20rpx;
				padding: 4rpx 10rpx;
				font-size: 20rpx;
				color: $white;
				z-index: 2;
			}

			.status-indicator.disabled {
				background-color: #FF9800;
			}
		}
	

	.bottom-nav {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 10;
		height: 100rpx;
		background-color: #00cbc0;
		border-top: 1rpx solid $border-color;
		display: flex;
		align-items: center;
		justify-content: space-around;
		padding: 0 20rpx;

		.nav-item {
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: flex;
			

			.nav-icon {
				font-size: 40rpx;
			}

			.nav-text {
				font-size: 32rpx;
				margin-left: 8rpx;
				color: #fff;
			}
		}
	}
	.nav-right{
		font-size: 28rpx;
		color: #8B2316;
	}
</style>