<template>
	<view class="gbox">
		<u-list @scrolltolower="scrolltolower" height="100%">
			<u-list-item v-for="(item, index) in list" :key="index">
				<view class="gbox-item">
					<view class="gbox-item-top adf">
						<view class="gbox-item-top-type">{{typeCfg[item.type]||'个人版'}}</view>
						<view class="gbox-item-top-title">{{item.reportName||''}}</view>
					</view>
					<view class="gbox-item-ps">
						<view class="gbox-item-p adfac">
							<view class="gbox-item-p-left">团队名称：</view>
							<view class="gbox-item-p-right">{{item.teamName||''}}</view>
						</view>
						<view class="gbox-item-p adf">
							<view class="gbox-item-p-left">报告状态：</view>
							<view class="gbox-item-p-right" :style="{'color':stateColor[item.state]}">{{stateDict[item.state]}}</view>
						</view>
						<view class="gbox-item-p adf">
							<view class="gbox-item-p-left">创建时间：</view>
							<view class="gbox-item-p-right">{{item.createDate||''}}</view>
						</view>
						<!-- <image class="gbox-item-ask" :src="imgBase+'report_ask.png'" @click="askReport(item)" v-if="item.state==1&&item.fileUrl"></image> -->
						<image class="gbox-item-ask" :src="imgBase+'report_ask.png'" @click="testShow=true" v-if="item.state==1&&item.fileUrl"></image>
					</view>
					<view class="gbox-item-bottom adfacjb">
						<view class="gbox-item-bottom-rightbox adfac" v-if="item.type==1">
							<view class="gbox-item-bottom-right" @click="reviewArtifact(item, 'background')" v-if="item.state==1">背景报告</view>
							<view class="gbox-item-bottom-right" @click="reviewArtifact(item, 'professional')" v-if="item.state==1">专业版</view>
							<view class="gbox-item-bottom-right" @click="reviewArtifact(item, 'public')" v-if="item.state==1">公开版</view>
							<view class="gbox-item-bottom-right" @click="reSendReport(item)" v-if="item.state==-1">重新生成</view>
						</view>
						<view class="gbox-item-bottom-rightbox adfac" v-else-if="item.type==2">
							<view class="gbox-item-bottom-right" @click="reviewArtifact(item, 'background')" v-if="item.state==1">背景报告</view>
							<view class="gbox-item-bottom-right" @click="reviewArtifact(item, 'professional')" v-if="item.state==1">专业版</view>
							<view class="gbox-item-bottom-right" @click="reviewArtifact(item, 'public')" v-if="item.state==1">公开版</view>
							<view class="gbox-item-bottom-right" @click="forwardReport(item)" v-if="item.state==1&&item.fileUrl">发送邮件</view>
							<view class="gbox-item-bottom-right" @click="sendReport(item)" v-if="item.state!=-1">发送报告</view>
							<view class="gbox-item-bottom-right" @click="reSendReport(item)" v-if="item.state==-1">重新生成</view>
						</view>
					</view>
				</view>
			</u-list-item>
		</u-list>
		<view class="kind-reminder adffcacjc" v-if="testShow">
			<view class="kr-box adffcac">
				<view class="kr-title">温馨提示</view>
				<view class="kr-p" style="margin-top: 54rpx;">功能测试中，即将上线，敬请期待！</view>
				<view class="kr-btn" @click="testShow=false">确定</view>
			</view>
		</view>
		<cus-select-team-user 
			ref="selectTeamUser" 
			:show="teamUserShow"
			:list="teamUserList"
			@close="handleClose"
			@changeAll="changeAll"
			@handleSelectUser="handleSelectUser"
			@handleConfirm="sendConfirm"
		></cus-select-team-user>
	</view>
</template>

