<template>
	<view class="container">
		<scroll-view
			class="scroll_view"
			scroll-y
			scroll-with-animation
			scroll-anchoring
			:scroll-into-view="point"
		>
			<view class="top_bg_box">
				<image mode="widthFix" :src="icon.satisfaction.ques_top_bg"></image>
				<view class="ques_introduce displayFlexCol">
					<text>{{ quesList.SubjectTitle }}</text>
					<text>{{ quesList.Remark }}</text>
				</view>
			</view>
			<view class="main_box">
				<view class="mask_form" v-if="complete"></view>
				<block v-for="(item, index) in quesList.QuestionList" :key="index">
					<view
						class="ques_item_box"
						:id="'p' + index"
						:class="item.QuestType == 'SubTitle' ? 'sub_title' : ''"
					>
						<view class="ques_title_box">
							<text class="mustQuest_tag" wx:if="{{item.MustQuest}}">*</text>
							<text v-if="item.QuestType != 'SubTitle'">{{ item.Sort }}.{{ item.Question }}</text>
							<text v-if="item.QuestType == 'SubTitle'">{{ item.Num }}、{{ item.Question }}</text>
						</view>
						<!-- 填空题 -->
						<view
							class="ques_options align_items_left displayFlexCol"
							v-if="item.QuestType == 'Input'"
						>
							<text class="input_label">{{ item.Question }}：</text>
							<view class="textarea_box">
								<textarea
									auto-height
									:data-index="index"
									:placeholder="'最多输入' + item.RuleInfo.MaxLength + '个字'"
									:maxlength="item.RuleInfo.MaxLength"
									:value="item.AnswerList"
									@blur="setVal"
								/>
							</view>
						</view>
						<!-- 矩阵填空题 -->
						<view
							class="ques_options align_items_left displayFlexCol"
							v-if="item.QuestType == 'MatrixInput'"
						>
							<block
								v-for="(childItem, childIndex) in item.MatrixQuestionList"
								:key="`MatrixInput-${index}-${childIndex}`"
							>
								<view class="matrix_input_box margin_bottom_10 displayFlexRow">
									<text>{{ childItem.Question }}：</text>
									<view class="textarea_box matrix_textarea_box">
										<textarea
											auto-height
											:data-index="index"
											:data-childindex="childIndex"
											:placeholder="'最多输入' + childItem.RuleInfo.MaxLength + '个字'"
											:maxlength="childItem.RuleInfo.MaxLength"
											:value="childItem.AnswerList"
											@input="setVal"
										/>
									</view>
								</view>
							</block>
						</view>
						<!-- 单选/多选题 -->
						<view
							class="ques_options displayFlexCol"
							v-if="item.QuestType == 'Radio' || item.QuestType == 'Checkbox'"
						>
							<block
								v-for="(childItem, childIndex) in item.QuestionItemList"
								:key="`Checkbox-${index}-${childIndex}`"
							>
								<text
									class="choice_item"
									:class="fn.answer(item, childItem.ItemId) ? 'active_option' : ''"
									:data-index="index"
									:data-childindex="childIndex"
									@click="choiceOption"
								>
									{{ childItem.ItemName }}
								</text>
							</block>
						</view>
						<!-- 选择题 -->
						<view class="ques_options displayFlexCol" v-if="item.QuestType == 'Select'">
							<picker
								class="picker_box"
								range-key="ItemName"
								:range="item.QuestionItemList"
								:data-index="index"
								:value="item.AnswerList"
								@change="bindPickerChange"
							>
								<view class="picker displayFlexRow">
									<text>{{ item.QuestionItemList[item.AnswerList].ItemName }}</text>
									<image :src="icon.satisfaction.right" mode="" />
								</view>
							</picker>
						</view>
						<!-- 矩阵单选题/矩阵多选题/矩阵量表 -->
						<view
							class="ques_options matrix_border displayFlexCol"
							v-if="
								item.QuestType == 'MatrixRadio' ||
								item.QuestType == 'MatrixCheckbox' ||
								item.QuestType == 'MatrixScale'
							"
						>
							<view class="matrix_options matrix_options_title displayFlexRow">
								<block
									v-for="(childItem, childIndex) in item.MatrixQuestionList[0].QuestionItemList"
									:key="`${item.QuestType}0-${index}-${childIndex}`"
								>
									<text
										:style="{
											width: fn.getWidth(item.MatrixQuestionList[0].QuestionItemList.length) + '%',
										}"
									>
										{{ childItem.ItemName }}
									</text>
								</block>
							</view>
							<block
								v-for="(childItem, childIndex) in item.MatrixQuestionList"
								:key="`${item.QuestType}-${index}-${childIndex}`"
							>
								<view class="matrix_icon_box displayFlexCol">
									<text
										:style="{
											width: fn.getWidth(item.MatrixQuestionList[0].QuestionItemList.length) + '%',
										}"
										>{{ childItem.Question }}</text
									>
									<view class="matrix_options displayFlexBetween">
										<block
											v-for="(sunItem, sunIndex) in childItem.QuestionItemList"
											:key="`${item.QuestType}-${index}-${childIndex}-${sunIndex}`"
										>
											<view
												class="displayFlexRow"
												:data-index="index"
												:data-childindex="childIndex"
												:data-sunindex="sunIndex"
												@click="choiceMatrixOption"
											>
												<!-- 矩阵单选/矩阵量表 -->
												<image
													:src="
														fn.answer(childItem, sunItem.ItemId)
															? icon.satisfaction.circle_active
															: icon.satisfaction.circle
													"
													mode=""
													v-if="item.QuestType == 'MatrixRadio' || item.QuestType == 'MatrixScale'"
												/>

												<!-- 矩阵多选 -->
												<image
													:src="
														fn.answer(childItem, sunItem.ItemId)
															? icon.satisfaction.checkBox_circle_active
															: icon.satisfaction.checkBox_circle
													"
													mode=""
													v-if="item.QuestType == 'MatrixCheckbox'"
												/>
											</view>
										</block>
									</view>
								</view>
							</block>
						</view>
						<!-- 上传文件题 -->
						<view class="ques_options displayFlexCol" v-if="item.QuestType == 'UploadImage'">
							<view class="img_list displayFlexRow">
								<image
									class="add_img"
									mode=""
									:src="icon.satisfaction.add"
									:data-index="index"
									@click="choiceFile"
								/>
								<block
									v-for="(imgItem, imgIndex) in item.AnswerList"
									:key="`UploadImage-${index}-${imgIndex}`"
								>
									<view class="add_img">
										<image class="item_img" :src="imgItem" mode="" />
										<image
											class="cha_img"
											:src="icon.satisfaction.cha_green"
											mode=""
											:data-index="index"
											:data-imgitem="imgItem"
											@click="closeImg"
										/>
									</view>
								</block>
							</view>
							<view class="add_img_tips p_flexStart">
								<text>限制：</text>
								<text> 仅支持图片上传、</text>
								<text>
									大小不超过{{ item.RuleInfo.FileSize }}M数量不超过{{ item.RuleInfo.FileCount }}个
								</text>
							</view>
						</view>
						<!-- 量表题 -->
						<view class="ques_options displayFlexRow" v-if="item.QuestType == 'Scale'">
							<block
								v-for="(childItem, childIndex) in item.QuestionItemList"
								:key="`Scale-${index}-${childIndex}`"
							>
								<view
									class="options_item_box displayFlexCol"
									:data-index="index"
									:data-childindex="childIndex"
									@click="choiceOption"
								>
									<text>{{ childItem.ItemName }}</text>
									<image
										:src="
											fn.answer(item, childItem.ItemId)
												? icon.satisfaction.circle_active
												: icon.satisfaction.circle
										"
										mode=""
									/>
								</view>
							</block>
						</view>
					</view>
				</block>
			</view>
		</scroll-view>

		<view class="yjfl" @click="yjfk">
			<image :src="icon.satisfaction.yjfk" alt="" style="width: 140rpx; height: 140rpx" />
			<view class="title"> 意见反馈 </view>
		</view>
		<view class="footer_box displayFlexRow">
			<text :class="complete ? 'backgroundCustom_D9' : ''" @click="submit">提交</text>
		</view>

		<!-- 是否实名弹窗 -->
		<view class="modal_wrap" v-if="showModal_Anonymous">
			<view class="modal_box">
				<view class="modal_tit">是否实名填写</view>
				<view class="modal_con">
					<view class="modal_box_b1" @click="isAnonymous(1)">实名填写</view>
					<view class="modal_box_b1" @click="isAnonymous(2)">匿名填写</view>
				</view>
			</view>
		</view>
		<!-- 是否实名弹窗 -->
		<view class="modal_wrap" v-if="showModal_User">
			<view class="modal_box">
				<view class="modal_tit">请选择答卷人</view>
				<view class="modal_con">
					<view class="modal_user_item" v-if="currentUser.memberName" @click="goSelMember">
						<view>
							<view>
								<text class="modal_t1">{{ currentUser.memberName }}</text>
								<text class="modal_t2">
									{{ currentUser.sex == 1 ? '男' : currentUser.sex == 2 ? '女' : '未知' }} |
									{{ currentUser.age }}岁
								</text>
							</view>
							<view class="modal_t3">{{ currentUser.mobile }}</view>
						</view>
						<image class="modal_user_right_img" :src="icon.satisfaction.right"></image>
					</view>
					<view class="modal_user_item" wx:else @click="goSelMember">
						<view>点击选择答卷人</view>
						<image class="modal_user_right_img" :src="icon.satisfaction.right"></image>
					</view>
					<view class="modal_btn_wrap displayFlexBetween" v-if="currentUser.memberName">
						<view class="modal_btn modal_btn1" @click="goBack">取消</view>
						<view class="modal_btn modal_btn2" @click="confirmMember">确定</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useOnLoad } from '@/hook';
