<template>
 	<div class="app"> 
		<div class="title">
			<div>
				<el-button @click="toAddPage" type="primary">设计问卷</el-button>
			</div>
			<div> 
				   <el-input
						v-model="scarData"
						placeholder="请输入内容" 
						@keyup.enter="getListData"
					> 
						<template #append>
							<el-button @click="getListData" icon="Search" />
						</template>
					</el-input>
			</div> 
		</div>
		<div class="content">
			<div v-for="(v,i) in dataList" :key="i">
				<div>
					<div @click="toTianBaoPage(v.surveyId , '标题预览')">
						<a style="color:rgb(0 ,169 ,255)"><u>{{v.title}}</u>&emsp;<span style="color:#000">( {{isEnd(v)}} )</span></a>
					</div> 
					<div>答卷：{{ v.answercount || 0 }}</div>
					<div>{{ v.createtime }}</div> 
				</div>
				<div>  
					<div>
						<el-button text @click="editFn(v.surveyId)">
							<template #icon>
								<el-icon style="font-size:16px;color:#00b2f9"><Edit /></el-icon>
							</template>
							<template #default>
								编辑问卷
							</template>
						</el-button>
						<el-button text @click="getFaBuData(v)">
							<template #icon>
								<el-icon style="font-size:16px;color:#00b2f9"><EditPen /></el-icon>
							</template>
							<template #default>
								修改发布信息
							</template> 
						</el-button>
						<el-button text @click="toTongJiPage(v.surveyId)">
							<template #icon>
								<el-icon style="font-size:16px;color:#00b2f9"><Search /></el-icon>
							</template>
							<template #default>
								查看分析结果
							</template> 
						</el-button>
						<el-button text @click="dowYuanShi(v.surveyId)">
							<template #icon>
								<el-icon style="font-size:16px;color:#00b2f9"><Document /></el-icon>
							</template>
							<template #default>
								下载原始数据
							</template> 
						</el-button>
					</div>
					<div>
						<el-button type="primary" text @click="getUserData(v.surveyId)">查看用户</el-button>
						<el-button type="primary" text @click="copyFn(v.surveyId)">复制</el-button>
						<el-button @click="deleteFn(v.surveyId)" type="danger" text>删除</el-button>
						<div style="display: flex; align-items: center;">
							<el-button type="primary" text @click="copyUrl(v.surveyId)">复制链接</el-button>
							<input style="position: absolute;z-index: -9999;" :value="returnCopyData(v)" :id="`pageCopy_${v.surveyId}`" />
						</div>
						<div style="display: flex; align-items: center;"> 
							<el-button  type="primary" text size="small" @click="dowQR(v)" >下载二维码</el-button> 
							<div style="display:none" :id="`pageQR_${v.surveyId}`"></div>
						</div> 
					</div>
				</div>
			</div>
		</div>


		<!-- 弹出框 --> 
		<el-dialog
			v-model="faBuDis"
			title="修改发布信息"
			width="30%"
			@close="fabuClose"
		>
			<div>
				<el-form :model="fabuFormData" label-width="120px">
					<!-- <el-form-item label="调研对象" v-show="false">
						<el-radio v-model="fabuFormData.surveyway" :label="公开访问"  value="1"/>
					</el-form-item> -->
					<el-form-item label="访问设置">
						<el-checkbox v-model="fabuFormData.setting" :true-label="1">只能在微信中填写</el-checkbox>
					</el-form-item>
					<el-form-item label="调研时间">
						<el-date-picker
							v-model="fabuFormData.time"
							type="datetimerange"
							range-separator="至"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							value-format="YYYY-MM-DD HH:mm:ss"
						/>
					</el-form-item>
					<el-form-item label="提交时弹窗设置"> 
						<el-checkbox-group v-model="fabuFormData.set">
							<el-checkbox label="输入姓名" />
							<el-checkbox label="输入手机号" />
						</el-checkbox-group>
					</el-form-item>
				</el-form>
			</div>
			<template #footer>
				<el-button @click="faBuDis = false">取消</el-button>
				<el-button type="primary" @click="fabuSub()">确认</el-button>
			</template>
		</el-dialog>

		<!-- 弹出框 --> 
		<el-dialog
			v-model="userDis"
			title="用户列表"
			width="60%"
		>
			<div>
				 <el-table :data="userData" style="width: 100%">
					<el-table-column  prop="answeruser" label="用户头像/昵称">
						<template v-slot="scoped">
							<div style="display:flex;align-items: center;column-gap: 10px;">
								<el-image style="width: 50px; height: 50px;border-radius: 50px;" :src="scoped.row.imgurl"  />
								<div>{{scoped.row.nickname}}</div>
							</div>
						</template>
					</el-table-column>
					<el-table-column align="center" prop="entername" label="用户姓名" />
					<el-table-column align="center" prop="enterphone" label="手机号"  />
					<el-table-column align="center" prop="createtime" label="提交时间" />
					<el-table-column align="center" :formatter="userTimeFn" label="答题时长"/>
					<el-table-column align="center" label="操作" width="180">
						<template v-slot="scoped">
							<el-button @click="toTianBaoPage(scoped.row)" text size="small" type="primary" >查看</el-button>
							<el-button @click="deleteUserData(scoped.row.answersheetId)" text size="small" type="danger" >删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<template #footer>
				<el-button @click="userDis = false">关 闭</el-button> 
			</template>
		</el-dialog> 

  	</div>
