<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"
						v-if="!isQuestionHidden(item)"
						:class="item.QuestType == 'SubTitle' ? 'sub_title' : ''"
					>
						<view class="ques_title_box">
							<text class="mustQuest_tag" v-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 displayFlexCol"
							v-if="item.QuestType == 'SubTitle' && item.HasScaleInSubtitle"
						>
							<block
								v-for="(childItem, childIndex) in subtitleSatisfactionOptions"
								:key="`SubTitleSatisfaction-${index}-${childIndex}`"
							>
								<text
									class="choice_item"
									:class="
										isSubtitleSatisfactionActive(item.SubTitleIndex, childIndex) ? 'active_option' : ''
									"
									:data-subtitleindex="item.SubTitleIndex"
									:data-childindex="childIndex"
									@click="choiceSubtitleSatisfaction"
								>
									{{ childItem }}
								</text>
							</block>
						</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" v-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,
	QuerySample_V3,
	QueryMemberByCard_V3,
} from '../../service';
import icon from '@/utils/icon';
import { common, throttle } 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 subtitleSatisfactionOptions = ['非常满意', '比较满意', '一般', '不太满意', '很不满意'];
const subtitleSatisfaction = reactive({} as Record<string, number | null>);
const subtitleHiddenQuestionTypes = ['Radio', 'Scale', 'Checkbox'];
const anonymousType = ref(0);
const showModal_Anonymous = ref(false); // 是否实名填写弹窗显示
const showModal_User = ref(false); // 实名用户选择弹窗显示
const pageParams = reactive({
	cardNo: '',
	cardType: '',
  sampleId: '',
});
let quesAnswers = reactive({
	MemberId: '',
	TaskId: '-1',
	SysAppId: 'visit',
	SubjectId: '',
	UserAgent: '',
	IP: '',
	Location: '',
	Mobile: '',
	UserName: '',
	Sex: '',
	Age: '',
	IdCard: '',
	ThirdPartyId: '',
	AnswerUseTime: 0,
	PushDept: '',
	PushDeptName: '',
	BedNo: '',
	HospitalNo: '',
	CardNo: '',
	CardType: '',
  SampleId: '',
	AnswerList: [],
});

let queryPatient = reactive({
	cardNo: '',
	cardType: ''
});

const getAgeByBirthDate = (birthDate = '') => {
	const birth = `${birthDate}`.replace(/\D/g, '').slice(0, 8);
	if (!/^\d{8}$/.test(birth)) return '';
	const year = Number(birth.slice(0, 4));
	const month = Number(birth.slice(4, 6));
	const day = Number(birth.slice(6, 8));
	const date = new Date(year, month - 1, day);
	if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) return '';
	const today = new Date();
	let age = today.getFullYear() - year;
	if (today.getMonth() + 1 < month || (today.getMonth() + 1 === month && today.getDate() < day)) {
		age--;
	}
	return age >= 0 ? `${age}` : '';
};

const getPatientInfoByIdCard = (idCard = '') => {
	const card = `${idCard}`.trim();
	if (!/^\d{17}[\dXx]$/.test(card)) return { sex: '', age: '' };
	const factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
	const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
	const sum = factors.reduce((total, factor, index) => total + Number(card[index]) * factor, 0);
	if (checkCodes[sum % 11] !== card[17].toUpperCase()) return { sex: '', age: '' };
	const birth = card.slice(6, 14);
	const sexCode = Number(card.slice(16, 17));
	const age = getAgeByBirthDate(birth);
	if (!age) return { sex: '', age: '' };
	return {
		sex: sexCode % 2 === 1 ? '1' : '2',
		age,
	};
};

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

const main = async (options) => {
	currentUser.value = getCurrentUser();
	pageParams.cardNo = options.cardno || options.cardNo || '';
	pageParams.cardType = options.cardtype || options.cardType || '';
	pageParams.sampleId = options.sampleId || options.SampleId || '';
	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(anonymousType.value);
		}
		await querySubjectInfoById_V3();
		// 查询样本和答案
		// await querySample_V3();
		// 开始计算答卷时间
		getSec();
		
		if(options?.type == "sms_myddc") {
			currentUser.value.cardNo = pageParams.cardNo
			currentUser.value.cardType = pageParams.cardType
			showModal_Anonymous.value = false
			showModal_User.value = false
		}
	} 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];
	}
};