import { useDomain } from '@kasite/uni-app-base';
import { mapGetters } from '@kasite/uni-app-base/store/hook';
import {
	QuerySubjectListToChannelTask_V3,
	QuerySubjectInfoById_V3,
	UploadZxFile,
	CommitAnswer_V3,
} from '../../service';
import icon from '@/utils/icon';
import { common } from '@/utils';
import fn from './fn';

const app = getApp();

let time = null;
const currentUser = ref({} as any);
const taskId = ref('');
const objType = ref('3'); // 3门诊 4住院
const quesList = ref({} as any);
const imgList = ref([]);
const point = ref('');
const complete = ref(false);
const anonymousType = ref(0);
const showModal_Anonymous = ref(false); // 是否实名填写弹窗显示
const showModal_User = ref(false); // 实名用户选择弹窗显示
let quesAnswers = reactive({
	MemberId: '',
	TaskId: '-1',
	SysAppId: 'visit',
	SubjectId: '',
	UserAgent: '',
	IP: '',
	Location: '',
	Mobile: '',
	UserName: '',
	Sex: '',
	Age: '',
	ThirdPartyId: '',
	AnswerUseTime: 0,
	PushDept: '',
	PushDeptName: '',
	BedNo: '',
	HospitalNo: '',
	CardNo: '',
	AnswerList: [],
});