</template>

<script setup >
import { ref, getCurrentInstance } from 'vue';
    
import { useRouter } from 'vue-router'; 
const router = useRouter();

import QRCode from 'qrcodejs2-fix';

import request from '@/utils/request' 
import { download } from '@/utils/request'
import { getPageListData, deletePageData, createPageData, editPageData } from '@/api/main/system/system';

const { proxy } = getCurrentInstance();

// 行数据
const table = ref({})

// 表格数据
const dataList = ref([]); ;

// 搜索数据
const scarData = ref('');

// 用户弹出框
const userDis = ref(false);
// 用户数据
const userData = ref([]);

// 发布弹出框
const faBuDis = ref(false);
// 发布表单数据
const fabuFormData = ref({
	surveyway : 1, //调研方式
	setting : '', //只能在微信中访问
	time : [],
	set : [],
})
 
 

// 获取列表
const getListData = (() => {
    return (function fn(page) {
        dataList.value = []; 
 
        getPageListData(`/survey/survey` , { title : scarData.value } ).then(({ data, total }) => {
            dataList.value = data; 
        });
        return fn;
    })();
})();

// 二维码下载
function dowQR (v){
	const el = document.getElementById(`pageQR_${v.surveyId}`);
	el.innerHTML = '';
	 
	new QRCode( el , {
		text: returnCopyData(v) , //二维码内容字符串
		width: 128, //图像宽度
		height: 128, //图像高度
		colorDark: '#000000', //二维码前景色
		colorLight: '#ffffff', //二维码背景色
		correctLevel: QRCode.CorrectLevel.H, //容错级别
	}) 

	let img = document.querySelectorAll(`#pageQR_${v.surveyId} img`)[0];
	img.onload = ()=>{ 
		let a = document.createElement('a');
		a.setAttribute('href' , img.src);
		a.download = '二维码.png';
		a.click();
	 
		a.remove();
	}

}

// 复制链接
function copyUrl (id){ 
	let el = document.getElementById(`pageCopy_${id}`);
	el.select();
	document.execCommand('copy');

	proxy.$modal.msgSuccess('复制完成！');
}

// 复制链接原始数据
function returnCopyData (v){ 
	// const appid = 'wxe8b06998505853d2';
	// const url = encodeURI(`${getoRigin()}/fillOut?id=${v.surveyId}`);
	// const url = encodeURI(`http://67b12c3.r20.cpolar.top/fillOut?id=${v.surveyId}`); //测试数据
	 
	// if(v.setting === 1){
		// return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=111#wechat_redirect`
	// }else{
		return `${getoRigin()}/fillOut?id=${v.surveyId}`;
	// }

}
 
// 发布回显
function getFaBuData (v){  
	if(v['surveyway'] === 1){
		fabuFormData.value['surveyway'] = 1	
	}else{
		fabuFormData.value['surveyway'] = ''
	}
	if(v['setting'] === 1){ 
		fabuFormData.value['setting'] = 1	
	}else{ 
		fabuFormData.value['setting'] = ''	
	}
	if( v['starttime'] ){
		fabuFormData.value['time'] = [
			v['starttime'] , 
			v['endtime'] 
		]
	}else{
		fabuFormData.value['time'] = []
	}  
	fabuFormData.value['set'] = [ 
		v['entername']  === 1 ? '输入姓名' : '',
		v['enterphone'] === 1 ? '输入手机号' : '',
	]

	table.value = v;
	faBuDis.value = true;
}

// 发布弹出框关闭事件
function fabuClose (){
	fabuFormData.value = {
		surveyway : 1, //调研方式
		setting : '', //只能在微信中访问
		time : [],
		set : [],
	}
}

