<template>
	<view class="qbox adffc">
		<view class="list" v-if="list.length">
			<up-list @scrolltolower="scrolltolower" style="height: 100%">
				<up-list-item class="list-item" v-for="(item, index) in list" :key="index">
					<view @click.prevent="showDialog(item)">
						<image class="expand" :src="imgBase + 'questionnaire_icon_down.png'"></image>
						<view class="title">{{ item.title || '' }}</view>
						<view class="name">团队名称：{{ item.teamName || '' }}</view>
						<view class="progress adfacjb">
							<view class="progress-left adfac">
								<view class="progress-left-text">作答进度：</view>
								<view class="progress-left-box">
									<view class="progress-left-box-current" :style="{ width: (item.finishNum / item.userNum) * 100 + '%' }"></view>
								</view>
							</view>
							<view class="progress-right">
								<span>{{ item.finishNum }}/</span>
								{{ item.userNum }}
							</view>
						</view>
						<view class="bottom adfacjb">
							<view class="bottom-left">截止时间：{{ item.endTime }}</view>
							<view class="bottom-right" v-if="item.status === 0 && item.type == 1" @click.stop="handleAnswer(item)">立即作答</view>
							<view class="bottom-right" v-else-if="item.status === 1 && !item.fileUrl" @click.stop="createReport(item)">生成报告</view>
						</view>
					</view>
				</up-list-item>
			</up-list>
		</view>
		<view class="empty" v-else>
			<page-empty></page-empty>
		</view>
		<view class="dialog adffc" v-if="show">
			<view class="dbox">
				<view class="dbox-top adfacjb">
					<view class="dbox-top-title">{{ dto.title || '' }}</view>
					<image class="dbox-top-expand" :src="imgBase + 'questionnaire_icon_down.png'" @click="show = false"></image>
				</view>
				<view class="dbox-name">团队名称：{{ dto.teamName || '' }}</view>
				<view class="dbox-progress adfacjb">
					<view class="dbox-progress-left adfac">
						<view class="dbox-progress-left-text">作答进度：</view>
						<view class="dbox-progress-left-box">
							<view class="dbox-progress-left-box-current" :style="{ width: (dto.finishNum / dto.userNum) * 100 + '%' }"></view>
						</view>
					</view>
					<view class="dbox-progress-right">
						<span>{{ dto.finishNum }}/</span>
						{{ dto.userNum }}
					</view>
				</view>
				<view class="dbox-menu">
					<view class="dbox-menu-pre adffcac" v-for="(item, index) in menuListCopy" :key="index" @click="handleMenuClick(item, index)">
						<template v-if="item.text === '分享问卷'">
							<button class="share-btn" open-type="share">
								<image :src="item.img"></image>
								<text>{{ item.text }}</text>
							</button>
						</template>
						<template v-else>
							<image :src="item.img"></image>
							<text>{{ item.text }}</text>
						</template>
					</view>
				</view>
			</view>
		</view>
		<view class="dialog adffc" v-if="teamInfoShow">
			<view class="dialog-box">
				<view class="dialog-box-title">团队信息</view>
				<image class="dialog-box-close" :src="imgBase + 'remind_close.png'" @click="teamInfoShow = false"></image>
				<view class="dialog-box-teaminfo">
					<cus-team-info-fill ref="teamRef" confirmText="保存" @handleConfirm="handleConfirm"></cus-team-info-fill>
				</view>
			</view>
		</view>
		<div class="alert adffcacjc" v-if="alertShow">
			<div class="alert-box">
				<div class="alert-box-title">温馨提示</div>
				<image :src="imgBase + 'remind_close.png'" class="alert-box-close" @click="alertShow = false"></image>
				<div class="alert-box-text">
					该问卷尚未生成报告
					<br />
					请确认团队人员是否全部作答
					<br />
					完成后点击生成报告
				</div>
				<div class="zt_btn" @click="alertShow = false">我知道了</div>
			</div>
		</div>
		<cus-team-user
			:deluser="true"
			:show="teamUserShow"
			:list="teamUserList"
			@close="teamUserShow = false"
			@addUser="addUser"
			@handleConfirm="userConfirm"
			@deleteUser="deleteUser"
		></cus-team-user>
	</view>