const { getCurrentUser } = mapGetters({
	getCurrentUser: 'getCurrentUser',
});

const main = async (options) => {
	currentUser.value = getCurrentUser();
	const params = {
		SubjectId: options.subjectId,
		TaskId: options.taskId,
	};
	const resp = await QuerySubjectListToChannelTask_V3(params);
	if (!common.isEmpty(resp)) {
		objType.value = resp[0].GroupType;
		//匿名有3种传参 ""(空) "true" "false" 转换字符串为布尔值
		let anonymous =
			resp[0].Anonymous === 'false'
				? false
				: resp[0].Anonymous === 'true'
				? true
				: resp[0].Anonymous || '';
		// type 1实名 2:匿名 3自行选择
		anonymousType.value = anonymous === '' ? 3 : anonymous === false ? 1 : 2;
		showModal_Anonymous.value = anonymous == 3 ? true : false;
		taskId.value = options.taskId;
		quesAnswers.SubjectId = options.subjectId;
		//如果不是执行选择直接调用对应填写按钮
		if (anonymous != 3) {
			isAnonymous(anonymous);
		}
		querySubjectInfoById_V3();
		// 开始计算答卷时间
		getSec();
	} else {
		common.showModal('该任务已失效', () => {
			common.goToUrl(`/pages/business/tabbar/homePage/homePage`, { skipWay: 'reLaunch' });
		});
		return;
	}
};
/** 实名/匿名 */
const isAnonymous = (type) => {
	//实名
	if (type == 1) {
		showModal_Anonymous.value = false;
		showModal_User.value = true;
	}
	//匿名
	else {
		currentUser.value = {};
		showModal_Anonymous.value = false;
	}
};
/** 问卷详情 */
const querySubjectInfoById_V3 = async () => {
	const resp = await QuerySubjectInfoById_V3({
		SubjectId: quesAnswers.SubjectId,
	});
	if (common.isNotEmpty(resp)) {
		if (resp[0].Status != 0) {
			common.showModal('该问卷已失效', () => {
				common.navigateBack(1);
			});
			return;
		}
		if (resp[0].State != 1) {
			common.showModal('该问卷未发布', () => {
				common.navigateBack(1);
			});
			return;
		}
		// 提交答案数据模版
		quesAnswers.PushDept = resp[0].DeptId;
		quesAnswers.PushDeptName = resp[0].PushDeptName;
		resp[0].QuestionList.forEach((item, index) => {
			item.AnswerList = [];
			item.MustQuest = item.MustQuest == 'false' ? false : true;
			item.RuleInfo = item.RuleInfo != '' ? JSON.parse(item.RuleInfo) : '';
			// 多选框
			if (item.QuestType == 'Select') {
				item.AnswerList = 0;
			}
			if (common.isNotEmpty(item.MatrixQuestionList)) {
				item.MatrixQuestionList.forEach((childItem) => {
					childItem.AnswerList = [];
					childItem.RuleInfo = childItem.RuleInfo != '' ? JSON.parse(childItem.RuleInfo) : '';

					// 答案列表模版
					let answerItem = {
						Answer: [],
						Blank: index,
						QuestId: childItem.QuestId,
						QuestType: item.QuestType,
						MustQuest: item.MustQuest,
					};
					quesAnswers.AnswerList.push(answerItem);
					if (common.isNotEmpty(childItem.QuestionItemList)) {
						childItem.QuestionItemList.forEach((sunItem) => {
							sunItem.Check = false;
						});
					}
				});
			} else {
				// 答案列表模版
				let answerItem = {
					Answer: [],
					Blank: index,
					QuestId: item.QuestId,
					QuestType: item.QuestType,
					MustQuest: item.MustQuest,
				};
				quesAnswers.AnswerList.push(answerItem);
			}
		});
		resp[0].QuestionList = bySort(resp[0].QuestionList);
		quesList.value = resp[0];
		console.log(quesList.value);
	}
};
/** 计算答题时间 */
const getSec = () => {
	time = setTimeout(() => {
		let answerUseTime = quesAnswers.AnswerUseTime;
		answerUseTime++;
		quesAnswers.AnswerUseTime = answerUseTime;
		getSec();
	}, 1000);
};
/** 根据子标题排序 */
const bySort = (list: any[]) => {
	let find = 0;
	let sort = 0;
	let item = {} as any;
	for (var t = 0; t < list.length; t++) {
		item = list[t];
		//子标题
		if (item.QuestType == 'SubTitle') {
			//将子标题底下的题目从1开始排
			sort = 0;
			//判断是出现的第几个子标题
			//num是子标题的排序
			item.Num = toChinesNum(find + 1);
			find++;
		} else {
			//sort是子标题底下的排序
			item.Sort = sort + 1;
			sort++;
		}
		item.SortNum = t;
		if (common.isNotEmpty(item.QuestionItemList)) {
			item.QuestionItemList.forEach((childItem, childIndex) => {
				childItem.SortNum = childIndex;
				if (common.isNotEmpty(childItem.QuestionItem)) {
					childItem.QuestionItem.forEach((sunItem, sunIndex) => {
						sunItem.SortNum = sunIndex;
					});
				}
			});
		}
	}
	return list;
};
/** 汉字顺序 */
const toChinesNum = (num) => {
	var changeNum = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'],
		newNum = '',
		arr = num.toString().split('');
	arr[0] = parseInt(arr[0]) - 1;
	if (arr[0] == -1 && arr.length == 1) {
		return '零';
	}
	if (arr.length > 1) {
		arr[1] = parseInt(arr[1]) - 1;
		if (!arr[0]) {
			newNum = !arr[0] && arr[1] == -1 ? changeNum[9] : changeNum[9] + changeNum[arr[1]];
		} else {
			newNum = changeNum[arr[0]] + changeNum[9] + (changeNum[arr[1]] ? changeNum[arr[1]] : '');
		}
	} else {
		newNum = changeNum[arr[0]];
	}
	return newNum;
};