<script>
	import { getPlatformInfo } from '@/utils/platform.js'; 
	import { reportArtifactUrl } from '@/utils/reportArtifactLinks.js'
	import CusSelectTeamUser from '@/components/CusSelectTeamUser/index.vue'
	export default {
		props:{
			list:{
				typeof:Array,
				default:[]
			}
		},
		components:{ CusSelectTeamUser },
		data(){
			return {
				typeCfg:{
					1:'个人版',
					2:'团队版',
					0:'团队PRO版'
				},
				stateDict:{
					'0':'生成中',
					'1':'生成成功',
					'-1':'生成失败'
				},
				stateColor:{
					'0':'#FFD750',
					'1':'#33A7A7',
					'-1':'#F4657A'
				},
				teamUserShow:false,
				teamUserList:[],
				categoryData:[],
				sendType:1,
				selectItem:null,
				testShow:false
			}
		},
		methods:{
			scrolltolower(){
				this.$emit('scrolltolower')
			},
			getUserCategoryData(){
				return new Promise((resolve,reject)=>{
					this.$api.get('/getListByType/UserCategory').then(({data:res})=>{
						if(res.code!==0) return this.$showToast(res.msg)
						this.categoryData = res.data.map(d=>({name:d.dictLabel,id:d.dictValue}))
						resolve()
					})
				})
			},
			async forwardReport(item){
				//发送给账号自己的邮箱
				if(!uni.getStorageSync('userInfo')||!JSON.parse(uni.getStorageSync('userInfo')).email) return this.$showModal('发送邮件前请先在我的-设置-用户信息中绑定邮箱')
				uni.showModal({
					title:'温馨提示',
					content:`是否确认将“${item.reportName||''}”下的PDF报告文件发送到账号绑定邮箱中？`,
					confirmText:'确认',
					success: (res) => {
						if(res.confirm){
							this.$api.get(`/core/report/sendToEmail/${item.reportId}`).then(({data:res})=>{
								if(res.code!==0) return this.$showToast(res.msg)
								this.$showModal('邮件发送成功，可在绑定的邮箱中查看详细内容。')
							})
						}
					}
				})
				
				// this.sendType = 1;
				// this.$refs.selectTeamUser.title = '发送邮件'
				// await this.getUserCategoryData()
				// this.$api.get(`/core/member/listByQueTeamId/${item.teamQueId}`).then(({data:res})=>{
				// 	if(res.code!==0) return this.$showToast(res.msg)
				// 	this.teamUserList = res.data;
				// 	this.teamUserList.forEach((l,i)=>{
				// 		l.categoryName = this.categoryData.find(c=>c.id==l.category)?.name;
				// 		this.$set(this.teamUserList[i],'select',false);
				// 	})
				// 	this.teamUserShow = true;
				// })
			},
			handleSelectUser(index){
				this.$set(this.teamUserList[index],'select',!this.teamUserList[index].select);
				this.dealNumAndAll()
			},
			handleClose(){
				this.teamUserShow = false;
				this.initSelectUserComponent();
			},
			changeAll(selected){
				this.teamUserList.forEach((l,i)=>{
					this.$set(this.teamUserList[i],'select',selected);
				})
				this.$refs.selectTeamUser.selectNums = this.teamUserList.filter(l=>l.select).length;
			},
			dealNumAndAll(){
				const selectnum = this.teamUserList.filter(l=>l.select).length;
				this.$refs.selectTeamUser.selectNums = selectnum;
				this.$refs.selectTeamUser.selectAll = selectnum === this.teamUserList.length;
			},
			sendConfirm(){
				if(this.teamUserList.filter(t=>t.select).length===0) return this.$showToast('请选择要发送的用户')
				if(this.sendType===1&&(!uni.getStorageSync('userInfo')||!JSON.parse(uni.getStorageSync('userInfo')).email)) return this.$showModal('发送前请先在我的-设置-用户信息中绑定邮箱')
				
				if(this.sendType===1){
					this.handleClose();
				} else if(this.sendType===2){
					const item = JSON.parse(JSON.stringify(this.selectItem));
					uni.showModal({
						title:'发送报告',
						content:`是否确认将“${item.reportName||''}”发送给团队成员`,
						confirmText:'确认',
						success: (res) => {
							if(res.confirm){
								this.$api.post(`/core/report/sendReport`,{
									reportId:item.reportId,
									memberList:this.teamUserList.filter(t=>t.select).map(t=>({id:t.id,mobile:t.mobile,category:t.category}))
								}).then(({data:res})=>{
									if(res.code!==0) return this.$showToast(res.msg)
									this.handleClose();
									uni.navigateTo({
										url:'/pagesHome/sendResult?result='+res.code
									})
								})
							}
						}
					})
				}
			},
			initSelectUserComponent(){
				this.$refs.selectTeamUser.selectNums = 0;
				this.$refs.selectTeamUser.selectAll = false;
			},
			reviewArtifact(item, kind){
				const url = reportArtifactUrl(item, kind)
				if(!url) return this.$showToast('该报告尚未生成，请稍后再试。')
				const { isPC, isMobile, platform } = getPlatformInfo();
				console.log(platform,'platform');//android
				if (isPC) {
					this.$showModal('请在手机端该微信小程序中查看报告')
				} else if (isMobile||platform==='devtools') {
					this.openReportDocument(url)
					// uni.navigateTo({
					// 	url:'/pages/webView?src='+item.fileUrl
					// })
				}
			},
			async openReportDocument(fileUrl) {
			  try {
				// 1. 显示加载提示
				uni.showLoading({ title: '加载中...' });
				// 2. 先下载PDF文件到本地（解决安卓直接预览网络文件慢的问题）
				const downloadRes = await uni.downloadFile({
				  url: fileUrl,
				  // 可选：设置超时时间，避免长时间等待
				  timeout: 30000
				});
				
				const dres = downloadRes[1]||null;
				
				if (dres.statusCode !== 200) {
				  uni.hideLoading();
				  uni.showToast({ title: '文件下载失败', icon: 'none' });
				  return;
				}
		
				// 3. 按实际扩展名使用微信原生文档预览
				const openRes = await uni.openDocument({
				  filePath: dres.tempFilePath,
				  fileType: this.documentType(fileUrl),
				  showMenu: false
				});
		
				uni.hideLoading();
			  } catch (error) {
				uni.hideLoading();
				uni.showToast({ title: '加载失败，请重试', icon: 'none' });
				}
			},
			documentType(fileUrl) {
				const path = (fileUrl || '').split('?')[0].toLowerCase()
				return path.endsWith('.docx') ? 'docx' : 'pdf'
			},
			askReport(item){
				uni.navigateTo({
					url:`/pages/reportAsk?pdfUrl=${item.fileUrl}&fileName=${this.typeCfg[item.type]||'个人版'}-${item.reportName}`
				})
			},
			async sendReport(item){
				if(!item.fileUrl) return this.$showModal('该报告尚未生成PDF文件，请等待生成后发送。')
				
				this.sendType = 2;
				this.$refs.selectTeamUser.title = '发送报告'
				this.selectItem = item;
				await this.getUserCategoryData()
				this.$api.get(`/core/member/listByQueTeamId/${item.teamQueId}`).then(({data:res})=>{
					if(res.code!==0) return this.$showToast(res.msg)
					this.teamUserList = res.data;
					this.teamUserList.forEach((l,i)=>{
						l.categoryName = this.categoryData.find(c=>c.id==l.category)?.name;
						this.$set(this.teamUserList[i],'select',false);
					})
					this.teamUserShow = true;
				})
			},
			reSendReport(item){
				this.$api.get(`/core/report/regenerateReport/${item.reportId}`).then(({data:res})=>{
					if(res.code!==0) return this.$showToast(res.msg)
					this.$emit('reSendReport')
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.gbox{
		height: 100%;
		&-item{
			margin-top: 20rpx;
			background: #FFFFFF;
			border-radius: 24rpx;
			padding: 40rpx 20rpx 20rpx;
			&-top{
				&-type{
					width: 98rpx;
					height: 36rpx;
					padding: 2rpx 13rpx;
					box-sizing: border-box;
					background: #FFF7DC;
					border-radius: 6rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 24rpx;
					color: #BA9B31;
					line-height: 33rpx;
				}
				&-title{
					width: calc(100% - 98rpx);
					font-family: PingFang-SC, PingFang-SC;
					font-weight: bold;
					font-size: 32rpx;
					color: #002846;
					line-height: 32rpx;
					text-indent: 17rpx;
				}
			}
			
			&-ps{
				margin-top: 20rpx;
				background: #F5F8FA;
				border-radius: 5px;
				padding: 20rpx 20rpx 30rpx;
				position: relative;
			}
			
			&-p{
				margin-top: 32rpx;
				&:first-child{
					margin-top: 0;
				}
				&>view{
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 24rpx;
					color: #667E90;
					line-height: 24rpx;
				}
				&-left{
					width: 134rpx;
				}
				&-right{
					width: calc(100% - 134rpx);
				}
				&-progress{
					width: calc(100% - 134rpx);
					&-l{
						width: 410rpx;
						height: 12rpx;
						background: #F0F2F8;
						border-radius: 6rpx;
						position: relative;
						&-current{
							height: 12rpx;
							background: #FFDF73;
							border-radius: 6rpx;
							position: absolute;
							left: 0;
							top: 0;
						}
					}
					&-r{
						width: calc(100% - 410rpx);
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #002846;
						line-height: 24rpx;
						text-align: right;
					}
				}
			}
			
			&-ask{
				width: 64rpx;
				height: 64rpx;
				position: absolute;
				right: 20rpx;
				bottom: 42rpx;
			}
			
			&-bottom{
				margin-top: 20rpx;
				overflow: hidden;
				&-rightbox{
					flex: 1;
					margin-left: -35rpx;
					justify-content: flex-end;
				}
				&-left{
					&>view{
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #667E90;
						line-height: 24rpx;
					}
				}
				&-right{
					width: calc(25% - 35rpx);
					padding: 15rpx;
					text-align: center;
					box-sizing: border-box;
					background: linear-gradient( 90deg, #33A7A7 0%, #4DB2B2 100%);
					border-radius: 20rpx;
					font-family: PingFang-SC, PingFang-SC;
					font-size: 24rpx;
					color: #FFFFFF;
					margin-left: 35rpx;
				}
			}
		}
	
		.kind-reminder{
			position: fixed;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
			z-index: 1000;
			background: rgba(0, 0, 0, .6);
			.kr-box{
				width: calc(100% - 100rpx);
				padding: 54rpx 60rpx 48rpx;
				box-sizing: border-box;
				background: url('https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/remind_bg.png') no-repeat;
				background-size: 100% 100%;
				position: relative;
				image{
					width: 48rpx;
					height: 48rpx;
					position: absolute;
					top: 40rpx;
					right: 30rpx;
				}
				.kr-title{
					font-family: PingFang-SC, PingFang-SC;
					font-weight: bold;
					font-size: 36rpx;
					color: #002846;
					line-height: 56rpx;
					text-align: center;
				}
				.kr-p{
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 30rpx;
					color: #002846;
					line-height: 48rpx;
					text-align: center;
					span{
						font-weight: bold;
						margin: 0 10rpx;
					}
				}
				.kr-btn{
					width: calc(100% - 80rpx);
					height: 88rpx;
					background: linear-gradient( 90deg, #33A7A7 0%, #64BBBB 100%);;
					border-radius: 44rpx;
					font-family: PingFang-SC, PingFang-SC;
					font-weight: bold;
					font-size: 32rpx;
					color: #FFFFFF;
					line-height: 88rpx;
					text-align: center;
					letter-spacing: 2rpx;
					margin-top: 66rpx;
				}
			}
		}
	}
</style>
