/**
 * 工具函数模块
 * 包含通用的工具方法
 */

/**
 * 获取屏幕尺寸并计算视频高度
 * @param {Object} context - 页面上下文
 */
export function getScreenSize(context) {
	var res = wx.getWindowInfo(); // 基础库2.20.1+可用
	var screenWidth = res.windowWidth;
	var videoHeight = screenWidth * (9 / 16); // 计算16:9高度

	context.setData({
		screenWidth: screenWidth,
		videoHeight: videoHeight
	});
}

/**
 * 生成展开状态：只根据接口返回的 is_current，哪个小节 is_current 为 true 就展开哪个
 * @param {Object} context - 页面上下文
 */
export function generateExpandedStatus(context) {
	var courseList = context.data.courseList;

	if (!courseList || courseList.length === 0) {
		return;
	}

	var sections = new Array(courseList.length).fill({ expanded: false });
	var sectionId = null;
	var selectedIndex = 0;

	for (var i = 0; i < courseList.length; i++) {
		if (courseList[i].is_current === true) {
			sections[i] = { expanded: true };
			sectionId = courseList[i].id || courseList[i].course_id || courseList[i].section_id;
			selectedIndex = i;
			break;
		}
	}

	context.setData({
		sections: sections,
		currentSelectedCourseId: sectionId,
		currentSelectedCourseIndex: selectedIndex
	});

	if (sectionId && sectionId !== 0 && sectionId !== '0' && sectionId !== 'undefined') {
		if (courseList[selectedIndex] && courseList[selectedIndex].is_started && context.refreshTaskListStatus) {
			context.refreshTaskListStatus(sectionId, selectedIndex);
		}
	}
}

/**
 * 解析视频完成百分比
 * @param {Object} task - 任务对象
 * @returns {Number|null} 完成百分比（1-100）或 null
 */
export function resolveVideoCompletionPercent(task) {
	if (!task) {
		return null;
	}
	var candidates = [];
	var pushCandidate = function(val) {
		if (val !== undefined && val !== null && val !== '') {
			candidates.push(val);
		}
	};

	pushCandidate(task.completion_percentage);
	pushCandidate(task.completionPercent);
	if (task.condition) {
		pushCandidate(task.condition.completion_percentage);
		pushCandidate(task.condition.completionPercent);
		if (task.condition.video) {
			pushCandidate(task.condition.video.completion_percentage);
			pushCandidate(task.condition.video.completionPercent);
			pushCandidate(task.condition.video.percentage);
		}
	}
	if (task.content) {
		pushCandidate(task.content.completion_percentage);
		pushCandidate(task.content.completionPercent);
		if (task.content.video) {
			pushCandidate(task.content.video.completion_percentage);
			pushCandidate(task.content.video.completionPercent);
			pushCandidate(task.content.video.percentage);
		}
	}
	if (task.detail) {
		pushCandidate(task.detail.completion_percentage);
		pushCandidate(task.detail.completionPercent);
		pushCandidate(task.detail.video_completion_percent);
	}

	for (var i = 0; i < candidates.length; i++) {
		var value = Number(candidates[i]);
		if (isNaN(value)) {
			continue;
		}
		if (value <= 0) {
			continue;
		}
		// 支持 0-1 之间的小数表示
		if (value > 0 && value <= 1) {
			value = value * 100;
		}
		value = Math.min(100, Math.max(1, Math.round(value)));
		return value;
	}
	return null;
}

/**
 * 更新任务状态
 * @param {Object} context - 页面上下文
 * @param {String} taskId - 任务ID
 * @param {String} status - 任务状态
 */
export function updateTaskStatus(context, taskId, status) {
	// 1. 深拷贝原数据
	var newCourseList = JSON.parse(JSON.stringify(context.data.courseList));

	// 2. 嵌套循环找到对应的任务（支持 id 和 task_id 两种字段名）
	var taskIdStr = String(taskId);
	for (var group of newCourseList) {
		if (!group.tasks || !Array.isArray(group.tasks)) continue;
		for (var task of group.tasks) {
			var currentTaskId = String(task.id || task.task_id || '');
			if (currentTaskId === taskIdStr) {
				// 3. 修改状态值（确保状态值符合规范）
				// 状态值：NotStarted, InProgress, Completed, Reviewing, Rejected
				if (status === 'NotStarted' || status === 'InProgress' || 
					status === 'Completed' || status === 'Reviewing' || 
					status === 'Rejected') {
					task.status = status;
				} else {
					return;
				}

				// 4. 更新数据
				context.setData({
					courseList: newCourseList
				});
				return;
			}
		}
	}
}