/** 单选/多选/量表 */
const choiceOption = (e) => {
	let index = e.currentTarget.dataset.index;
	let childIndex = e.currentTarget.dataset.childindex;
	let answerIndex = 0;
	let questionList = quesList.value.QuestionList;
	let answerList = quesAnswers.AnswerList;
	answerList.forEach((itm, ind) => {
		if (itm.QuestId == questionList[index].QuestId) {
			answerIndex = ind;
		}
	});
	// 单选/量表
	if (questionList[index].QuestType == 'Radio' || questionList[index].QuestType == 'Scale') {
		if (
			questionList[index].AnswerList[0] != questionList[index].QuestionItemList[childIndex].ItemId
		) {
			questionList[index].AnswerList = [];
			questionList[index].AnswerList.push(questionList[index].QuestionItemList[childIndex].ItemId);
		}
		answerList[answerIndex].Answer = questionList[index].QuestionItemList[childIndex].ItemId;
	}
	// 多选
	else if (questionList[index].QuestType == 'Checkbox') {
		let flag = false;
		questionList[index].AnswerList.forEach((item) => {
			if (item == questionList[index].QuestionItemList[childIndex].ItemId) {
				flag = true;
			}
		});

		if (flag) {
			questionList[index].AnswerList = questionList[index].AnswerList.filter((item) => {
				return item != questionList[index].QuestionItemList[childIndex].ItemId;
			});
			answerList[answerIndex].Answer = answerList[answerIndex].Answer.filter((fiItem) => {
				return fiItem != questionList[index].QuestionItemList[childIndex].ItemId;
			});
		} else {
			if (questionList[index].RuleInfo.MaxLength < questionList[index].AnswerList.length + 1) {
				common.showModal('最多选择' + questionList[index].RuleInfo.MaxLength + '项');
				return;
			}
			questionList[index].AnswerList.push(questionList[index].QuestionItemList[childIndex].ItemId);
			answerList[answerIndex].Answer.push(questionList[index].QuestionItemList[childIndex].ItemId);
		}
	}
	quesList.value.QuestionList = questionList;
	quesAnswers.AnswerList = answerList;
};
/** 选择题 */
const bindPickerChange = (e) => {
	let index = e.currentTarget.dataset.index;
	let val = e.detail.value;
	let questionList = quesList.value.QuestionList;
	let answerList = quesAnswers.AnswerList;
	let answerIndex = 0;
	answerList.forEach((itm, ind) => {
		if (itm.QuestId == questionList[index].QuestId) {
			answerIndex = ind;
		}
	});
	questionList[index].AnswerList = val;
	answerList[answerIndex].Answer = questionList[index].QuestionItemList[val].ItemId;
	quesList.value.QuestionList = questionList;
	quesAnswers.AnswerList = answerList;
};
/** 矩阵单选 */
const choiceMatrixOption = (e) => {
	let index = e.currentTarget.dataset.index;
	let childIndex = e.currentTarget.dataset.childindex;
	let sunIndex = e.currentTarget.dataset.sunindex;
	let questionList = quesList.value.QuestionList;
	let answerList = quesAnswers.AnswerList;
	let answerIndex = 0;
	answerList.forEach((itm, ind) => {
		if (itm.QuestId == questionList[index].MatrixQuestionList[childIndex].QuestId) {
			answerIndex = ind;
		}
	});

	// 矩阵单选/矩阵量表
	if (
		questionList[index].QuestType == 'MatrixRadio' ||
		questionList[index].QuestType == 'MatrixScale'
	) {
		if (
			questionList[index].MatrixQuestionList[childIndex].AnswerList[0] !=
			questionList[index].MatrixQuestionList[childIndex].QuestionItemList[sunIndex].ItemId
		) {
			questionList[index].MatrixQuestionList[childIndex].AnswerList = [];
			questionList[index].MatrixQuestionList[childIndex].AnswerList.push(
				questionList[index].MatrixQuestionList[childIndex].QuestionItemList[sunIndex].ItemId
			);
		}
		answerList[answerIndex].Answer =
			questionList[index].MatrixQuestionList[childIndex].QuestionItemList[sunIndex].ItemId;
	}
	// 矩阵多选
	else if (questionList[index].QuestType == 'MatrixCheckbox') {
		let flag = false;
		questionList[index].MatrixQuestionList[childIndex].AnswerList.forEach((item) => {
			if (
				item == questionList[index].MatrixQuestionList[childIndex].QuestionItemList[sunIndex].ItemId
			) {
				flag = true;
			}
		});

		if (flag) {
			questionList[index].MatrixQuestionList[childIndex].AnswerList = questionList[
				index
			].MatrixQuestionList[childIndex].AnswerList.filter((item) => {
				return (
					item !=
					questionList[index].MatrixQuestionList[childIndex].QuestionItemList[sunIndex].ItemId
				);
			});
			answerList[answerIndex].Answer = answerList[answerIndex].Answer.filter((fiItem) => {
				return (
					fiItem !=
					questionList[index].MatrixQuestionList[childIndex].QuestionItemList[sunIndex].ItemId
				);
			});
		} else {
			questionList[index].MatrixQuestionList[childIndex].AnswerList.push(
				questionList[index].MatrixQuestionList[childIndex].QuestionItemList[sunIndex].ItemId
			);
			answerList[answerIndex].Answer.push(
				questionList[index].MatrixQuestionList[childIndex].QuestionItemList[sunIndex].ItemId
			);
		}
	}
	quesList.value.QuestionList = questionList;
	quesAnswers.AnswerList = answerList;
};
/** 选择文件 */
const choiceFile = (e) => {
	let index = e.currentTarget.dataset.index;
	let questionList = quesList.value.QuestionList;
	let answerList = quesAnswers.AnswerList;
	let answerIndex = 0;
	answerList.forEach((itm, ind) => {
		if (itm.QuestId == questionList[index].QuestId) {
			answerIndex = ind;
		}
	});

	if (answerList[answerIndex].Answer.length >= questionList[index].RuleInfo.FileCount) {
		common.showModal('最多上传' + questionList[index].RuleInfo.FileCount + '张图片');
		return;
	}

	uni.chooseMedia({
		count: questionList[index].RuleInfo.FileCount,
		mediaType: ['image'],
		sourceType: ['album', 'camera'],
		sizeType: ['compressed'],
		async success(res) {
			uni.showLoading({
				title: '上传中。。。',
			});
			for (var i = 0; i < res.tempFiles.length; i++) {
				let m = 1024 * 1024;
				if (res.tempFiles[i].size < m) {
					let imgUrl = (await uploadFile(
						res.tempFiles[i].tempFilePath,
						questionList[index].RuleInfo.FileCount,
						answerList[answerIndex].Answer
					)) as string;
					if (common.isNotEmpty(imgUrl)) {
						imgUrl =
							imgUrl.indexOf('http') > -1 ? imgUrl : useDomain() + imgUrl.replace(/\\/g, '/');
						answerList[answerIndex].Answer.push(imgUrl);
						questionList[index].AnswerList = answerList[answerIndex].Answer;
						quesList.value.QuestionList = questionList;
						quesAnswers.AnswerList = answerList;
						if (res.tempFiles.length - 1 == i) {
							uni.hideLoading();
						}
					}
				} else {
					uni.hideLoading();
					common.showModal('文件不得大于' + questionList[index].RuleInfo.FileSize + 'M');
					return;
				}
			}
		},
	});
};
/** 上传文件 */
const uploadFile = (imgItem, fileCount, imgList) => {
	return new Promise((resolve, reject) => {
		if (imgList.length >= fileCount) {
			uni.hideLoading();
			common.showModal('最多上传' + fileCount + '张图片');
			return;
		}
		// 将图片上传至服务器
		uni.uploadFile({
			url: UploadZxFile,
			filePath: imgItem,
			name: 'newsFile',
			formData: {
				user: 'test',
			},
			header: {
				token: uni.getStorageSync('token'),
			},
			data: {},
			success(res) {
				const data = JSON.parse(res.data);
				if (data.RespCode == '10000') {
					resolve(data.url);
				} else {
					common.showModal(data.msg);
				}
			},
		});
	});
};
/** 删除图片 */
const closeImg = (e) => {
	let index = e.currentTarget.dataset.index;
	let imgItem = e.currentTarget.dataset.imgitem;
	let questionList = quesList.value.QuestionList;
	let answerList = quesAnswers.AnswerList;
	let answerIndex = 0;
	answerList.forEach((itm, ind) => {
		if (itm.QuestId == questionList[index].QuestId) {
			answerIndex = ind;
		}
	});
	answerList[answerIndex].Answer = answerList[answerIndex].Answer.filter((item) => {
		return item != imgItem;
	});

	questionList[index].AnswerList = answerList[answerIndex].Answer;
	quesList.value.QuestionList = questionList;
	quesAnswers.AnswerList = answerList;
};
/** 获取input值 */
const setVal = (e) => {
	let index = e.currentTarget.dataset.index;
	let childIndex = e.currentTarget.dataset.childindex;
	let questionList = quesList.value.QuestionList;
	let answerList = quesAnswers.AnswerList;
	let answerIndex = 0;
	// 矩阵填空题
	if (questionList[index].QuestType == 'MatrixInput') {
		if (
			questionList[index].MatrixQuestionList[childIndex].AnswerList.length ==
			questionList[index].MatrixQuestionList[childIndex].RuleInfo.MaxLength
		) {
			common.showToast(
				'最多输入' + questionList[index].MatrixQuestionList[childIndex].RuleInfo.MaxLength + '个字'
			);
			return;
		}
		answerList.forEach((itm, ind) => {
			if (itm.QuestId == questionList[index].MatrixQuestionList[childIndex].QuestId) {
				answerIndex = ind;
			}
		});
		questionList[index].MatrixQuestionList[childIndex].AnswerList = e.detail.value;
	}
	// 填空题
	else {
		if (questionList[index].RuleInfo.DataType != '无') {
			let dataTypeOptions = questionList[index].RuleInfo.DataTypeOptions;
			for (var i = 0; i < dataTypeOptions.length; i++) {
				if (questionList[index].RuleInfo.DataType == dataTypeOptions[i].Value) {
					const regRule = dataTypeOptions[i].Rule;
					let reg = null;
					if (regRule.startsWith('/') && regRule.endsWith('/')) {
						reg = new RegExp(regRule.slice(1, -1));
					} else {
						reg = new RegExp(regRule);
					}
					if (!reg.test(e.detail.value)) {
						common.showModal('请输入' + dataTypeOptions[i].Text);
						questionList[index].AnswerList = '';
						answerList[answerIndex].Answer = '';

						this.setData({
							'quesList.QuestionList': questionList,
							'quesAnswers.AnswerList': answerList,
						});
						return;
					}
				}
			}
		}

		if (questionList[index].AnswerList.length == questionList[index].RuleInfo.MaxLength) {
			common.showToast('最多输入' + questionList[index].RuleInfo.MaxLength + '个字');
			return;
		}
		answerList.forEach((itm, ind) => {
			if (itm.QuestId == questionList[index].QuestId) {
				answerIndex = ind;
			}
		});
		questionList[index].AnswerList = e.detail.value;
	}

	answerList[answerIndex].Answer = e.detail.value;
	quesList.value.QuestionList = questionList;
	quesAnswers.AnswerList = answerList;
};

