/**序列化表单,多个value用数组存放**/
String.prototype.substitute = function(data) {
if (data && typeof data == 'object') {
return this.replace(/\{([^{}]+)\}/g, function(match, key) {
var value = data[key]
return value !== undefined ? '' + value : ''
})
} else {
return this.toString()
}
}
function tplNameReplace(num){
var str=num.value;
var value=str.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5\.]/g,'');
num.value=value;
}
$(function(){
//模版系列
var hgc_DtkTplModule = {
tpls:{
tplItemTPl:'
\
\
\
{title}\
\
\
总分:{total_score}分\
题量:{total_topics}小题\
\
\
其他信息
\
版式:{format}\
考号:{examFields}\
\
',
dtkBaseInfoTpl:'\
板式:{format}\
考号:{examFields}\
装订线:{hasBindline}\
总分:{total_score}分\
题量:{total_topics}\
',
dtkSubjectInfoTpl:'\
{bigTitle}{bigTitle}\
{subjectType}\
{questionLength}题\
共{questionScore}分\
',
dtkSubjectInfoXZTpl:'\
{bigTitle}{bigTitle}\
{subjectType}\
{questionLength}\
共{questionScore}分\
'
},
init:function(){
//判断[新创建]是数学还是其他学科(其他学科)
this.isMathForNew = !~location.href.indexOf('third/thirdview_duo')
//存放模版列表信息
this.tplList = []
this.dtkPosition = {}
this.examGroupId = $('input[name="examGroupId"]').val();
this.formatMap = {
horizontal:'横版',
vertical:'竖版',
1:'一栏',
2:'两栏',
3:'三栏'
}
this.questionTypes = {
1:'单选',
2:'多选',
11:'不定项选择',
5:'填空',
7:'解答',
17:'选做',
'7c':'作文'
}
this.savePrintInfo = localStorage.getItem('savePrintInfo')!=undefined? JSON.parse(localStorage.getItem('savePrintInfo')):{}
let _this = this;
this.thirdOnlineUrl = '/index.php/online/third';
let isCardReturn = window.location.href.indexOf('isCardReturn');
// let isCardReturn = document.referrer.indexOf('vue');
if(isCardReturn>-1){
let resData = JSON.parse(localStorage.getItem('upDataThreeCard'));
// let resData = JSON.parse(upDataThreeCard);
if(resData.savePrintInfo){
localStorage.setItem('savePrintInfo',JSON.stringify(resData.savePrintInfo));
_this.savePrintInfo = resData.savePrintInfo;
}
// $.post('/print/getOnlineCardTempData',{
// examGroupId:saveFormData.examGroupId,
// },function(res){
// res = JSON.parse(res);
// let resData = JSON.parse(res.data);
// if(resData.savePrintInfo){
// localStorage.setItem('savePrintInfo',JSON.stringify(resData.savePrintInfo));
// _this.savePrintInfo = resData.savePrintInfo;
// _this.initDom()
// _this.initPage()
// _this.getDtkInfo()
// }
// })
}
//提供下载pdf 的唯一标识符
this.downloadPdfIdentifier = ''
this.initDom()
this.bindEvent()
this.initPage()
this.getDtkInfo()
this.getTplList();
},
initDom:function(){
this.$dtkContentInfo = $('.hgc_leftContent .contentInfo')
this.$dtkContentNoInfo = $('.hgc_leftContent .contentNoInfo')
},
initPage:function(){
this.initConnectDtkStatus()
},
initConnectDtkStatus:function(){
var self = this;
//如果不是在线答题卡编辑页面跳转过来,直接清空storage
// if(!~document.referrer.indexOf('vue')){
// self.clearStorage()
// self.savePrintInfo = {}
// }
//判断是否有题目信息
var hasSubjectInfo = Object.keys(self.savePrintInfo).length;
self.setContentInfoStatus(hasSubjectInfo)
//如果进入该页面是关联答题卡页面,直接显示
if(localStorage.getItem('isConnect') === 'block'){
$(".template-flag").trigger('click')
}
},
setContentInfoStatus:function(hasSubjectInfo){
var self = this;
self.$dtkContentInfo[hasSubjectInfo?'show':'hide']()
self.$dtkContentNoInfo.css('display',hasSubjectInfo?'none':'flex')
},
// setConnectStatus:function(status){
// $('.hgc_leftContent').css('display',status)
// localStorage.setItem('isConnect',status)
// },
//获取当前答题卡信息
getDtkInfo:function(){
var self = this;
var dtkInfo = null;
//如果有记录的答题卡信息就使用记录的答题卡信息
var storageInfo = self.savePrintInfo;
var hasDtkInfo = Object.keys(storageInfo).length
self.examGroupId = JSON.parse(localStorage.getItem('testFormData')).examGroupId
var hasOnlineCard = JSON.parse(localStorage.getItem('testFormData')).hasOnlineCard
//考试id 存在就是编辑考试
if(self.examGroupId && !hasDtkInfo &&hasOnlineCard==1){
//console.log('test')
$.post('/index.php/third/getTemplateByExamGroupId',{examGroupId:self.examGroupId},function(res){
//console.log(res)
var savePrintInfoObj = {}
if(!JSON.parse(res).success){
// self.setConnectStatus('none')
self.setContentInfoStatus(false)
return;
}
dtkInfo = JSON.parse(res).data;
// dtkInfo = JSON.parse(res).data.position ? JSON.parse(JSON.parse(res).data.position) :{};
// dtkInfo.position = JSON.parse(JSON.stringify(dtkInfo));
self.dtkPosition = dtkInfo;
//判断是否是老版在线答题卡
if(JSON.parse(dtkInfo.position).online_card_version && JSON.parse(dtkInfo.position).online_card_version != '3.0.0'){
self.setContentInfoStatus(false)
return;
}
let question_info={
content:dtkInfo.questions
}
savePrintInfoObj = {
position:JSON.parse(dtkInfo.position),
sheet_answer:dtkInfo.sheet_answer,
sheet_score:dtkInfo.sheet_score,
timu:dtkInfo.timu,
title:dtkInfo.name,
question_info:question_info,
pdf_url:dtkInfo.online_card_pdf
}
self.verificationDtkInfo(savePrintInfoObj,dtkInfo.questions)
self.savePrintInfo = savePrintInfoObj
localStorage.setItem('savePrintInfo',JSON.stringify(savePrintInfoObj))
self.renderDtkInfo(savePrintInfoObj)
// self.setConnectStatus('block')
self.setContentInfoStatus(true)
})
}else{
if(hasDtkInfo){
dtkInfo = storageInfo;
self.dtkPosition = dtkInfo.position;
//直接把dtkInfo存到
self.renderDtkInfo(dtkInfo)
// self.setConnectStatus('block')
self.setContentInfoStatus(true)
}else{
// self.setConnectStatus('none')
self.setContentInfoStatus(false)
}
}
},
verificationDtkInfo:function(data,resData){
var self = this;
let topicAll = JSON.parse(JSON.stringify(resData));
// let topicMod = JSON.parse(JSON.stringify(data.position.buildQuestions));
// jQuery.each(topicMod,function (modI,topicModItem){
// topicAll = topicAll.concat(topicModItem.questions)
// })
jQuery.each(resData,function (i,item){
jQuery.each(data.question_info.content,function (j,topic){
if(topic.questionNum==item.questionNum){
let isEdit = false;
if(topic.fullScore!=item.fullScore){
isEdit = true
topic.fullScore=item.fullScore
}
if(item.questionTypeId == 2){
if(item.ruleScoreHalf != topic.halfScore){
isEdit = true
topic.halfScore = item.ruleScoreHalf
}
}
if(isEdit){
self.editDtkInfo(topicAll,topic.topicNo,item)
}
}
})
})
},
editDtkInfo:function(topicAll,topicNo,resDataTtem){
jQuery.each(topicAll,function (idx,topic){
if(topic.topicNo==topicNo){
topic.fullScore=resDataTtem.fullScore
if(resDataTtem.questionTypeId == 2){
if(resDataTtem.ruleScoreHalf != topic.halfScore){
topic.halfScore = resDataTtem.ruleScoreHalf
}
}
}
})
},
renderDtkInfo:function(dtkInfo){
var self = this;
// self.downloadPdfIdentifier = dtkInfo.position.identifier
self.renderDtkBaseInfo(dtkInfo)
self.renderDtkSubjectInfo(dtkInfo.position.topicListObject)
},
renderDtkBaseInfo:function(dtkInfo){
var self = this;
var tpl_data = dtkInfo.position
var dtkbaseInfo = self.getOtherInfo(tpl_data)
var paperScoreAll = self.getScoreAll(dtkInfo.question_info.content)
var calcScoreTimu = self.calcScoreTimu(paperScoreAll,dtkInfo.timu)
calcScoreTimu.total_score = tpl_data.cardSetting.examInfoConfig.fullScore.text;
var baseInfoHtmls = self.tpls.dtkBaseInfoTpl.substitute({
...dtkbaseInfo,
total_score:calcScoreTimu.total_score,
total_topics:calcScoreTimu.total_topics,
hasBindline:tpl_data.cardSetting.hasBindingLine?'有':'无'
})
$('.hgc_leftContent .module').eq(0).find('.infoItem').eq(0).children('.info').html(baseInfoHtmls)
},
getScoreAll:function (data) {
let scoreArr = [];
let pId = 0;
for (let i = 0; i < data.length; i++) {
if(data[i].questionTypeId==17){
if(data[i].topicNo!=pId){
scoreArr.push(Number(data[i].fullScore))
pId = data[i].topicNo
}
}else{
scoreArr.push(Number(data[i].fullScore))
}
}
return scoreArr
},
calcQuestionsLen:function(buildQuestions,modelId){
let count = 0,score = 0;
// for(let modelId in buildQuestions){
if(buildQuestions[modelId].questionTypeId == 17){
count = buildQuestions[modelId].questions[0].total + '选' + buildQuestions[modelId].questions[0].required;
score += parseFloat(buildQuestions[modelId].questions[0].fullScore)
}else{
buildQuestions[modelId].questions.forEach(function(val,index){
if(val){
score += parseFloat(val.fullScore)
}else{
buildQuestions[modelId].questions.splice(index,1)
}
})
count += buildQuestions[modelId].questions.filter(v=>v!=null).length
}
// }
return {count:count,score:score};
},
calcTotalScore:function(buildQuestions,modelId){
let count = 0,score = 0;
for(let modelId in buildQuestions){
if(buildQuestions[modelId].questionTypeId == 17){
count += parseFloat(buildQuestions[modelId].questions[0].total);
score += parseFloat(buildQuestions[modelId].questions[0].fullScore)
}else{
buildQuestions[modelId].questions.forEach(function(val,index){
if(val){
score += parseFloat(val.fullScore)
}else{
buildQuestions[modelId].questions.splice(index,1)
}
})
count += buildQuestions[modelId].questions.filter(v=>v!=null).length
}
}
// return {count:count,score:score};
$('.dtkTotalScore').html(score).attr('data-topics',count)
},
renderDtkSubjectInfo:function(buildQuestions){
var self = this;
var subjectInfoHtml = '';
for(let modelId in buildQuestions){
// subjectInfoHtml += '\
//
\
subjectInfoHtml += '
\
'+buildQuestions[modelId].questionTitleReadonly+''+buildQuestions[modelId].questionTitleReadonly+'\
'+PaperAndTopicConfig.topicTypeObj[buildQuestions[modelId].questionCreateTypeId]+'\
'+this.calcQuestionsLen(buildQuestions,modelId).count+'题\
共'+this.calcQuestionsLen(buildQuestions,modelId).score+'分\
'
//
\
//
'
this.calcTotalScore(buildQuestions,modelId);
}
$('.cardTopicInfo').html(subjectInfoHtml)
},
//获取模版
getTplList:function(){
var self = this
$.get('/index.php/third/tplList',function(res){
var result = JSON.parse(res);
if(result.success === 1 && result.thisTpls){
self.tplList = []
jQuery.each(result.thisTpls, function (i, item){
let tpl_data = JSON.parse(item.tpl_data)
if(tpl_data.position && tpl_data.position.online_card_version == '3.0.0'){
// if(tpl_data.position.){
self.tplList.push(item)
// }
} else {
// let errTplMsg = '在线答题卡模板:'+item.title+'(id:'+item.third_tpl_id+')'+'缺少数据,是否删除模板?'
// layer.confirm(errTplMsg, {title:'提示'}, function(index){
// self.delTpl(item.third_tpl_id)
// layer.close(index);
// });
}
})
if(self.tplList.length>0){
$('#tplListMsg').hide();
} else{
$('#tplListMsg').show()
}
self.renderTplList(self.tplList)
}
})
},
//format examFields
getOtherInfo:function(tpl_data){
var self = this;
let papers = ['','A3','A4','16K','8Ks','8Kb'];
let direction = tpl_data.cardSetting.direction==1?'horizontal':'vertical';
var format = papers[tpl_data.cardSetting.paperSize]+'-'+self.formatMap[direction]+'-'+self.formatMap[tpl_data.cardSetting.column]
var examFields = ''
if(tpl_data.cardSetting.examinationNumberType.indexOf(1)){
examFields+='条形码'
}
if(tpl_data.cardSetting.examinationNumberType.indexOf(2)){
examFields+=' 填涂'
}
return {
format:format,
examFields:examFields
}
},
calcScoreTimu:function(sheet_score,timu){
var self = this;
var total_topics = 0;
var total_score = 0
for(var key in sheet_score){
total_score+=Number(sheet_score[key])
}
for(var type in timu){
total_topics+=Number(timu[type])
}
if(timu==undefined){
total_topics = sheet_score.length
}
return {
total_topics:total_topics,
total_score:total_score
}
},
renderTplList:function(tpls){
var self = this;
// if(!tpls.length)alert('数据不存在');
var htmls = tpls.reduce( function(str,item){
var tpl_data = JSON.parse(item.tpl_data)
var otherInfo = self.getOtherInfo(tpl_data.position)
item.format = otherInfo.format
item.examFields = otherInfo.examFields
str += self.tpls.tplItemTPl.substitute(item)
return str
},'')
$('.tplList').html(htmls)
$('#tplLength').text(tpls.length)
// if(tpls.length > 0){
// $('#tplListMsg').show();
// }else{
// $('#tplListMsg').hide();
// }
},
bindEvent:function(){
var self = this;
// $(".template-flag").click(function(){
// var $rightContent = $(".hgc_leftContent");
// $(".hgc_leftContent").toggle();
// self.setConnectStatus($rightContent.css('display'))
// });
$('body').on('click','.menu',function(e){
e.stopPropagation()
$(this).children('.triangle').css('display','flex')
$(this).children('.menuList').css('display','flex')
})
$(document).click(function(){
$('.menu').children('.triangle').css('display','none')
$('.menu').children('.menuList').css('display','none')
})
$('body').on('click','.menuList span',function(e){
var $this = $(this);
var type = $(this).attr('class');
var tplId = $(this).attr('data-id')
switch(type){
case 'del':
self.delTpl(tplId,$this)
break;
case 'preview':
self.previewTpl(tplId);
break;
case 'use':
self.useTpl(tplId);
break;
}
})
//修改新版答题卡
$('#editNewMyTpl').click(function(e){
self.goEditAnswerSheet();
})
//保存模版
$('#saveMyTpl').click(function(){
var tplTitle = '',total_score,total_topics;
// var {sheet_score,timu,position,question_info} = self.savePrintInfo;
// var total_topics = 0;
// var total_score = position.cardSetting.examInfoConfig[1].text;
// if(typeof(sheet_score) === 'string'){
// sheet_score = JSON.parse(sheet_score);
// }
// for(var key in sheet_score){
// total_score+=+sheet_score[key]
// }
// for(var type in timu){
// total_topics+=Number(timu[type])
// }
// if(timu==undefined){
// total_topics = question_info.content.length
// }
layer.confirm('', function(index){
//do something
tplTitle = $('#tplName').val();
$('.hgc_inputItem .error')[tplTitle?'hide':'show']()
total_score = $('.dtkTotalScore').html();
total_topics = $('.dtkTotalScore').attr('data-topics')
if(tplTitle){
$.ajax({
url: '/index.php/third/saveTemplateByOnline',
method: 'POST',
data:{
title:tplTitle,
total_score,
total_topics,
tpl_data:JSON.stringify(self.savePrintInfo)
},
success: function (data) {
if(JSON.parse(data).success === 1){
layer.msg('保存答题卡成功');
self.getTplList()
} else {
layer.msg(JSON.parse(data).message);
}
}
})
}
tplTitle && layer.close(index);
});
})
var $tplListEl = $('.hgc_leftContent .tplList');
$('.hgc_leftContent .btnItem').click(function(){
var stepNum = $(this).hasClass('leftBtn')?225:-225;
var curLeft =Math.abs($tplListEl.position().left);
if(stepNum<0 && curLeft<220){
return false
}
var listW = Math.abs($tplListEl.width());
var boxW = Math.abs($('.relation-answer-card .tplBox').width());
if((curLeft + boxW +stepNum -240)==listW || (curLeft + boxW +stepNum -240)>listW){
return false
}
$tplListEl.animate({left:-(curLeft+stepNum)},100)
})
$('.contentNoInfo .hbtn').click(function(){
self.goOnlineCard()
})
/*创建答题卡*/
$('#goAnswerSheet').click(function(){
var newTestFormData = JSON.parse(localStorage.getItem('testFormData')) || {};
var AnswerSheetUrl = '/index.php/online/answersheet?examGroupId='+newTestFormData.examGroupId+'&cardType=0&isEdit=0'
location.href = AnswerSheetUrl;
})
//下载pdf
$('#downLoadPdfBtn').click(function () {
var newTestFormData = JSON.parse(localStorage.getItem('testFormData')) || {};
//isProduction
// var host = isProduction?'//zsyapi.zhixinhuixue.com':'//192.168.1.60:8001'
// location.href = host+'/download/'+self.downloadPdfIdentifier
// location.href = self.savePrintInfo.pdf_url;
location.href = '/third/download?url=' + self.savePrintInfo.pdf_url + '&title=pdf-'+self.savePrintInfo.title+newTestFormData.examGroupId
})
// 保存并返回
$("body").delegate("#createThirdCard", "click", function(e) {
e.preventDefault();
if(!localStorage.savePrintInfo || !JSON.parse(localStorage.savePrintInfo).online_card_version){
location.href = '/index.php/third/index'
return false
}
// var error=[];
// if(error.length == 0){
$(this).attr('active','false');
var data = JSON.parse(localStorage.getItem('testFormData')) || {};
//如果选择关联答题卡的时候
if($('.hgc_leftContent').is(':visible')){
var tplInfo = self.savePrintInfo;
for(var key in tplInfo){
var keyInfo = tplInfo[key];
if(typeof keyInfo === 'object'){
if(key === 'pdfTemplate')continue;
data[key] = JSON.stringify(keyInfo)
}else{
if(key === 'pdfHtml'){
keyInfo = new Blob([keyInfo], {
type: 'text/plain;charset=utf-8'
})
key = 'pdfTemplate'
}
data[key] = keyInfo
}
}
}
var formData = new FormData()
for(var k in data){
if(k === 'pdfTemplate'){
formData.append(k,data[k],'pdfTepmlate.txt')
}else{
formData.append(k,data[k])
}
}
//console.log(formData)
$.ajax({
//'//192.168.1.51/index.php/print/saveCardOnline' + loginStatus,
url:"/index.php/third/insertThirdSheet",
method: 'POST',
processData: false,
contentType: false,
dataType: 'json',
data: formData,
success: function (data) {
//console.log(data)
if(data.success === 1){
layer.msg(data.message);
self.clearStorage()
location.href = data.result;
location.href = '/index.php/third/index'
}else {
layer.msg(data.message);
self.clearStorage()
setTimeout(function () {
location.href = '/index.php/third/index'
},3000)
}
}
})
// }else{
// layer.msg(error.join(','));
// $("#createThirdCard").attr('active','true');
// }
});
},
clearStorage:function(){
//清空storage
localStorage.removeItem('position')
localStorage.removeItem('buildQuestions')
localStorage.removeItem('savePrintInfo')
localStorage.removeItem('testFormData')
localStorage.removeItem('isCardReturn')
},
useTpl:function(tplId){
var self = this;
var tpl = self.tplList.find(v=>v.third_tpl_id === tplId);
var tpl_data = JSON.parse(tpl.tpl_data);
var tplTestFormData = JSON.parse(localStorage.getItem('testFormData')) || {};
tpl_data.examGroupId = tplTestFormData.examGroupId;
// localStorage.setItem('position',tpl.tpl_data)
// localStorage.setItem('buildQuestions',JSON.stringify(JSON.parse(tpl.tpl_data).buildQuestions))
localStorage.setItem('savePrintInfo',JSON.stringify(tpl_data));
this.savePrintInfo = tpl_data;
// this.savePrintInfo = JSON.parse(tpl.tpl_data)
// self.goOnlineCard()
// hgc_DtkTplModule.getDtkInfo()
// location.href = self.thirdOnlineUrl;
self.goEditAnswerSheet();
},
previewTpl:function(tplId){
var self = this;
var tpl = self.tplList.find(v=>v.third_tpl_id === tplId);
var tpl_data = JSON.parse(tpl.tpl_data);
var tplTestFormData = JSON.parse(localStorage.getItem('testFormData')) || {};
tpl_data.examGroupId = tplTestFormData.examGroupId;
// 存储预览前的试卷信息
if(localStorage.getItem('savePrintInfo')){
localStorage.setItem('previewSavePrintInfo',localStorage.getItem('savePrintInfo'));
}
localStorage.setItem('savePrintInfo',JSON.stringify(tpl_data));
this.savePrintInfo = tpl_data;
location.href = '/index.php/online/answersheet?examGroupId='+tpl_data.examGroupId+'&cardType=0&isEdit=1&isPreview=1';
},
goOnlineCard:function(){
var self = this;
self.isOldTpl();
},
isOldTpl:function (isPreview) {
var self = this;
var addGrade = 0
$('.grade-sel ul li').each(function(){
if($(this).hasClass('active')){
addGrade = $(this).attr('grade')
}
})
if(addGrade!=undefined&&addGrade!==0){
var grade = addGrade
} else {
var grade = $("input[name='grade']").val();
}
// var grade = 1;
// modifyThirdExam
var isEdit = ~location.href.indexOf('modifyThirdExam');
if(isEdit){
if(hasThirdCard==1&&hasOnlineCard==0){
layer.confirm('', function(index){
// $.ajax({
// url: 'index.php/third/clearExamTpl',
// method: 'POST',
// data:{
// examGroupId:self.examGroupId,
// },
// success: function (data) {
// if(data.success === 1){
// $('.grade-sel ul li').each(function(){
// if($(this).hasClass('active')){
// grade = $(this).attr('grade')
// }
// })
localStorage.setItem('grade',grade)
location.href = self.thirdOnlineUrl
// }else{
// layer.msg(data.info)
// }
// }
// })
});
}else{
// $('.grade-sel ul li').each(function(){
// if($(this).hasClass('active')){
// grade = $(this).attr('grade')
// }
// })
localStorage.setItem('grade',grade)
location.href = self.thirdOnlineUrl
}
}else{
// $('.grade-sel ul li').each(function(){
// if($(this).hasClass('active')){
// grade = $(this).attr('grade')
// }
// })
localStorage.setItem('grade',grade)
location.href = self.thirdOnlineUrl
}
},
goEditAnswerSheet:function () {
var newTestFormData = JSON.parse(localStorage.getItem('testFormData')) || {};
location.href = '/index.php/online/answersheet?examGroupId='+newTestFormData.examGroupId+'&cardType=0&isEdit=1';
},
delTpl:function(tplId,$this){
$.post('/third/delTpl',{third_tpl_id:tplId},function(res){
var result = JSON.parse(res);
if(result.success === 1 && $this){
$this.closest('.tplItem').remove()
$('#tplLength').text(Number($('#tplLength').text() -1))
if(Number($('#tplLength').text())==1){
$('#tplListMsg').hide()
} else{
$('#tplListMsg').show()
}
}
})
}
}
hgc_DtkTplModule.init()
})