/** 查询样本和答案 */
const querySample_V3 = async () => {
	const resp = await QuerySample_V3({
		SubjectId: quesAnswers.SubjectId,
		IsGetAnswer: true,
		ThirdPartyId: currentUser.MemberId,
		State: 1
	});
	if (common.isNotEmpty(resp)) {
		quesList.value.QuestionList.forEach((item) => {
		  resp[0].AnswerList.forEach((childItem) => {
		    if(item.QuestId == childItem.QuestId) {
		      if(item.QuestType == "Input") {
		        item.AnswerList = childItem.Answer
		      }
		      
		      if(item.QuestType == "UploadImage") {
		        item.AnswerList = childItem.Answer.split(",")
		      }
		      
		      if(common.isNotEmpty(item.QuestionItemList)) {
		        if(item.QuestType == "Select"){
		          item.QuestionItemList.forEach((sunItem,sunIndex) => {
		            if(sunItem.ItemId == childItem.Answer) {
		              item.AnswerList = sunIndex
		            }
		          })
		        }else {
		          item.AnswerList = childItem.Answer.split(",")
		        }
		      }
		    }
	
		      
		    if(common.isNotEmpty(item.MatrixQuestionList)) {
		      item.MatrixQuestionList.forEach((sunItem) => {
		        if(sunItem.QuestId == childItem.QuestId) {
		          if(sunItem.QuestType == "MatrixInput") {
		            sunItem.AnswerList = childItem.Answer
		          }
		          if(sunItem.QuestType == "MatrixCheckbox" || sunItem.QuestType == "MatrixRadio" || sunItem.QuestType == "MatrixScale") {
		            sunItem.AnswerList = childItem.Answer.split(",")
		          }
		        }
		      })
		    }
		  })
		})
		complete.value = true;
	}
}