/** 提交 */
const submit = async () => {
	uni.showLoading();
	await common.sleep(1000);
	if (complete.value) return;
	const answers = { ...quesAnswers } as any;
	for (var i = 0; i < answers.AnswerList.length; i++) {
		let item = answers.AnswerList[i];
		if (item.MustQuest && common.isEmpty(item.Answer)) {
			common.showToast('存在未填写的问卷');
			point.value = 'p' + item.Blank;
			return;
		}
	}
	answers.AnswerList.forEach((item) => {
		if (typeof item.Answer == 'object') {
			item.Answer = item.Answer.join();
		}
	});
	answers.AnswerList = JSON.stringify(quesAnswers.AnswerList);
	quesAnswers.IP = (await getIP()).cip;
	quesAnswers.Location = (await getIP()).cname;
	quesAnswers.UserAgent = app.globalData.smallPro_systemInfo;
	quesAnswers.Mobile = currentUser.value.mobile;
	quesAnswers.UserName = currentUser.value.memberName;
	quesAnswers.MemberId = currentUser.value.memberId;
	quesAnswers.Sex = currentUser.value.sex;
	quesAnswers.Age = currentUser.value.age;
	quesAnswers.ThirdPartyId = currentUser.value.memberId || uni.getStorageSync('openid');
	quesAnswers.BedNo = '';
	quesAnswers.HospitalNo = objType.value == '4' ? currentUser.value.cardNo : '';
	quesAnswers.CardNo = objType.value == '3' ? currentUser.value.cardNo : '';
	quesAnswers.TaskId = taskId.value;
	let res = await CommitAnswer_V3(quesAnswers);
	clearTimeout(time);
	if (common.isNotEmpty(res)) {
		common.showModal('提交成功！', () => {
			common.navigateBack(1);
		});
	}
};
/** 获取IP */
const getIP = () => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: 'https://pv.sohu.com/cityjson?ie=utf-8',
			success: (res: any) => {
				const result = res.data.substring(res.data.indexOf('{'), res.data.lastIndexOf('}') + 1);
				const obj = JSON.parse(result);
				resolve(obj);
			},
		});
	}) as Promise<any>;
};