</template>

<script>
import PageEmpty from '@/components/pageEmpty/index.vue'
import CusTeamUser from '@/components/CusTeamUser/index.vue'
import CusTeamInfoFill from '@/components/CusTeamInfoFill/index.vue'
export default {
	components:{ PageEmpty, CusTeamUser, CusTeamInfoFill },
	props:{
		list:{
			typeof:Array,
			default:[]
		}
	},
	data(){
		return {
			show:false,
			teamInfoShow:false,
			teamUserShow:false,
			alertShow:false,
			dto:null,
			menuList:[
				{
					img:this.$imgBase+'questionnaire_edit.png',
					text:'编辑问卷'
				},
				{
					img:this.$imgBase+'questionnaire_share.png',
					text:'分享问卷'
				},
				{
					img:this.$imgBase+'questionnaire_info.png',
					text:'团队信息'
				},
				{
					img:this.$imgBase+'questionnaire_copy.png',
					text:'复制链接'
				},
				{
					img:this.$imgBase+'questionnaire_users.png',
					text:'团队人员'
				},
				{
					img:this.$imgBase+'questionnaire_report.png',
					text:'生成报告'
				}
			],
			menuListCopy:[],
			teamUserList:[],
			originTeamUserList:[],
			teamScaleData:[],
			teamLevelData:[],
			categoryData:[],
			delMemberIds:[],
		}
	},
	methods:{
		onShareAppMessage(res) {
		    // res.from === 'button' // 来自页面内分享按钮
		    // res.from === 'menu'   // 来自右上角菜单分享
		    const sharerId = JSON.parse(uni.getStorageSync('userInfo'))?.id;
		    console.log(`准备分享，团队问卷ID: ${this.dto.teamQuestionnaireId}, 分享者ID: ${sharerId}`);
		    return {
		      title: this.dto.title || '发现一个好物，分享给你！',
		      path: `/pages/home?shareTQId=${this.dto.teamQuestionnaireId}&shareUserId=${sharerId}`,
		      // imageUrl: this.$imgBase+''
		    };
		},
		scrolltolower(){
			this.$emit('scrolltolower')
		},
		showDialog(item){
			this.dto = item;
			if(this.dto.type==1) this.menuListCopy = this.menuList.filter((_, index) => index !== 4);
			else this.menuListCopy = JSON.parse(JSON.stringify(this.menuList))
			this.show = true;
		},
		async getTeamScaleData(){
			return new Promise((resolve,reject)=>{
				this.$api.get('/getListByType/team_scale').then(({data:res})=>{
					if(res.code!==0) return this.$showToast(res.msg)
					this.teamScaleData = res.data.map(d=>({name:d.dictLabel,id:d.dictValue}))
					resolve()
				})
			})
		},
		async getTeamHierarchyData(){
			return new Promise((resolve,reject)=>{
				this.$api.get('/getListByType/team_hierarchy').then(({data:res})=>{
					if(res.code!==0) return this.$showToast(res.msg)
					this.teamLevelData = res.data.map(d=>({name:d.dictLabel,id:d.dictValue}))
					resolve()
				})
			})
		},
		async 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 handleMenuClick(item){
			if(item.text==='编辑问卷'){
				uni.navigateTo({
					url:`/pagesHome/questionnaireEdit?teamQuestionnaireId=${this.dto.teamQuestionnaireId}&type=${this.dto.type}&questionnaireName=${this.dto.title}&isEdit=true`
				})
				this.show = false;
			}else if(item.text==='分享问卷'){

			}else if(item.text==='团队信息'){
				this.teamInfoShow = true;
				await this.getTeamScaleData()
				await this.getTeamHierarchyData()
				this.$api.get(`/core/user/team/${this.dto.teamId}`).then(({data:res})=>{
					if(res.code!==0) return this.$showToast(res.msg)
					this.$refs.teamRef.setTeamInfo(res.data)
					this.$refs.teamRef.teamInfo.functionIds = res.data.functions.map(f=>f.id);
					this.$refs.teamRef.teamInfo.orgIds = res.data.organizations.map(o=>o.id);
					this.$refs.teamRef.areaText = res.data.provinceName+res.data.cityName;
					this.$refs.teamRef.industryText = res.data.industryName;
					this.$refs.teamRef.functionTypeText = res.data.functions.map(f=>f.functionName).join('、');
					this.$refs.teamRef.architectureTypeText = res.data.organizations.map(f=>f.orgName).join('、');
					this.$refs.teamRef.teamScaleText = this.teamScaleData.find(d=>d.id==res.data.scale).name;
					this.$refs.teamRef.teamLevelText = this.teamLevelData.find(d=>d.id==res.data.hierarchy).name;
				})
			}
			else if(item.text==='复制链接') {
				let shareUserId = JSON.parse(uni.getStorageSync('userInfo')).id;
				let res = await this.$api.post('/wx/genInviteLink',{
					'path': '',
					'query': `shareTQId=${this.dto.teamQuestionnaireId}&shareUserId=${shareUserId}`,
					'env_version': 'trial'//默认"release"，正式版"release"，体验版"trial"，开发版"develop"
				});
				if(res.data.code!==0) return this.$showToast(res.data.msg)
				uni.setClipboardData({
					data:res.data.data.openlink,
					success: () => {
						this.$showToast('复制成功')
					},
					fail: () => {
						this.$showToast('复制失败')
					}
				})
			}
			else if(item.text==='团队人员'){
				await this.getUserCategoryData()
				this.$api.get(`/core/member/listByQueTeamId/${this.dto.teamQuestionnaireId}`).then(({data:res})=>{
					if(res.code!==0) return this.$showToast(res.msg)
					this.teamUserList = res.data;
					this.originTeamUserList = res.data;
					this.teamUserList.forEach(l=>{
						l.categoryName = this.categoryData.find(c=>c.id==l.category)?.name;
					})
					this.teamUserShow = true
				})
			}
			else if(item.text==='生成报告'){
				if(this.dto.status==0) return this.$showToast('问卷未完成，全部团队人员作答后才能生成报告')
				this.createReportConfirm(this.dto.teamQuestionnaireId)
			}
		},
		handleConfirm(data){
			data.coachId = JSON.parse(uni.getStorageSync('userInfo')).id;
			this.$api.put('/core/user/team',data).then(({data:res})=>{
				if(res.code!==0) return this.$showToast(res.msg)
				this.$showToast('保存成功')
				this.teamInfoShow = false;
			})
		},
		handleAnswer(item){
			uni.navigateTo({
				url:'/pagesPublish/questionnaireFill?teamQuestionnaireId='+item.teamQuestionnaireId+'&teamId='+item.teamId+'&type='+item.type
			})
		},
		createReport(item){
			this.dto = item;
			this.createReportConfirm(item.teamQuestionnaireId)
		},
		createReportConfirm(teamQuestionnaireId){
			this.$api.get(`/core/team/questionnaire/generateReportCheck/${teamQuestionnaireId}`).then(({data:res})=>{
				if(res.code===0&&res.data===0){
					this.createReportFn(teamQuestionnaireId);
				}else if(res.code===0&&res.data>0){
					uni.showModal({
						title:'生成报告',
						content:`该问卷已生成${res.data??0}份报告，是否再次生成新报告？`,
						confirmColor:'#199C9C',
						success: (res) => {
							if(res.confirm){
								this.createReportFn(teamQuestionnaireId);
							}
						}
					})
				}else if(res.code!==0){
					uni.showModal({
						title:'生成报告',
						content:res.msg,
						showCancel:false,
						confirmColor:'#199C9C'
					})
				}
				this.show = false;
			})
		},
		createReportFn(teamQuestionnaireId){
			this.$api.get(`/core/team/questionnaire/genReport/${teamQuestionnaireId}`).then(({data:res})=>{
				this.show = false;
				uni.navigateTo({
					url:'/pagesHome/reportResult?result='+res.code+'&info='+encodeURIComponent(JSON.stringify(this.dto))
				})
			})
		},
		sendReport(item){

		},
		addUser(){
			uni.navigateTo({
				url:'/pagesMy/teamUser?type=select',
				events:{
					selectUserConfirm: data => {
						data.forEach((d,i)=>(this.$set(data[i],'status',0)));
						let newUser = this.filterUsers(this.teamUserList,data)
						this.teamUserList = [...this.teamUserList,...newUser];
					}
				}
			})
		},
		filterUsers(originArr,selectArr){
			const aValuesToExclude = new Set(originArr.map(item => item.id));
			return selectArr.filter(item => {
			  return !aValuesToExclude.has(item.id);
			});
		},
		userConfirm(){
			if(this.teamUserList.length===0) return this.$showToast('至少保留一位团队人员');
			this.$api.get('/core/team/questionnaire/'+this.dto.teamQuestionnaireId).then(({data:res})=>{
				if(res.code!==0) return this.$showToast(res.msg)
				let dto = res.data;
				dto.coachId = JSON.parse(uni.getStorageSync('userInfo')).id;
				dto.delMemberIds = [...new Set(this.delMemberIds)];
				dto.memberList = this.teamUserList;
				dto.type = 2;
				delete dto.memberInfos;
				this.$api.put('/core/team/questionnaire/updateMembers',dto).then(({data:resu})=>{
					if(resu.code!==0) return this.$showToast(resu.msg)
					this.$showToast('操作成功')
					this.teamUserShow = false;
					// this.show = false;
				})
			})
		},
		deleteUser(data){
			let u = this.originTeamUserList.find(u=>u.id===data.item.id);
			if(u) this.delMemberIds=[...this.delMemberIds,u.id]
			this.teamUserList.splice(data.index,1);
		}
	}
}
</script>