// 发布提交
function fabuSub(){ 
	let rowData = table.value	 

	let params = {
		surveyId : rowData.surveyId,
		surveyway : fabuFormData.value.surveyway, 
		setting : fabuFormData.value.setting, 
		starttime : fabuFormData.value.time[0],
		endtime : fabuFormData.value.time[1],
		entername : fabuFormData.value.set.includes('输入姓名') ? 1 : 0 ,
		enterphone : fabuFormData.value.set.includes('输入手机号') ? 1 : 0 ,
	};


	editPageData('/survey/survey' , params).then(data=>{
		getListData()
		proxy.$modal.msgSuccess('发布成功！');
		faBuDis.value = false;
	})
}

// 添加问卷
function toAddPage (){
	router.push('/questionnaireManagement/surveyAdd?type=add')
}

// 删除问卷
function deleteFn (id){ 
	deletePageData(`/survey/survey/${id}`).then(()=>{
		getListData(); 
		proxy.$modal.msgSuccess('删除成功！');
	})
}

// 编辑问卷
function editFn (id){
	router.push(`/questionnaireManagement/surveyAdd?id=${id}&type=edit`) 
}

// 复制问卷
function copyFn (id){
	router.push(`/questionnaireManagement/surveyAdd?id=${id}&type=copy`) 
}

// 获取域名
function getoRigin (){
	return location.origin
}

// 跳转至统计页面
function toTongJiPage (id){
	router.push(`/questionnaireManagement/statisticalAnalysis?id=${id}`)  
}

// 跳转至问卷填报
function toTianBaoPage (data , type){
	if(type === '标题预览'){
		router.push(`/questionnaireManagement/fillOut?id=${data}&user=-1`)  
	}else{
		router.push(`/questionnaireManagement/fillOut?id=${data.surveyid}&user=${data.answeruser}`)  
	}
}

// 删除用户数据
function deleteUserData(id){
	deletePageData(`/survey/answersheet/${id}`).then(()=>{
		getUserData();
		getListData();
		proxy.$modal.msgSuccess('删除成功！'); 
	})
}

// 获取用户数据
function getUserData (id){
	userDis.value = true;

	getPageListData('/survey/answersheet' , {
		surveyid : id
	}).then(({data})=>{
		userData.value = data
	})
}

// 计算用户答题时长
function userTimeFn (data){
	let starttime = new Date(data.starttime).getTime()
	let endtime = new Date(data.endtime).getTime()
	let time = endtime - starttime; 

	let h = Math.floor(time / 3600000) 
	let m = Math.floor((time % 3600000) / 60000)

	return `${h}小时${m}分`
}

// 下载原始数据
function dowYuanShi (id){ 
	download('/survey/survey/answerlist/exportExcel' , {surveyid: id} , '原始数据.xlsx').then(()=>{
		proxy.$modal.msgSuccess('下载成功！')
	})
}

// 判断状态
function isEnd (data){
	let oldTime = new Date(data.starttime).getTime();
	let newTime = new Date(data.endtime).getTime();
	let time = new Date().getTime();
	

	if(!data.endtime || !data.starttime){
		return '未发布';
	}

	if(time < oldTime){
		return '未开始';
	}else if(time > newTime){
		return '已结束';
	}else if(time > oldTime && time < newTime){
		return '进行中';
	} 
}
 
</script>

<style scoped lang="scss">
	.app{
		background: rgb(236, 238, 245);
		height: calc(100vh - 84px);
		padding: 20px;
		overflow: auto;

		.title{
			background: #fff;
			padding: 40px 40px 0 40px;

			display: grid;
			grid-template-columns: 100px 300px;
			justify-content: space-between;
			justify-items: start;

			>div:last-child{
				justify-self: end;

				display: flex; 
				column-gap: 10px;
			}
		}
		.content{
			background: #fff;
			padding: 40px;
			min-height: calc(100vh - 84px - 40px);
			>div:nth-child(n+2){
				padding: 20px 0;
				box-sizing: content-box;
			}
			>div:nth-last-child(n+2){
				box-sizing: content-box;
				padding-bottom: 20px;
				border-bottom: 1px solid #e9e9e9;
			}
			>div{
				width: 100%;
				height: 70px;

				display: grid;
				grid-template-columns: 1fr;
				grid-template-rows: 1fr 1fr;

				>div{
					display: grid;
					align-items: center;
				}
				>div:first-child{
					grid-template-columns: 1fr 100px 200px;
					>div:nth-child(n+2){
						justify-self: end;
						color: #7a7a7a;
						font-size: 14px;
					}
				}
				>div:last-child{
					grid-template-columns: 60% 40%;

					>div{
						display: flex;
					}
					>div:first-child{
						column-gap: 80px;
					}
					>div:last-child{
						justify-content: end;
						column-gap: 30px;
					}

					.el-button{
						margin: 0;
						padding: 0;
					}
				}
			}
		}
	}
</style>