const goBack = () => {
	uni.navigateBack({
		delta: 1,
	});
};
const yjfk = () => {};
const goSelMember = () => {};
const confirmMember = () => {};

useOnLoad((options) => {
	main(options);
});
</script>

<style lang="scss" scoped>
.align_items_left {
	align-items: flex-start;
}

.active_option {
	background: #18ba89 !important;
	color: white !important;
}

.mask_form {
	width: 100%;
	height: 100%;
	position: absolute;
	top: 0;
	left: 0;
	z-index: 100;
}

.container {
	overflow: hidden;
}

.scroll_view {
	height: 100%;
}

.top_bg_box {
	position: relative;

	image {
		width: 100%;
		height: 456rpx;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 1;
	}
	.ques_introduce {
		padding: 46rpx 52rpx 0 52rpx;
		box-sizing: border-box;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 2;
		text:nth-child(1) {
			font-size: 36rpx;
			font-weight: bold;
			color: white;
			margin-bottom: 20rpx;
		}
		text:nth-child(2) {
			line-height: 45rpx;
			font-size: 28rpx;
			color: white;
		}
	}
}

.main_box {
	padding: 470rpx 30rpx 190rpx 30rpx;
	box-sizing: border-box;
	position: relative;
	z-index: 2;
}

.ques_item_box {
	padding: 30rpx;
	box-sizing: border-box;
	background: white;
	border-radius: 20rpx;
	margin-bottom: 32rpx;

	> .ques_title_box > text {
		line-height: 50rpx;
		font-size: 36rpx;
		font-weight: bold;
		color: #1c1c1c;
	}
	.mustQuest_tag {
		color: #dc2828;
	}
}

