<template>
	<view style="width: 100%">
		<view class="u-page">
			<u-toast ref="uToast"></u-toast>
			<u-loading-page :loading="loading" bg-color="#e8e8e8"></u-loading-page>

			<u-row customStyle="margin: 10px">
				<u-col span="3">
					<!-- <u-button type="primary" icon="reload" @click="getList" shape="circle" text="刷新状态">
					</u-button> -->
				</u-col>
				<u-col span="3"></u-col>
				<!-- <u-col span="2">
					<view class="u-slot-title">
						<u-tag v-show='!serviceApply.startTime' text="未签到" plain type="warning"></u-tag>
						<u-tag v-show='serviceApply.startTime' text="已签到" plain type="success"></u-tag>
					</view>
				</u-col> -->
				<u-col span="1"></u-col>
				<u-col span="3">
					<!-- <u-button type="primary" style="text-align: right;" icon="map" shape="circle"
						@click="handel_sign_click" text="签到"></u-button> -->
				</u-col>
			</u-row>

			<!-- <u-row customStyle="margin: 10px">
				<u-col span="3">
					<u-button type="primary" icon="reload" @click="getList" shape="circle" text="刷新状态">
					</u-button>
				</u-col>
				<u-col span="6">
					<u--text text="签到状态:"></u--text>
					<u--text v-show='!serviceApply.startTime' type="error" text="未签到"></u--text>
					<u--text v-show='serviceApply.startTime' type="success" text="已签到"></u--text>
				</u-col>
				<u-col span="3">
					<u-button type="primary" style="text-align: right;" icon="map" shape="circle"
						@click="handel_sign_click" text="签到"></u-button>
				</u-col>
			</u-row> -->

			<u-modal width="450rpx" :show="show_signing" :show-close="false" :showConfirmButton="false">
				<view class="slot-content">
					<u-loading-icon mode="circle" text="签到中" textSize="18"></u-loading-icon>
				</view>
			</u-modal>

			<!-- <u-modal :show="show_outsideReason" title="定位超出范围" @confirm="handle_outsideReason_confirm">
				<view class="slot-content">
					<view class="slot-content">
						<u--textarea v-model="serviceApply.attribute1" placeholder="请填写定位超出范围原因,用于记录,不能为空"
							maxlength="50"></u--textarea>
					</view>
				</view>
			</u-modal> -->

			<!-- <u-row customStyle="margin: 5px">
				<u-col span="10">
					<u-search style="z-index: 999;" :disabled='true' bgColor="rgb(255 255 255)" placeholder="搜索"
						shape="round" @click="handle_SearchBox_click" :showAction="false" :animation="true"></u-search>
				</u-col>
				<u-col span="2">
					<u-button type="primary" icon="reload" @click="handleReflashClick" size="small" shape="circle"
						text="连接">
					</u-button>
				</u-col>
			</u-row> -->

			<!-- <u-popup :show="show" @close="close" @open="open">
				<view style="width: 93%;align-self: center;">
					<u--form labelWidth='auto' labelPosition="left" :model="queryParamsForm" :rules="rules" ref="form1">
						<u-form-item label="申请人姓名" prop="name" borderBottom ref="item1">
							<u--input inputAlign='center' shape='square' border="none" v-model="queryParamsForm.name">
							</u--input>
						</u-form-item>
						<u-form-item label="申请人身份证号码" prop="idNumber" borderBottom ref="item1">
							<u--input inputAlign='center' shape='square' border="none"
								v-model="queryParamsForm.idNumber">
							</u--input>
						</u-form-item>
					</u--form>
					<u-row customStyle="margin:10px">
						<u-col span="12">
							<u-button class="custom-style" type="primary" size="small" @click="handel_search_click">搜索
							</u-button>
						</u-col>
					</u-row>
					<u-row customStyle="margin:10px">
						<u-col span="12">
							<u-button class="custom-style" type="primary" size="small" @click="handel_reset_click">重置
							</u-button>
						</u-col>
					</u-row>
				</view>
			</u-popup> -->

			<u-row customStyle="margin-bottom: 10px ">
				<u-col span="12">
					<u-empty v-if="DataList.length == 0" mode="list"></u-empty>
					<u-cell-group customStyle="background-color: white;" v-else>
						<u-cell v-for="(item, index) in DataList"
						 :key="item.assignId" size="large"
						  isLink clickable
						  :title="item.paperName"
							@click="handel_cell_click" 
							:name="item.assignDetailId">
							<view slot="title" class="u-slot-title">
								<text class="u-cell-text">{{ item.paperName }}</text>
								<u-tag v-if="item.status == '1'" text="答题完成" plain size="mini" type="success">
								</u-tag>
								<u-tag v-else-if="item.status == '0'" text="待答题" color="#C6C7CB" borderColor="#C6C7CB"
									plain size="mini">
								</u-tag>
							</view>
						</u-cell>
					</u-cell-group>
					<uni-load-more :status="status" :contentText="loadText" @clickLoadMore="MyonLoad" />
				</u-col>
			</u-row>
		</view>

		<!-- <view class="submit-button">
      <u-button size="large" @click="handle_Answer_click">开始答题</u-button>
    </view> -->
	</view>
