function selectedOption(question, optionCode) {
	const options = question && Array.isArray(question.options) ? question.options : []
	return options.find(option => String(option.code) === String(optionCode)) || null
}

function validateBackgroundAnswer(question, optionCode, customText) {
	const option = selectedOption(question, optionCode)
	if (!option) return '请选择当前题目的答案'
	if (option.customAllowed && !String(customText || '').trim()) return '请填写其他选项的具体内容'
	return ''
}

function createBackgroundAnswerPayload(question, optionCode, customText) {
	const option = selectedOption(question, optionCode)
	return {
		detailId: question && question.detailId,
		optionCode: optionCode || '',
		customText: option && option.customAllowed ? String(customText || '').trim() : ''
	}
}

function encodeQuery(params) {
	return Object.keys(params || {})
		.filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
		.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
		.join('&')
}

function backgroundIntroUrl(params) {
	return `/pagesPublish/backgroundSurveyIntro?${encodeQuery(Object.assign({ stage: 'background' }, params))}`
}

function perillIntroUrl(params) {
	return `/pagesPublish/backgroundSurveyIntro?${encodeQuery(Object.assign({ stage: 'perill' }, params))}`
}

function questionnaireFillUrl(params) {
	return `/pagesPublish/questionnaireFill?${encodeQuery(params)}`
}

function isPublishablePerillQuestionnaire(questionnaire) {
	if (!questionnaire) return false
	return !questionnaire.purpose || questionnaire.purpose === 'PERILL'
}

module.exports = {
	selectedOption,
	validateBackgroundAnswer,
	createBackgroundAnswerPayload,
	encodeQuery,
	backgroundIntroUrl,
	perillIntroUrl,
	questionnaireFillUrl,
	isPublishablePerillQuestionnaire
}
