// miniprogram/pages/testSAS/testSAS.js
// const db = wx.cloud.database()
const baseUrl = "https://fare.somnisix.top/";
const authorization = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6Ijk5YzI3MjI2LTdkOWQtNDhiOC1hYjlhLWM4YjVjYWZiZGNkNyIsInVzZXJuYW1lIjoiYWRtaW4ifQ.zITQOINFkHs19_1RAgHS4I9YMaVxVq0Dsn3t6r_K7rv3rXvJy0sMtodejIMi_PNa_m4uQYxnU-6k3wC2LZht_Q";
const api = "system/questionInvest";
const qnaire = require("./data.js")
var ans = new Array(24)
var ansJson = []
Page({
	data: {
		qnaire: [],
		activeIcon: "/subpages/icons/ic_selected_radio.svg",
		normalIcon: "/subpages/icons/ic_radio.svg",
		activeColor: "color:#0BC3AA;",
		normalColor: "color:#666666;",
		showDateDialog: false,
		currentDate: "",
		currentDateItem: null,
		answerJson: [],
		columns: [[], []],
		BMI: null, 
		mInputId:"",
		weight: 0,
		height: 0,
		promptTextMessageFlag: false,//结果弹窗
		isPrivacyAgreed: false, // 隐私条款是否勾选  
		privacyDetailShow: false,// 隐私条款弹出页是否显示  
		changeValue: '',//
		comScore: 0,
		comScoreStatus: '', 
		comScoreIndex:0,
		ratingResultsList: [{
			title: "非常好",
			icon: "/subpages/icons/ic_triangle_down_1.svg",
			color: "#70B3FE"
		}, {
			title: "良好",
			icon: "/subpages/icons/ic_triangle_down_2.svg",
			color: "#68D89E"
		}, {
			title: "一般",
			icon: "/subpages/icons/ic_triangle_down_3.svg",
			color: "#FFA95A"
		}, {
			title: "差",
			icon: "/subpages/icons/ic_triangle_down_4.svg",
			color: "#FC726E"
		}],
		formatter(type, value) {
			if (type === 'hour') {
				return `${value}时`;
			}
			if (type === 'minute') {
				return `${value}分`;
			}
			return value;
		},
	},
	onOpenDateDialog(event) {
		const item = event.currentTarget.dataset.item;
		const value = item.value || "";
		this.setData({ currentDateItem: item, currentDate: value, showDateDialog: true });
	},
	onCloseDateDialog() {
		this.setData({ showDateDialog: false, currentDateItem: null });
	},
	onCloseResultsDialog() {
		this.setData({ promptTextMessageFlag: false });
	},
	onDateInput(event) {
		const item = this.data.currentDateItem;
		if (!item) {
			return
		}
		let oldJsonList = this.data.qnaire;

		for (let i = 0; i < oldJsonList.length; i++) {
			const element = oldJsonList[i];
			if (element.num == item.num) {
				element['value'] = event.detail;
				break;
			}
		}

		this.setData({
			qnaire: oldJsonList
		});
		this.onCloseDateDialog()
	},
	onChangeInput(event) {
		const item = event.currentTarget.dataset.item
		// console.log(item);

		let oldJsonList = this.data.qnaire;

		for (let i = 0; i < oldJsonList.length; i++) {
			const element = oldJsonList[i];
			if (element.num == item.num) {
				element['questionValue'] = event.detail;
				break;
			}
		}

		this.setData({
			qnaire: oldJsonList
		});
	},
	onChangePrivacy(event) {
		const check = event.detail;

		this.setData({
			checkedPrivacy: check
		});

	},
	onChangeRadio(event) {
		const item = event.currentTarget.dataset.item
		// console.log(item);

		let oldJsonList = this.data.qnaire;

		for (let i = 0; i < oldJsonList.length; i++) {
			const element = oldJsonList[i];
			if (element.num == item.num) {
				element['value'] = event.detail;
				break;
			}
		}

		this.setData({
			qnaire: oldJsonList
		});

	},
	handleTouchMove: function () {
		return false; // 阻止手动滑动  
	},
	hideModal: function () {
		this.setData({
			privacyDetailShow: false
		});
	},

	showPrivacyDetail: function () {
		this.setData({
			privacyDetailShow: true
		});
		// 这里可以添加代码来显示隐私条款弹出页，比如使用 wx.showModal 或自定义组件  
	},
	hidePrivacyPolicy() {
		this.setData({
			privacyDetailShow: false
		});
	},
	handleInputChange: function (e) {
		this.setData({
			height: e.detail.value
		});
		if (this.data.id == 1) {
			this.setData({
				weight: e.detail.value
			});
		}
		if (this.data.id == 3) {
			this.setData({
				weight: e.detail.value
			});
			if (this.data.weight >= 0 || this.data.height >= 0) {
				var bmi = this.data.weight / (this.data.height * this.data.height);
				this.setData({
					BMI: bmi
				});
			}
		}
	},
	radioChange: function (e) {
		console.log(e.detail.value)
		this.setData({
			changeValue: e.detail.value
		});
	},

	calculateTotalHours: function (hoursInput, minutesInput) {

		// 获取小时和分钟的值，如果为空或不是数字，则设置为0  
		let hours = parseFloat(hoursInput.value) || 0;
		let minutes = parseFloat(minutesInput.value) || 0;

		// 将分钟转换为小时的小数部分  
		// let minutesInHours = minutes / 60;  

		// 计算总时间（小时）  
		// let totalHours = hours + minutesInHours;  

		// 显示结果  
		// document.getElementById('result').textContent = `总时间: ${totalHours.toFixed(2)} 小时`;  
		// return totalHours.toFixed(2);
		return hours * 60 + minutes;
	},

	formSubmit: function () {
		if (!this.data.checkedPrivacy) {
			wx.showToast({
				icon: "none",
				title: "请先阅读并同意《舒眠调查问卷隐私条款》"
			})
			return;
		}
		var finish = true;
		var _this = this;
		let oldJsonList = _this.data.qnaire;
		var mInputId = "";
		for (let i = 0; i < oldJsonList.length; i++) {
			const element = oldJsonList[i];
			if (!element.value) {
				finish = false;
				console.log("未完成的：", element.num);
				mInputId = "item" + element.num;
				wx.showModal({
					title: '无法提交',
					content: '您还有部分题目未完成，请检查后重新提交',
					showCancel: false,
					confirmColor: '#0BC3AA',
					confirmText: "好的",
					success(res) {
						_this.setData({
							mInputId: mInputId
						})
					}
				})
				return;
			} else {
				// if (element.type == "radio&input" && !element.questionValue) {
				// 	finish = false;
				// }
			}
			
		}
		if (finish == false) {
			wx.showModal({
				title: '无法提交',
				content: '您还有部分题目未完成，请检查后重新提交',
				showCancel: false,
				confirmColor: '#0BC3AA',
				confirmText: "好的",
				success(res) {
					_this.setData({
						mInputId: mInputId
					})
				}
			})
		} else {
			wx.showLoading({
				title: '加载中',
			})
			setTimeout(function () {
				wx.hideLoading({
					success(res) {
						_this.answer2db(oldJsonList);
					}
				})
			}, 2000)
		}
	},

	answer2db: function (answerJson) {
		// db.collection('SAS').add({
		//   data: {
		//     answer: this.data.answer
		//   },
		//   success (res) {
		//     console.log(res._id);
		//   },
		//   fail (res) {
		//     wx.showToast({
		//       icon: 'none',
		//       title: '新增记录失败'
		//     })
		//     console.error('[数据库] [新增记录] 失败：', err)
		//   }
		// })
		console.log('answerJson=' + JSON.stringify(answerJson))
		let totalAllTemp = 0;
		let value1 = answerJson[0].value;
		let value2 = answerJson[1].value;
		let value3 = answerJson[2].value;
		let value4 = answerJson[3].value;
		let value5a = answerJson[4].value;
		let value5b = answerJson[5].value;
		let value5c = answerJson[6].value;
		let value5d = answerJson[7].value;
		let value5e = answerJson[8].value;
		let value5f = answerJson[9].value;
		let value5g = answerJson[10].value;
		let value5h = answerJson[11].value;
		let value5i = answerJson[12].value;
		let value5j = answerJson[13].value;
		let value6 = answerJson[14].value;
		let value7 = answerJson[15].value;
		let value8 = answerJson[16].value;
		let value9 = answerJson[17].value;
		let value10 = answerJson[18].value;
		let value11 = answerJson[19].value;
		let value12 = answerJson[20].value;
		let value13 = answerJson[21].value;
		let value14 = answerJson[22].value;
		let value15 = answerJson[23].value;

		//计算规则  https://mp.weixin.qq.com/s/QyTzuPoNErMjc2KcA1M61g
		let comA = 0;//条目6
		let comB = 0;
		let comB1 = 0;
		let comC = 0;
		let comD = 0;
		let comE = 0;
		let comF = 0;
		let comG = 0;

		comA = this.resultABCD(value6);
		comB1 = this.resultABCD(value2) + this.resultABCD(value5a);
		console.log("comB1=" + comB1);
		if (comB1 == 0) {
			comB = 0;
		} else if (comB1 >= 1 && comB1 <= 2) {
			comB = 1;
		} else if (comB1 >= 3 && comB1 <= 4) {
			comB = 2;
		} else if (comB1 >= 5 && comB1 <= 6) {
			comB = 3;
		}
		let value41 = parseInt((value4.split(':')[0]), 10) || 0;
		let value42 = parseInt((value4.split(':')[1]), 10) || 0;
		let value43 = value41 * 60 + value42
		console.log("value43=" + value43);
		if (value43 > 420) {
			comC = 0;
		} else if (value43 >= 360 && value43 <= 420) {
			comC = 1;
		} else if (value43 >= 300 && value43 < 360) {
			comC = 2;
		} else if (value43 < 300) {
			comC = 3;
		}


		let datediff = this.calculateTimeDifference(value1, value3);
		console.log("datediff=" + datediff);
		let sleepRate = datediff ? ((value43 / datediff) * 100) : 0;
		console.log("sleepRate=" + sleepRate);
		if (sleepRate >= 85) {
			comD = 0;
		} else if (sleepRate >= 75 && sleepRate <= 84) {
			comD = 1;
		} else if (sleepRate >= 65 && sleepRate < 74) {
			comD = 2;
		} else if (sleepRate < 65) {
			comD = 3;
		}

		let value5All = this.resultABCD(value5b)
			+ this.resultABCD(value5c)
			+ this.resultABCD(value5d)
			+ this.resultABCD(value5e)
			+ this.resultABCD(value5f)
			+ this.resultABCD(value5g)
			+ this.resultABCD(value5h)
			+ this.resultABCD(value5i)
			+ this.resultABCD(value5j);
		console.log("value5All=" + value5All);
		if (value5All == 0) {
			comE = 0;
		} else if (value5All >= 1 && value5All <= 9) {
			comE = 1;
		} else if (value5All >= 10 && value5All <= 18) {
			comE = 2;
		} else if (value5All >= 19 && value5All <= 27) {
			comE = 3;
		}

		comF = this.resultABCD(value7);
		console.log("comF=" + comF);
		let valueGAll = this.resultABCD(value8) + this.resultABCD(value9);
		console.log("valueGAll=" + valueGAll);
		if (valueGAll == 0) {
			comG = 0;
		} else if (valueGAll >= 1 && valueGAll <= 2) {
			comG = 1;
		} else if (valueGAll >= 3 && valueGAll <= 4) {
			comG = 2;
		} else if (valueGAll >= 5 && valueGAll <= 6) {
			comG = 3;
		}

		console.log('comA=' + comA);
		console.log('comB=' + comB);
		console.log('comC=' + comC);
		console.log('comD=' + comD);
		console.log('comE=' + comE);
		console.log('comF=' + comF);
		console.log('comG=' + comG);

		let comAll = comA + comB + comC + comD + comE + comF + comG;
		let comScoreIndex = 0;
		let _comScoreStatus = "";
		if (comAll >= 0 && comAll <= 5) {
			_comScoreStatus = "非常好";
		} else if (comAll >= 6 && comAll <= 10) {
			_comScoreStatus = "较好";
			comScoreIndex = 1;
		} else if (comAll >= 11 && comAll <= 15) {
			_comScoreStatus = "良好";
			comScoreIndex = 2;
		} else if (comAll >= 16 && comAll <= 21) {
			_comScoreStatus = "差";
			comScoreIndex = 3;
		}

		console.log('comAll=' + comAll + ',comScoreStatus=' + _comScoreStatus);
		this.setData({
			comScore: comAll,
			comScoreStatus: _comScoreStatus,
			comScoreIndex,
			promptTextMessageFlag: true,
		})
	},
	resultABCD: function (a) {
		if (a == 'a') {
			return 0;
		} else if (a == 'b') {
			return 1;
		} else if (a == 'c') {
			return 2;
		} else if (a == 'd') {
			return 3;
		}
	},
	sleepState: function (a, b) {
		console.log('a=' + a + ',b=' + b);
		if (a == 'A') {
			if (b >= 1 && b <= 9) {
				return '不足';
			} else if (b >= 10 && b <= 12) {
				return '适中';
			} else if (b >= 13) {
				return '过长';
			} else {
				return '未知';
			}
		} else if (a == 'B') {
			if (b >= 1 && b <= 9) {
				return '不足';
			} else if (b >= 10 && b <= 12) {
				return '适中';
			} else if (b >= 13) {
				return '过长';
			} else {
				return '未知';
			}
		} else if (a == 'C') {
			if (b >= 1 && b <= 9) {
				return '不足';
			} else if (b >= 10 && b <= 12) {
				return '适中';
			} else if (b >= 13) {
				return '过长';
			} else {
				return '未知';
			}
		} else if (a == 'D') {
			if (b >= 1 && b <= 9) {
				return '不足';
			} else if (b >= 10 && b <= 12) {
				return '适中';
			} else if (b >= 13) {
				return '过长';
			} else {
				return '未知';
			}
		} else {
			return '未知';
		}
	},
	// 将时间字符串转换为分钟数  
	timeStringToMinutes: function (timeStr) {
		var parts = timeStr.split(":");
		return parseInt(parts[0], 10) * 60 + parseInt(parts[1], 10);
	},

	// 将分钟数转换回时间字符串格式 HH:mm  
	minutesToTimeString: function (minutes) {
		var hours = Math.floor(minutes / 60);
		var mins = minutes % 60;
		var minsStr = mins < 10 ? "0" + mins : mins.toString();
		return hours.toString() + ":" + minsStr;
	},

	// 计算时间差（分钟）  
	calculateTimeDifference: function (sleepTimeStr, wakeUpTimeStr) {
		// 将时间字符串转换为分钟  
		var sleepTimeMinutes = this.timeStringToMinutes(sleepTimeStr);
		var wakeUpTimeMinutes = this.timeStringToMinutes("24:00") + this.timeStringToMinutes(wakeUpTimeStr); // 加上第二天的0点到起床时间的分钟数  

		// 计算时间差  
		var diffInMinutes = wakeUpTimeMinutes - sleepTimeMinutes;

		// 将分钟数转换回时间字符串格式 HH:mm  
		var diffInHours = Math.floor(diffInMinutes / 60);
		var diffInMins = diffInMinutes % 60;

		// 返回时间差字符串  
		console.log("diffInMinutes==" + diffInMinutes)
		return diffInMinutes;
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {

		let oldJsonList = qnaire.qnaire
		oldJsonList.forEach(element => {

			let mapArray = [];
			if (element.type == "radio" || element.type == "radio&input") {
				for (let key in element.option) {
					mapArray.push({ key: key, value: element.option[key] });
				}
				element['options'] = mapArray;
			}
		});


		// console.log(oldJsonList);

		let columns = [[], []];

		for (let i = 0; i < 24; i++) {
			if (i < 10) {
				columns[0].push("0" + i);
			} else {
				columns[0].push("" + i);
			}
		}


		for (let i = 0; i < 60; i++) {
			if (i < 10) {
				columns[1].push("0" + i);
			} else {
				columns[1].push("" + i);
			}
		}
		console.log(columns);



		this.setData({
			privacyDetailShow: false,
			qnaire: oldJsonList,
			columns
		});
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
	
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})