</template>

<script setup>
	import {
		listAssignDetail,
		getAssignDetail,
		delAssignDetail,
		addAssignDetail,
		updateAssignDetail,
	} from "@/api/elder/questionnaire/assignDetail";
	import {
		listPaper
	} from "@/api/elder/questionnaire/paper";
	import {
		onLoad,
		onShow,
		onHide,
		onReady
	} from '@dcloudio/uni-app'
	import {
		computed,
		ref,
		reactive,
		onMounted,
	} from 'vue'
	// 遮罩层
	// 选中数组
	let ids = ref([])
	// 总条数
	let total = ref(0)
	// 发起问卷明细表格数据
	let DataList = ref([])
	// 弹出层标题
	let title = ref('')
	// 是否显示弹出层
	let open = ref(false)
	// 查询参数
	let queryParams = reactive({
		pageNum: 1,
		pageSize: 10,
		assignId: null,
		value: null,
		level: null,
		required: null,
		status: null,
	})
	// 表单参数
	let form = reactive({})
	// 表单校验
	let rules = reactive({})
	let checkIn = ref(false) //自动签到
	let show_signing = ref(false) //签到窗口
	let id = ref('')
	// 查询参数
	let loading = ref(false) //加载中提示框显示
	let show = ref(false) //搜索框显示

	let location = ref(null) //位置信息字符串
	let targetDistance = ref(5) //限制定位与用户登记位置的最大误差距离（千米）
	let Distance = ref(0)
	let signStatu = ref("") //签到状态，成功，失败
	let show_outsideReason = ref(false) //超范围原因框
	let isOutside = ref(false) //是否超出范围
	let assignId = ref(null)
	let onLoadDone = ref(false)
	let finished =ref(false)
	let paperOptions = ref([])
	// 计算属性
	let getItemLabel = computed((item) => {
		let result = "";
		if (item.status) result += item.status;
		// if (item.status) result += item.status + ':'
		// if (item.taskStarttime) result += item.taskStarttime
		// if (item.taskEndtime) result += '-' + item.taskEndtime
		return result;
	});
	onLoad((options) => {
		console.log("options", options);
		assignId.value = options.assignId;
		queryParams.assignId = options.assignId;
	})
	onShow(() => {
		//同步等待onLoadDone，直到为true才执行
		finished.value = false; //重置搜索完结
		queryParams.pageNum = 1; //重置搜索页
		getList();
	})
	//开始答题
	function handle_Answer_click() {
		//跳转页面，将考卷ID，答案
		// this.$tab.navigateTo(
		//   "/pages/WenJuanDiaoCha/Answer/edit?assignId=" + this.assignId
		//    + "&assignDetailId=" +
		//     this.assignDetailId +
		//     "&paperId=" +
		//     this.paperId
		// );
	}
	/** 查询发起问卷明细列表 */
	function getList() {
		loading.value = true;
		listAssignDetail(queryParams).then((response) => {
			//将response.rows每一项添加一个paperName和paperGroup属性，通过this.paperOptions的paperId找到对应的paperName和paperGroup
			console.log("listAssignDetail", response);
			if(response.hasOwnProperty('rows')){
				if (response.rows.length > 0) {
					response.rows.forEach((item) => {
						paperOptions.value.forEach((paper) => {
							if (item.paperId == paper.paperId) {
								item.paperName = paper.paperName;
								item.paperGroup = paper.paperGroup;
							}
						});
					});
					DataList.value = response.rows;
					total.value = response.total;
					loading.value = false;
				}
			}else{
				loading.value = false;
				total.value =0;
				DataList.value =[]
			}
		
		});
	}

	function getOptions() {
		listPaper({
			pageNum: 1,
			pageSize: 1000,
		}).then((response) => {
			console.log("getOptions", response);
			paperOptions.value = response.rows;
		});
	}
	// 取消按钮
	function cancel() {
		open.value = false;
		reset();
	}
	// 表单重置
	function reset() {
		form = {
			assignDetailId: null,
			assignId: null,
			orderNum: null,
			value: null,
			level: null,
			required: null,
			createBy: null,
			createTime: null,
			updateBy: null,
			updateTime: null,
			remark: null,
			spare1: null,
			spare2: null,
			spare3: null,
		};
		resetForm("form");
	}
	/** 搜索按钮操作 */
	function handleQuery() {
		queryParams.pageNum = 1;
		getList();
	}
	/** 重置按钮操作 */
	function resetQuery() {
		resetForm("queryForm");
		handleQuery();
	}
	// 多选框选中数据
	function handleSelectionChange(selection) {
		ids.value = selection.map((item) => item.assignDetailId);
		single.value = selection.length !== 1;
		multiple.value = !selection.length;
	}
	/** 新增按钮操作 */
	function handleAdd() {
		reset();
		open.value = true;
		title.value = "添加发起问卷明细";
	}
	/** 修改按钮操作 */
	function handleUpdate(row) {
		reset();
		const assignDetailId = row.assignDetailId || this.ids;
		getAssignDetail(assignDetailId).then((response) => {
			form = response.data;
			open.value = true;
			title.value = "修改发起问卷明细";
		});
	}
	/** 提交按钮 */
	function submitForm() {
		this.$refs["form"].validate((valid) => {
			if (valid) {
				if (form.assignDetailId != null) {
					updateAssignDetail(form).then((response) => {
						this.$modal.msgSuccess("修改成功");
						open.value = false;
						getList();
					});
				} else {
					addAssignDetail(this.form).then((response) => {
						this.$modal.msgSuccess("新增成功");
						open.value = false;
						getList();
					});
				}
			}
		});
	}
	/** 删除按钮操作 */
	function handleDelete(row) {
		const assignDetailIds = row.assignDetailId || this.ids;
		this.$modal
			.confirm(
				'是否确认删除发起问卷明细编号为"' + assignDetailIds + '"的数据项？'
			)
			.then(function() {
				return delAssignDetail(assignDetailIds);
			})
			.then(() => {
				getList();
				this.$modal.msgSuccess("删除成功");
			})
			.catch(() => {});
	}
	/** 导出按钮操作 */
	function handleExport() {
		download(
			"elder/questionnaire/assignDetail/export", {
				...queryParams,
			},
			`assignDetail_${new Date().getTime()}.xlsx`
		);
	}

	function handle_ratingChange(value) {
		// this.form.level = value;
	}
	//跳转回答页面
	function handle_answer(row) {
		console.log("handle_answer", row);
		//URl传参跳转
		// this.$router.push({
		//   name: `Answer`,
		//   params: {
		//     assignDetailId: row.assignDetailId, //这种传参方式，不是在url中传参，而是在路由的params中传参，所以在跳转的时候，需要在路由中配置name和params
		//   },
		// });
	}
	//签到
	function handel_sign_click() {
		if (isOutside.value) {
			show_outsideReason.value = true;
			return;
		}
		show_signing.value = true;
		uni.getLocation({
			type: "gcj02",
			geocode: true,
			isHighAccuracy: true,
			success: (res) => {
				show_signing.value = false;
				location.value =
					res.address.province +
					res.address.city +
					res.address.district +
					res.address.street +
					res.address.streetNum +
					res.address.poiName;
				serviceApply.realLatitude = res.latitude;
				serviceApply.realLongitude = res.longitude;
				// this.signLocation.latitude = res.latitude
				// this.signLocation.longitude = res.longitude
				//比较目标距离(需要申请人信息)
				let Distance = GetDistance(
					serviceApply.taskLatitude,
					serviceApply.taskLongitude,
					serviceApply.realLatitude,
					serviceApply.realLongitude
				);
				Distance.value = Distance * 1000;
				signStatu.value = "成功";
				updateSignLocationAndReason();
				// if (Distance <= this.targetDistance) {
				// 	//距离内
				// 	this.signStatu = "成功";
				// 	this.updateSignLocationAndReason();
				// 	this.$refs.uToast.show({
				// 		type: 'success',
				// 		message: "签到成功",
				// 		iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png',
				// 		complete() {}
				// 	})
				// } else {
				// 	//超出距离,需要填写理由
				// 	this.show_outsideReason = true;
				// 	//签到时间传入作为改造开始时间的默认值/或者签到直接更新每一个的改造开始时间
				// }
			},
			fail: (res) => {
				console.log("定位失败：" + res);
				signStatu.value = "失败";
				this.$refs.uToast.show({
					type: "fail",
					message: "定位失败：" + res,
					complete() {},
				});
				location.value = "定位失败,请检查设备定位权限是否开启";
			},
		});
	}
	// //填写原因确认框
	// handle_outsideReason_confirm() {
	// 	if (!this.serviceApply.attribute1) {
	// 		this.$refs.uToast.show({
	// 			type: 'error',
	// 			message: "原因不能为空",
	// 			iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png',
	// 			complete() {}
	// 		})
	// 		return
	// 	}
	// 	this.show_outsideReason = false
	// 	this.signStatu = "成功";
	// 	this.updateSignLocationAndReason();
	// 	this.$refs.uToast.show({
	// 		type: 'success',
	// 		message: "签到成功",
	// 		iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png',
	// 		complete() {}
	// 	})
	// },
	//更新签到地点和理由
	function updateSignLocationAndReason() {
		serviceApply.planStartTime = GetDatetime();
		let partParmeter = {
			id: serviceApply.id,
			realLatitude: serviceApply.realLatitude,
			realLongitude: serviceApply.realLongitude,
			//"attribute1": this.serviceApply.attribute1,
			attribute2: Distance.value,
			startTime: serviceApply.planStartTime,
		};
		updateSlhgzresqjl(partParmeter).then((response) => {
			if (response.code == 200) {
				this.$refs.uToast.show({
					type: "success",
					message: "签到成功",
					iconUrl: "https://cdn.uviewui.com/uview/demo/toast/success.png",
					complete() {},
				});
				//更新信息-签到状态
				getSlhgzresqjl(id.value).then((response) => {
					queryParams.taskId = response.data.taskId; //将老人id保存
					serviceApply = response.data;
				});
			} else {
				this.$refs.uToast.show({
					type: "fail",
					message: "签到失败",
					complete() {},
				});
			}
		});
	}

	function handel_cell_click(item) {
		//跳转题目页，传输assignId（考试）,assignDetailId(哪张考卷)
		// this.$tab.navigateTo(
		// 	"/pages/WenJuanDiaoCha/Answer/index?assignId=" +
		// 	this.assignId +
		// 	"&assignDetailId=" +
		// 	item.name
		// );
		uni.navigateTo({
			url:"/WenJuanDiaoCha/Answer/index?assignId=" +assignId.value +"&assignDetailId=" +item.name
		})
	}

	function fetch() {
		queryParams.pageNum = queryParams.pageNum + 1;
		listAssignDetail(queryParams).then((response) => {
			DataList.value = DataList.value.concat(response.rows);
			total.value = response.total;
			// this.update_connetStatus();
		});
	}
</script>

<style scoped>
	.custom-style {
		width: 90%;
		font-weight: bolder;
		font-size: 15px;
	}

	.u-slot-title {
		display: flex;
		align-items: center;
		/* 垂直居中 */
	}

	.u-cell-text {
		margin-right: 10px;
		/* 可根据需要调整元素间的间距 */
	}

	.slot-content {
		width: 90%;
		/* 自定义宽度 */
		margin: 0 auto;
		/* 水平居中 */
	}

	.status-col {
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}

	.status-wrapper {
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}

	.submit-button {
		display: flex;
		justify-content: center;
		margin-top: 20rpx;

		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		z-index: 9999;
		/* 保证在最上层 */
	}
</style>