.ques_options {
	margin-top: 34rpx;
}

.choice_item {
	width: 100%;
	line-height: 80rpx;
	font-size: 30rpx;
	color: #686868;
	text-align: center;
	margin-bottom: 16rpx;
	border-radius: 10rpx;
	background: #f8f8fa;

	&:last-child {
		margin-bottom: 0;
	}
}

.input_label {
	line-height: 40rpx;
	font-size: 32rpx;
	color: #474747;
}

.textarea_box {
	width: 100%;
	padding: 20rpx;
	box-sizing: border-box;
	border-radius: 10rpx;
	background: #f8f8fa;
	margin-top: 22rpx;
	textarea {
		width: 100%;
	}
}

.matrix_textarea_box {
	width: 70%;
}

.picker_box {
	width: 100%;
}

.picker {
	width: 100%;
	height: 80rpx;
	padding: 22rpx;
	box-sizing: border-box;
	background: #f9f9f9;
	border-radius: 20rpx;
	justify-content: space-between;

	text {
		white-space: nowrap;
		font-size: 28rpx;
		color: #686868;
	}
	image {
		width: 12rpx;
		height: 24rpx;
	}
}

.matrix_options {
	width: 100%;
	margin-bottom: 34rpx;
	justify-content: space-between;

	text {
		font-size: 30rpx;
		color: #1c1c1c;
		text-align: center;
		padding: 20rpx;
		box-sizing: border-box;
		word-wrap: break-word;
		word-break: break-all;
	}
}