/** 计算答题时间 */
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 currentSubTitleIndex = -1;
	let currentSubTitleItem = null as any;
	let item = {} as any;
	for (var t = 0; t < list.length; t++) {
		item = list[t];
		//子标题
		if (item.QuestType == 'SubTitle') {
			//将子标题底下的题目从1开始排
			sort = 0;
			//判断是出现的第几个子标题
			//num是子标题的排序
			item.SubTitleIndex = find;
			item.HasScaleInSubtitle = false;
			currentSubTitleIndex = find;
			currentSubTitleItem = item;
			item.Num = toChinesNum(find + 1);
			find++;
		} else {
			//sort是子标题底下的排序
			item.SubTitleIndex = currentSubTitleIndex;
			item.Sort = sort + 1;
			sort++;
			if (isSubtitleHiddenQuestion(item) && currentSubTitleItem) {
				currentSubTitleItem.HasScaleInSubtitle = true;
			}
		}
		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 isSubtitleScaleExpanded = (subtitleIndex) => {
	return Number(subtitleSatisfaction[subtitleIndex]) > 0;
};

const isSubtitleSatisfactionActive = (subtitleIndex, childIndex) => {
	return Number(subtitleSatisfaction[subtitleIndex]) === Number(childIndex);
};

const isSubtitleHiddenQuestion = (item) => {
	return subtitleHiddenQuestionTypes.includes(item?.QuestType);
};

const isQuestionHidden = (item) => {
	return isSubtitleHiddenQuestion(item) && item.SubTitleIndex > -1 && !isSubtitleScaleExpanded(item.SubTitleIndex);
};

const getAnswerIndex = (answerList, questId) => {
	let answerIndex = -1;
	answerList.forEach((item, index) => {
		if (item.QuestId == questId) {
			answerIndex = index;
		}
	});
	return answerIndex;
};

const setSingleQuestionAnswer = (question, answerList, childIndex) => {
	if (!question?.QuestionItemList?.[childIndex]) return;
	const answerIndex = getAnswerIndex(answerList, question.QuestId);
	const answer = question.QuestionItemList[childIndex].ItemId;
	if (question.QuestType == 'Checkbox' && !question.MustQuest) {
		question.AnswerList = [];
		if (answerIndex > -1) {
			answerList[answerIndex].Answer = [];
		}
		return;
	}
	question.AnswerList = [answer];
	if (answerIndex > -1) {
		answerList[answerIndex].Answer = question.QuestType == 'Checkbox' ? [answer] : answer;
	}
};

const choiceSubtitleSatisfaction = (e) => {
	const subtitleIndex = Number(e.currentTarget.dataset.subtitleindex);
	const childIndex = Number(e.currentTarget.dataset.childindex);
	const questionList = quesList.value.QuestionList;
	const answerList = quesAnswers.AnswerList;
	subtitleSatisfaction[subtitleIndex] = childIndex;

	if (childIndex == 0) {
		questionList.forEach((item) => {
			if (item.SubTitleIndex == subtitleIndex && isSubtitleHiddenQuestion(item)) {
				setSingleQuestionAnswer(item, answerList, 0);
			}
		});
	}

	quesList.value.QuestionList = questionList;
	quesAnswers.AnswerList = answerList;
};

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.chooseImage({
		count: questionList[index].RuleInfo.FileCount,
		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.tempFilePaths[i],
						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 validateSubtitleSatisfaction = () => {
	const questionList = quesList.value.QuestionList || [];
	for (var i = 0; i < questionList.length; i++) {
		const item = questionList[i];
		if (
			item.QuestType == 'SubTitle' &&
			item.HasScaleInSubtitle &&
			subtitleSatisfaction[item.SubTitleIndex] == null
		) {
			common.showToast('存在未填写的问卷');
			point.value = 'p' + i;
			return false;
		}
	}
	return true;
};

const submit = () => {
	throttle(async () => {
		await common.sleep(1000);
		if (complete.value) return;
		if (!validateSubtitleSatisfaction()) return;
		uni.showLoading();
		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();
			}
		});
		
		const cardNo = pageParams.cardNo || currentUser.value?.cardNo || '';
		const cardType = pageParams.cardType || currentUser.value?.cardType || '';
		let mobile = currentUser.value?.mobile ?? '';
		let memberName = currentUser.value?.memberName ?? '';
		let sex = currentUser.value?.sex ?? '';
		let age = currentUser.value?.age ?? '';
		let idCard = currentUser.value?.idCard ?? currentUser.value?.certNum ?? '';
		let memberId = currentUser.value?.MemberId ?? currentUser.value?.memberId ?? cardNo ?? '';

		queryPatient.cardNo = cardNo;
		queryPatient.cardType = cardType;
		let patientInfoRes = await QueryMemberByCard_V3(queryPatient);
		let patientInfo = patientInfoRes.resData;
		if (!patientInfo) {
		  uni.hideLoading();
		  return;
		}

		if (patientInfo.RespCode === '10000' && patientInfo.Data && patientInfo.Data.length > 0) {
		  const patient = patientInfo.Data[0];
		  const patientIdCard = patient.idCard || patient.idcard || patient.certNum || '';
		  const patientInfoByIdCard = getPatientInfoByIdCard(patientIdCard);
		  mobile = patient.mobile || mobile;
		  memberName = patient.memberName || memberName;
		  sex = patient.sex || patientInfoByIdCard.sex || sex;
		  age = currentUser.value?.age || getAgeByBirthDate(patient.birthDate) || patientInfoByIdCard.age || age;
		  idCard = patientIdCard || idCard;
		  memberId = patient.hisMemberId || patient.memberId || memberId;
		}

		answers.AnswerList = JSON.stringify(quesAnswers.AnswerList);

		// quesAnswers.IP = (await getIP()).cip;
		// quesAnswers.Location = (await getIP()).cname;
		quesAnswers.UserAgent = app.globalData.smallPro_systemInfo;
		quesAnswers.Mobile = mobile;
		quesAnswers.UserName = memberName;
		quesAnswers.MemberId = memberId;
		quesAnswers.Sex = sex;
		quesAnswers.Age = age;
		quesAnswers.IdCard = idCard;
		quesAnswers.ThirdPartyId = memberId || uni.getStorageSync('openid');
		quesAnswers.BedNo = '';
		quesAnswers.HospitalNo = objType.value == '4' ? cardNo : '';
		quesAnswers.CardNo = objType.value == '3' ? cardNo : '';
		quesAnswers.TaskId = taskId.value;
		quesAnswers.CardType = objType.value == '3' ? cardType : '';
		quesAnswers.SampleId = pageParams.sampleId;
		
		let res = await CommitAnswer_V3(quesAnswers);
		clearTimeout(time);
		if (common.isNotEmpty(res)) {
			common.showModal('提交成功！', () => {
				common.navigateBack(1);
			});
		}
	
	}, 5 * 1000);
};
/** 获取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>