<style scoped lang="scss">
.share-btn {
	background-color: transparent;
	border: none;
	padding: 0;
	margin: 0;
	line-height: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	&::after {
		border: none;
	}
}

.qbox {
	width: 100%;
	height: 100%;
	flex: 1;

	.list {
		flex: 1;
		margin-top: 20rpx;
		overflow: hidden;
		&-item {
			width: 100%;
			background: #ffffff;
			border-radius: 24rpx;
			margin-top: 20rpx;
			padding: 36rpx 24rpx 19rpx;
			box-sizing: border-box;
			position: relative;
			display: block;

			.expand {
				width: 32rpx;
				height: 32rpx;
				position: absolute;
				top: 36rpx;
				right: 32rpx;
			}

			.title {
				width: calc(100% - 128rpx);
				font-family: PingFang-SC, PingFang-SC;
				font-weight: bold;
				font-size: 32rpx;
				color: #002846;
				line-height: 32rpx;
			}

			.name {
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #667e90;
				line-height: 24rpx;
				margin-top: 35rpx;
			}

			.progress {
				margin-top: 36rpx;
				&-left {
					width: calc(100% - 95rpx);
					&-text {
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #667e90;
						line-height: 24rpx;
					}
					&-box {
						flex: 1;
						position: relative;
						height: 12rpx;
						background: #f0f2f8;
						border-radius: 6rpx;
						&-current {
							height: 12rpx;
							background: #7cc5c5;
							border-radius: 6rpx;
							position: absolute;
							top: 0;
							left: 0;
						}
					}
				}
				&-right {
					font-size: 24rpx;
					line-height: 24rpx;
					color: #95a5b1;
					span {
						font-size: 24rpx;
						line-height: 24rpx;
						color: #002846;
					}
				}
			}

			.bottom {
				margin-top: 30rpx;
				border-top: 1rpx solid #efefef;
				padding-top: 20rpx;
				&-left {
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 24rpx;
					color: #667e90;
					line-height: 24rpx;
				}
				&-right {
					border-radius: 32rpx;
					background: linear-gradient(90deg, #33a7a7 0%, #4db2b2 100%);
					padding: 19rpx 22rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 26rpx;
					color: #ffffff;
					line-height: 26rpx;
					letter-spacing: 2rpx;
				}
			}
		}
	}

	.empty {
		flex: 1;
	}

	.dialog {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.4);
		z-index: 1001;
		justify-content: flex-end;

		.dbox {
			width: 100%;
			height: 738rpx;
			background: #ffffff;
			box-shadow: 0rpx -2rpx 6rpx 0rpx rgba(0, 0, 0, 0.07);
			border-radius: 24rpx 24rpx 0rpx 0rpx;
			padding: 48rpx 30rpx 0;
			box-sizing: border-box;
			&-top {
				&-title {
					width: calc(100% - 60rpx);
					font-family: PingFang-SC, PingFang-SC;
					font-weight: bold;
					font-size: 32rpx;
					color: #002846;
					line-height: 40rpx;
				}
				&-expand {
					width: 32rpx;
					height: 32rpx;
					transform: rotate(180deg);
				}
			}

			&-name {
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #667e90;
				line-height: 24rpx;
				margin-top: 24rpx;
			}

			&-progress {
				margin-top: 36rpx;
				&-left {
					width: calc(100% - 95rpx);
					&-text {
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #667e90;
						line-height: 24rpx;
					}
					&-box {
						flex: 1;
						position: relative;
						height: 12rpx;
						background: #f0f2f8;
						border-radius: 6rpx;
						&-current {
							height: 12rpx;
							background: #7cc5c5;
							border-radius: 6rpx;
							position: absolute;
							top: 0;
							left: 0;
						}
					}
				}
				&-right {
					font-size: 24rpx;
					line-height: 24rpx;
					color: #95a5b1;
					span {
						font-size: 24rpx;
						line-height: 24rpx;
						color: #002846;
					}
				}
			}

			&-menu {
				margin-top: 43rpx;
				overflow: hidden;
				margin-left: -30rpx;
				&-pre {
					width: calc(25% - 30rpx);
					background: #f7f8fa;
					border-radius: 24rpx;
					padding: 30rpx 20rpx;
					margin-top: 24rpx;
					margin-left: 30rpx;
					box-sizing: border-box;
					float: left;
					image {
						width: 42rpx;
						height: 42rpx;
					}
					text {
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #002846;
						line-height: 24rpx;
						text-align: center;
						margin-top: 24rpx;
					}
				}
			}
		}

		&-box {
			width: 100%;
			height: 1200rpx;
			background: #f7f7f7;
			padding-top: 38rpx;
			border-radius: 24rpx 24rpx 0rpx 0rpx;
			box-sizing: border-box;
			position: relative;
			overflow-y: auto;
			&-title {
				font-family: PingFang-SC, PingFang-SC;
				font-weight: bold;
				font-size: 32rpx;
				color: #002846;
				line-height: 32rpx;
				text-align: center;
			}
			&-close {
				width: 48rpx;
				height: 48rpx;
				position: absolute;
				top: 30rpx;
				right: 30rpx;
			}
			&-teaminfo {
				margin-top: 40rpx;
			}
		}
	}

	.alert {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		z-index: 1002;
		background: rgba(0, 0, 0, 0.4);
		&-box {
			width: calc(100% - 100rpx);
			padding: 54rpx 99rpx 48rpx;
			box-sizing: border-box;
			position: relative;
			background: url('https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/alert_bg.png') no-repeat;
			background-size: 100% 100%;
			&-title {
				font-family: PingFang-SC, PingFang-SC;
				font-weight: bold;
				font-size: 36rpx;
				color: #002846;
				line-height: 56rpx;
				text-align: center;
			}
			&-close {
				width: 48rpx;
				height: 48rpx;
				position: absolute;
				top: 40rpx;
				right: 30rpx;
			}
			&-text {
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 30rpx;
				color: #002846;
				line-height: 48rpx;
				text-align: center;
				margin-top: 32rpx;
			}
			.zt_btn {
				margin-top: 66rpx;
			}
		}
	}
}
</style>