.matrix_border {
	border: 1px solid #f0f0f0;
}

.matrix_options_title {
	background: #f5f5f5;
}

.matrix_icon_box {
	width: 100%;
	align-items: flex-start;
	text {
		font-size: 30rpx;
		color: #1c1c1c;
		margin-bottom: 36rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
	}
	image {
		width: 40rpx;
		height: 40rpx;
	}
}

.sub_title {
	background: none;
}

.img_list {
	width: 100%;
	margin-bottom: 24rpx;
	justify-content: flex-start;
	flex-wrap: wrap;
	.item_img {
		width: 100%;
		height: 100%;
	}
}

.add_img {
	width: 32%;
	height: 200rpx;
	margin-right: 2%;
	margin-bottom: 3%;
	position: relative;
	&:nth-child(3n) {
		margin-right: 0;
	}
}

.add_img_tips {
	width: 100%;
	text {
		font-size: 30rpx;
		color: #474747;
	}
}

.cha_img {
	width: 50rpx;
	height: 50rpx;
	position: absolute;
	top: -15rpx;
	right: -5rpx;
}

.options_item_box {
	width: 100%;
	padding: 0 10rpx;
	box-sizing: border-box;
	margin-bottom: 20rpx;
	justify-content: space-between;

	text {
		font-size: 28rpx;
		color: #686868;
		word-wrap: break-word;
		word-break: break-all;
	}
	image {
		width: 40rpx;
		height: 40rpx;
		margin: 20rpx 0;
	}
}

.matrix_input_box {
	width: 100%;

	text {
		width: 30%;
		white-space: nowrap;
	}
	input {
		width: 70%;
	}
}

.footer_box {
	width: 100%;
	padding: 30rpx 30rpx 60rpx 30rpx;
	box-sizing: border-box;
	background: white;
	position: fixed;
	bottom: 0;
	left: 0;
	z-index: 10;

	text {
		width: 100%;
		line-height: 88rpx;
		font-size: 36rpx;
		color: white;
		text-align: center;
		border-radius: 88rpx;
		background: #18ba89;
		display: block;
	}
}

.modal_wrap {
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.6);
	position: fixed;
	left: 0;
	top: 0;
	z-index: 99;
	display: flex;
	align-items: center;
	justify-content: center;
}
.modal_box {
	width: 600rpx;
	max-height: 600rpx;
	background-color: #fff;
	border-radius: 5px;
	padding: 40rpx 40rpx 60rpx;
}
.modal_tit {
	text-align: center;
	font-size: 30rpx;
}
.modal_box_b1 {
	background-color: #f2f2f2;
	border-radius: 5px;
	line-height: 80rpx;
	margin-top: 40rpx;
	/* padding-left: 40rpx; */
	text-align: center;
}
.modal_user_item {
	background: #f2f2f2;
	padding: 30rpx;
	margin-top: 40rpx;
	position: relative;
}
.modal_user_right_img {
	width: 12rpx;
	height: 21rpx;
	position: absolute;
	right: 30rpx;
	top: 0;
	bottom: 0;
	margin: auto 0;
}
.modal_t1 {
	font-weight: bold;
	display: inline-block;
	margin-right: 20rpx;
	font-size: 32rpx;
}
.modal_t3 {
	margin-top: 20rpx;
}
.modal_btn {
	width: 46%;
	line-height: 75rpx;
	text-align: center;
	border-radius: 50rpx;
	margin-top: 40rpx;
}
.modal_btn1 {
	background: #aaaaaa;
	color: #fff;
}
.modal_btn2 {
	background: #61c88f;
	color: #fff;
}
.yjfl {
	position: fixed;
	bottom: 340rpx;
	right: 0;
	z-index: 100;
	width: 160rpx;
	text-align: center;

	.title {
		color: #fff;
		position: absolute;
		bottom: 10rpx;
		right: 4rpx;
		width: 100%;
		text-align: center;
		font-size: 24rpx;
	}
}
</style>
