打开/关闭菜单
Toggle preferences menu
打开/关闭个人菜单
未登录
未登录用户的IP地址会在进行任意编辑后公开展示。

MediaWiki:Gadget-tikuInlineEditModule.js:修订间差异

MediaWiki界面页面
无编辑摘要
(导入1个版本)
 
(未显示同一用户的106个中间版本)
第4行: 第4行:


function editThis(id) {
function editThis(id) {
    $('#' + id).fadeOut(0)
$('#'+id).fadeOut('fast')
    var data = $('.data')
     var timuList = gDomTimuList()
     var dataLength = data.length
console.log(timuList)
    var singleData = $(data[id]).html()
var order = timuList.order
    var html = singleData
var timu = timuList.timu
    if ($(data[id]).children().length > 0) {
     var dataJSON = timu[id].dataJSON
        $(data[id]).children().each(
     var inputBoxes = loadPreview(dataJSON)
            function (id, v) {
      
                console.log(v)
     var form = renderPreviewInputBoxes(inputBoxes, id)
                var innerHTML = entityToString(v)
     render(id, dataJSON.type, form,'#'+id,true)
                console.log(innerHTML)
     setTimeout(function(){
                var escape = ''
     $("html,body").animate({scrollTop:$("#edit-"+id).position().top},500)
                escape = innerHTML.replace(/"/g, '\\"')
    },250)
                console.log(escape)
   
                singleData = singleData.replace(innerHTML, escape)
}
            }
 
        )
function typeOfObj(object){
     }
return Object.prototype.toString.call(object);
    $(data[id]).html(html)
    console.log(singleData)
     var jsonData = $.parseJSON(singleData)
     console.log(jsonData)
     var o = eval('newInlineEditor(' + id + ',' + JSON.stringify(jsonData) + ',false,true).' + jsonData.type + '()')
     render(id, jsonData.type, o,'#'+id,true)
     console.log('加载题目:' + (id + 1) + '/' + dataLength)
    console.log($("#edit-"+id).position().top)
     $("html,body").animate({scrollTop:$("#edit-"+id).position().top},500)
}
}


function confirmEdit(id) {
function loadPreview(dataJSON){
     var pageTitle = $('#firstHeading').text()
     var timuJSON = dataJSON
     var data = formToJSON('#edit-' + id, true, 's')
    console.log(timuJSON)
     console.log(data)
    var order = ['source', 'pos', 'inputbox', 'sourceRange', 'title', 'choices', 'answer', 'explain', 'info']
     var formatedData = formatEditText(data)
     var chineseName = {
     var template = JSONtoTemplate(formatedData)
        'source':'编号'
     console.log(template)
        , 'pos':'挖空点符号'
    try {
        , 'inputbox':'是否显示输入框'
         inlineEditorPageText = getOriginalText(pageTitle, formatedData, template)
        , 'sourceRange':'子题目数'
    } catch (e) {
        , 'title':'题目'
        alert('获取本页内容失败,请检查网络并重试!\n如反复故障请先手动编辑并联系管理员。\n错误内容:' + e)
        , 'choices':'选项'
        , 'answer':'答案'
        , 'explain':'解释'
        , 'info':'信息'
     }
     var sametypes = [ 'pos', 'inputbox', 'sourceRange', 'info']
     var notsametypes = ['title', 'titlesList', 'optionsDic','optionsList', 'answer', 'answersList', 'explain', 'explainsList']
     var inputboxes = {
        type:timuJSON.type
        ,typeHTML:'<input style="display:none" name="edit-type" value="'+timuJSON.type+'">'
        ,source: '<p class="source">'+timuJSON.type+'型题 '+timuJSON.source+'</p><input style="display:none" name="edit-source" value="'+timuJSON.source+'">'
        ,title:[]
        ,choices:[]
        , answer:[]
        , explain:[]
    }
    for(var i=0;i<sametypes.length;i++){
        if(timuJSON[sametypes[i]]===undefined){
            continue
         }else if(sametypes[i]==='info'){
            inputboxes[sametypes[i]] = textareaGroup(chineseName[sametypes[i]],timuJSON[sametypes[i]], 'edit-'+sametypes[i])
        }else{
            inputboxes[sametypes[i]] = inputGroup(chineseName[sametypes[i]],timuJSON[sametypes[i]],  'edit-'+sametypes[i])
        }
       
     }
     }


     if (inlineEditorPageText !== false) {
     //处理题目
         loadModule(id, {before: inlineEditorPageText.inner, after: template})
    var isTitleList = typeOfObj(timuJSON.title)==='[object Array]' ? true:false
    var titles = !isTitleList ? [timuJSON.title] :  timuJSON.title
    console.log(titles )
    inputboxes.titlesNum = titles.length
    for(var i=0;i<titles.length;i++){
         inputboxes.title.push(textareaGroup(chineseName['title'],titles[i], 'edit-title-'+i))
     }
     }


}
    //处理答案
    var isAnswerList = typeOfObj(timuJSON.answer)==='[object Array]' ? true:false
    var answers = !isAnswerList ? [timuJSON.answer] :  timuJSON.answer
    console.log(answers)
    inputboxes.answersNum = answers.length
    for(var i=0;i<inputboxes.titlesNum;i++){//此处以题目数为准,有几个题目生成几个答案和解释框
    var answerText = answers[i]===undefined?'':answers[i]
        inputboxes.answer.push(inputGroup(chineseName['answer'],answerText, 'edit-answer-'+i))
    }


function getOriginalText(pageTitle, timuData, editedText) {
    //处理解释
     var latestPageData = getLatestPageRevision(editUrl, pageTitle)
     var isExplainList = typeOfObj(timuJSON.explain)==='[object Array]' ? true:false
    console.log(latestPageData)
     var explains = !isExplainList ? [timuJSON.explain] :  timuJSON.explain
    var regMatchInner = new RegExp('(?<=\\{\\{' + timuData.type + '型题\\n\\|source=' + timuData.source + '\\n)[^}}]*(?=\\}\\}?)', 'g')
    console.log(explains)
     var regMatchFull = new RegExp('(\\{\\{' + timuData.type + '型题\\n\\|source=' + timuData.source + '\\n)[^}}]*(\\}\\})', 'g')
     inputboxes.explainsNum = explains.length
     if (timuData.type === 'B' || timuData.type === 'C') {
    for(var i=0;i<inputboxes.titlesNum;i++){//此处以题目数为准,有几个题目生成几个答案和解释框
        regMatchInner = new RegExp('(?<=\\{\\{' + timuData.type + '型题\\n\\|source=' + timuData.source + '\\n\\|sourceRange=' + timuData.sourceRange + '\n)[^}}]*(?=\\}\\}?)', 'g')
    var explainText = explains[i]===undefined?'':explains[i]
         regMatchFull = new RegExp('(\\{\\{' + timuData.type + '型题\\n\\|source=' + timuData.source + '\\n\\|sourceRange=' + timuData.sourceRange + '\n)[^}}]*(\\}\\})', 'g')
         inputboxes.explain.push(textareaGroup(chineseName['explain'],explainText, 'edit-explain-'+i))
     }
     }
     console.log(regMatchInner)
 
     var inner = latestPageData.match(regMatchInner)
     //处理选项
     var full = latestPageData.match(regMatchFull)
     var isOptionList = typeOfObj(timuJSON.choices)==='[object Array]' ? true:false
    console.log(inner)
     var options = !isOptionList ? [timuJSON.choices] :  timuJSON.choices
     console.log(full)
     console.log(options)
     if (inner.length === 1 && full.length === 1) {
     for(var i=0;i<options.length;i++){
         latestPageData = latestPageData.replace(regMatchInner, editedText)
         var dic = options[i]
        return {full: full[0], inner: inner[0], replacedText: latestPageData}
         for(var k in dic){
    } else {
             options[i][k] = inputGroup(chineseName['choices']+' '+k,options[i][k], 'edit-choice-'+i+'-'+k)
        var warnText = '匹配到重复内容,请点击确认转为手动编辑(已作的编辑会丢失,请注意保存!)'
         for(var i=0;i<full.length;i++){
             warnText += '\n===匹配数据:'+i+'===\n'+full[i]
         }
         }
        var editSource = confirm(warnText)
        if (editSource){
            var confirmFresh = confirm('已作的编辑会丢失,如未保存请返回!')
            if(confirmFresh){
                $('#ca-edit').children('a')[0].click()
            }
        }
        return false
     }
     }
    //检测是否有选项,如果没有则不加
    if(options.length>0){
    inputboxes.choices = options
    }
   
    console.log(inputboxes)
    return inputboxes
}
}


function loadModule(id, data) {
function inputGroup(label, value, name, id, classes , placeholder){
    document.body.style.overflow = 'hidden'
id = id === undefined ?'':id
     var mask = $('<div id="mask" style="background: #000;background-size: cover; position: absolute; left: 0px; top: 0px; width: 100%; filter: alpha(opacity=30); opacity: 0.3; display: none; z-index: 2;"></div>')
classes = classes ===undefined ?'':classes
     mask.css('height', ($(window).height() + $(window).scrollTop()) + 'px')
placeholder = placeholder===undefined ? '':placeholder
     mask.prependTo('body')
     return $('<div class="mb-1">'+
     $('#mask').fadeIn(500)
    '<div class="input-group">'+
    confirmEditModule(id, data)
    '<div class="input-group-prepend">'+
    ' <div class="input-group-text"><b>'+label+'</b></div>'+
    '</div>'+
     '<input type="text" class="m-0 form-control '+classes+'" id="'+id+'" name="'+name+'" style="height:25px" placeholder="'+ placeholder +'" value="'+value+'">'+
     '</div>'+
     '</div>')
}
}
 
function textareaGroup(label, value, name, id, classes){
function dismissModule() {
id = id === undefined ?'':id
    document.body.style.overflow = 'visible'
classes = classes ===undefined ?'':classes
     $('#mask').fadeOut(700)
     return $('<div class="mb-1"><div class="input-group">'+
     $('.confirmEditContainer').fadeOut(300)
     '<div class="input-group-prepend">'+
     setTimeout(function () {
      '<span class="input-group-text"><b>'+label+'</b></span>'+
         $('#mask').remove()
     '</div>'+
        $('.confirmEditContainer').remove()
         '<textarea class="form-control" '+classes+'" id="'+id+'" name="'+name+'">'+value+'</textarea>'+
     }, 1000)
     '</div></div>')
}
}
 
function renderPreviewInputBoxes(inputBoxes,id){
function confirmEditModule(id, data) {
console.log(id,inputBoxes)
    if (data.before === undefined) {
     var form = $('<form id="edit-'+id+'" name="edit-'+id+'"><input name="edit-titleCount" style="display:none" value="'+inputBoxes.titlesNum+'">'+
        data.before = '无内容'
     '<br>正在编辑:</form>')
    } else if (data.after === undefined) {
     console.log(form)
        data.after = '无内容'
     var sametypes = ['typeHTML','source','pos', 'inputbox', 'sourceRange', 'info']
    }
     var differenttypes = ['title', 'choices', 'answer', 'explain']
     var div = $('<div style="position:absolute;top:0;left:0;width: 100%;overflow: scroll"></div>')
     for(var i=0;i<sametypes.length;i++){
    div.css('height', ($(window).height() + $(window).scrollTop()) + 'px')
         form.append(inputBoxes[sametypes[i]])
    var container = $('<div class="confirmEditContainer"></div>')
    var header = $('<div class="confirmEditHeader"><h3>以下为修改结果 请认真耐心检查核对!</h3><hr></div>')
    var changesContainer = $('<div class="changesContainer"></div>')
    var changes = $('<div class="changes"></div>')
    var before = $('<div class="before-edit change"><b>编辑前:</b><br><textarea>' + data.before + '</textarea></div>')
     var after = $('<div class="after-edit change"><b>编辑后:</b><br><textarea>' + data.after + '</textarea></div>')
     var appendix = $('<div class="confirmEditAppendix"><hr></div>')
     var btnSubmit = $('<button id="confirmEditAndSubmit" class="confirmEditBtn btn button-primary button-rounded">确认并提交更改</button>')
    var btnCancel = $('<button id="confirmEditDismiss" class="confirmEditBtn btn button-caution button-rounded">关闭本窗口</button>')
    changes.append(before, after)
    changes.appendTo(changesContainer)
    appendix.append(btnCancel, btnSubmit)
    container.append(header, changesContainer, appendix)
    container.appendTo(div)
    div.prependTo('body')
     $('#confirmEditDismiss').bind('click', function () {
        dismissModule()
    })
    $('#confirmEditAndSubmit').bind('click', function () {
        submitChanges(id)
        dismissModule()
    })
    var width = container.width()
     if ($(window).width() >= 600) {
        var left = ($(window).width() * 1 - width * 1) / 2
        var top = $(window).scrollTop() * 1 + $(window).height() * 0.15
    } else {
         var left = 5
        var top = $(window).scrollTop() * 1 + $(window).height() * 0.001
     }
     }
     container.css('left', left + 'px')
     if('B,C'.includes(inputBoxes.type)){
    container.css('top', top + 'px')
        for(var i in inputBoxes.choices){
 
            console.log(i)
    console.log(left)
             for(k in inputBoxes.choices[i]){
    $('.confirmEditContainer').fadeIn(500)
              form.append(inputBoxes.choices[i][k])
 
}
function submitChanges(id) {
    var pageTitle = $('#firstHeading').text()
    var data = formToJSON('#edit-' + id, true, 's')
    console.log(data)
    var formatedData = formatEditText(data)
    var template = JSONtoTemplate(formatedData)
    console.log(template)
    var pageData = inlineEditorPageText
    if (pageData !== false) {
        var confirmEdit = confirm('即将开始上传编辑,您的编辑会对所有题库用户产生影响,请再次确认您的编辑是否有误。\n感谢您对医林拾薪题库建设的贡献!')
        if (confirmEdit) {
             try {
                var token = get_token(editUrl, editOrigin)
                if(!token[0]){
                    alert('获取用户TOKEN失败,请检查是否注册并登录或网络状态!\n如反复故障请先手动编辑并联系管理员。\n错误内容:' + e)
                    dismissModule()
                    return false
                }
            } catch (e) {
                alert('获取用户TOKEN失败,请检查是否注册并登录或网络状态!\n如反复故障请先手动编辑并联系管理员。\n错误内容:' + e)
                dismissModule()
                return false
            }
            try {
                var edit = editpage_common(false, editUrl, token, pageTitle, pageData.replacedText, undefined, 'tiku-edit|tiku-inline-editor'
                    , '来自网页内题目的题目编辑,题目类型:' + formatedData.type + ';题号:' + formatedData.source + ';题目:' + formatedData.title)
                if (!edit[0]){
                    alert('上传编辑失败,请检查是否注册并登录或网络状态!\n如反复故障请先手动编辑并联系管理员。\n错误类型:' + edit[1].code+'\n错误内容'+edit[1].info)
                    dismissModule()
                    return false
                }
            } catch (e) {
                alert('上传编辑失败,请检查是否注册并登录或网络状态!\n如反复故障请先手动编辑并联系管理员。\n错误内容:' + e)
                dismissModule()
                return false
            }
 
            if (edit) {
                location.reload()
             }
             }
         }
         }
     }
     }
}
     for(var i=0;i<inputBoxes.titlesNum;i++){
function formatEditText(json) {
        var card =  
    var result = {}
             $('<div class="card mt-2">'+
    var choices = {}
                '<div class="card-body p-2">'+
    var title = {}
                '</div>'+
    var answer = {}
             '</div>')
    var explain = {}
if(inputBoxes.titlesNum>1){
     for (var i in json) {
card.children('.card-body').append('<h6 class="card-title m-1">子题目-'+(i+1)+'</h5>')
        var data = formToJSON(i, true, 't')
}
        if ((result.id && result.type) === undefined) {
        card.children('.card-body').append(inputBoxes.title[i])
            result.id = data.id
        if('A,A2,A3,X'.includes(inputBoxes.type)){
             result.type = data.type
             for(k in inputBoxes.choices[i]){
            result.source = data.source
                 card.children('.card-body').append(inputBoxes.choices[i][k])
        }
    }
    console.log(result)
    var transor = {
        A: function () {
             for (var i in json) {
                var data = formToJSON(i, true, 't')
                if (data.key === 'choices') {
                    choices[data.value] = json[i]
                } else {
                    result[data.key] = json[i].replace(/\\/g, '\\' + '\\').replace(/"/g, '\\' + '"')
                }
                console.log(data)
            }
            JSON.stringify(choices).match(/(?<=\{)([^}]*)(?=\})/g)
            result.choices = RegExp.$1
            console.log(result)
        },
        A2 :function () {
            transor.A()
        },
        X: function () {
            transor.A()
        },
        B: function () {
             for (var i in json) {
                 var data = formToJSON(i, true, 't')
                eval(data.key + '[data.value] = json[i]')
                console.log(data)
             }
             }
            JSON.stringify(choices).match(/(?<=\{)([^}]*)(?=\})/g)
            result.choices = RegExp.$1
            result.title = arrayToString(dicValueToList(title))
            result.sourceRange = dicValueToList(title).length
            result.answer = arrayToString(dicValueToList(answer))
            result.explain = arrayToString(dicValueToList(explain))
            console.log(result)
        },
        C: function () {
            transor.B()
         }
         }
        card.children('.card-body').append(inputBoxes.answer[i])
        card.children('.card-body').append(inputBoxes.explain[i])
        form.append(card)
     }
     }
     transor[result.type]()
     var submitBtn = new OO.ui.ButtonWidget( {
label: '提交',
flags: [
'primary',
'progressive'
]
} )
var cancelBtn = new OO.ui.ButtonWidget( {
label: '取消',
flags: [
'destructive'
]
} )
submitBtn.$element.bind('click',function(){confirmEditAndCheckDifference(id)})
cancelBtn.$element.bind('click',function(){cancelEdit(id)})
var btns = $('<div class="m-1"></div>')
btns.append(submitBtn.$element, cancelBtn.$element)
form.append(btns,'<hr>')
    console.log(form)
    return form
}
function cancelEdit(id){
$('#'+id).fadeIn('fast')
$('#edit-'+id).fadeOut('fast')
setTimeout(function(){
    $("html,body").animate({scrollTop:$("#"+id).position().top},500)
    },250)
}
function confirmEditAndCheckDifference(id){
var formatedData = formatEditText(id)
var oldData = gDomTimuList().timu[id].dataJSON
var compareChanges = findChangedItem(oldData,formatedData )
console.log(formatedData, oldData, compareChanges)
var afterEditWikiText = JSONtoTemplate(formatedData)
console.log(afterEditWikiText)
var namespace = $('.mw-page-title-namespace').text()===''?'':$('.mw-page-title-namespace').text()+':'
var pageName = namespace+$('.mw-page-title-main').text()
//设置弹出框按钮功能
var processDialog = newProcessDialog()
var MyProcessDialog = processDialog.MyProcessDialog
$('.oo-ui-windowManager').remove()
var windowManager = new OO.ui.WindowManager();
$( document.body ).append( windowManager.$element );
MyProcessDialog.prototype.getActionProcess = function ( action ) {
    var dialog = this;
    if( action === 'submit'){
    submitChange(pageName,afterEditWikiText)
    }
    if ( action ) {
        return new OO.ui.Process( function () {
            dialog.close( { action: action } );
        } );
    }
    return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
};
openWindows(MyProcessDialog,windowManager)
//获取页面内容


     return result
getOriginalText(pageName,formatedData)
$('#newWikiText').html('<pre>'+afterEditWikiText+'</pre>')
}
function getOriginalText(pageTitle, timuData, editedText) {
var api = new mw.Api();
api.get( {
        "action": "query",
        "format": "json",
        "prop": "revisions",
        "titles": pageTitle,
        "utf8": 1,
        "rvprop": "content",
        "rvlimit": 1,
        "rvslots": "*",
        "rvdir": "older"
     } ).done( function ( data ) {
    var pages = data.query.pages
    console.log( data );
    if(pages[-1]===undefined){
    var wikitext = ''
    for(var i in pages){wikitext = pages[i].revisions[0].slots.main['*']}
    console.log(wikitext)
    var regMatchInner = new RegExp('(?<=\\{\\{' + timuData.type + '型题\\n\\|source=' + timuData.source + '\\n)[^}}]*(?=\\}\\}?)', 'g')
    var regMatchFull = new RegExp('(\\{\\{' + timuData.type + '型题\\n\\|source=' + timuData.source + '\\n)[^}}]*(\\}\\})', 'g')
   
    console.log(regMatchInner)
    var inner = wikitext.match(regMatchInner)
    sInnerMatchList(inner)
    console.log(inner)
var options = $('<div></div>')
if(inner.length>0){
for(var i=0;i<inner.length;i++){
if(i===0){
options.append($('<label style="display: flex;"><input checked type="radio" style="margin-right:5px" name="multiMatchInner" value="'+i+'"><pre>'+inner[i]+'</pre></label>'))
}else{
options.append($('<label style="display: flex;"><input type="radio" style="margin-right:5px" name="multiMatchInner" value="'+i+'"><pre>'+inner[i]+'</pre></label>'))
}
}
}
    $('#oldWikiText').html(options)
    }
   
} );
   
}
function submitChange(pageTitle,newText){
var selectedOldText = gInnerMatchList()[$('input:radio[name="multiMatchInner"]:checked').val()]
console.log(selectedOldText)
new mw.Api().edit(
    pageTitle,
    function ( revision ) {
        return {
            text: revision.content.replace( selectedOldText, newText ),
            summary: newText+'替换'+selectedOldText,
            tags:"tiku-inline-editor"
        };
    }
)
.then( function () {
alertDialog('成功',"编辑成功",'三秒后将自动刷新页面',false)
setTimeout(function(){location.reload()},3000)
    console.log( 'Saved!' );
} );
}
function findChangedItem(oldObj, newObj ){
var lenOld = dicLen(oldObj)
var lenNew = dicLen(newObj)
var result = []
for(var i in oldObj){
if(newObj[i] === undefined){
result.push({key:i,status:'deleted'})
}
if(oldObj[i]!==newObj[i]){
result.push({key:i,status:'changed'})
}
}
for(var i in newObj){
if(oldObj[i] === undefined){
result.push({key:i,status:'new'})
}
}
return result
}
}
function newProcessDialog(){
// Example: Creating and opening a process dialog window.
MyProcessDialog = function ( config ) {
    MyProcessDialog.super.call( this, config );
}
OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
MyProcessDialog.static.name = 'myProcessDialog';
MyProcessDialog.static.title = '上传前检查';
MyProcessDialog.static.actions = [
    { action: 'submit', label: '确认提交', flags: [ 'primary', 'progressive' ] },
    { label: '返回', flags: 'safe' }
];
MyProcessDialog.static.size='full'
MyProcessDialog.prototype.initialize = function () {
    MyProcessDialog.super.prototype.initialize.apply( this, arguments );
    this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
    this.content.$element.append( '<div id="process-header"></div><div id="process-content"><h3>编辑前的文本(如有多个可能是编号相同,请选择与本题相应文本)</h3><form id="oldWikiText"></form><h3>编辑后</h3><div id="newWikiText"></div></div><div id="process-append"></div>' );
    this.$body.append( this.content.$element );
};


function arrayToString(array) {
return {MyProcessDialog:MyProcessDialog}
    var text = ''
}
    for (var i = 0; i < array.length; i++) {
function openWindows(MyProcessDialog,windowManager){
        if (i != 0) {
var dialog = new MyProcessDialog();
            text += ','
windowManager.addWindows( [ dialog ] );
        }
windowManager.openWindow( dialog );
        text += '"' + array[i].trim() + '"'
return windowManager
    }
}
    return text
function formatEditText(id) {
var formData = formToJSON($('#edit-'+id),true)
var titleCount = formData['edit-titleCount']*1
console.log(titleCount,formData)
var sametypes = [ 'type','source','pos', 'inputbox', 'sourceRange', 'info']
var result = {
titlesList:[],
answersList:[],
explainsList:[],
}
for(var i=0;i<sametypes.length;i++){
if(formData['edit-'+sametypes[i]]!==undefined){
result[sametypes[i]] = formData['edit-'+sametypes[i]]
}
}
//处理title,answers,explain
for(var i=0;i<titleCount;i++){
result.titlesList.push(formData['edit-title-'+i])
result.answersList.push(formData['edit-answer-'+i])
result.explainsList.push(formData['edit-explain-'+i])
}
result.title = arrayToString(result.titlesList, false)
result.answer = arrayToString(result.answersList, false)
result.explain = arrayToString(result.explainsList, false)
//处理选项
console.log(getItemByPrefix(formData,'edit-choice-',true))
if(dicLen(getItemByPrefix(formData,'edit-choice-',true))>0){
result.choicesDicList=[],
result.choicesTextList=[],
result.choices=''
for(var i=0;i<titleCount;i++){
var optionsRelatedToThis = getItemByPrefix(formData,'edit-choice-'+i+'-',true)
result.choicesDicList.push(optionsRelatedToThis)
console.log(formData.type)
if(formData['edit-type']==='A3'){
result.choicesTextList.push('{'+JSON.stringify(optionsRelatedToThis).match(RegExp(/(?<=\{).+(?=\})/))[0]+'}')
}else{
console.log(JSON.stringify(optionsRelatedToThis))
result.choicesTextList.push(JSON.stringify(optionsRelatedToThis).match(RegExp(/(?<=\{).+(?=\})/))[0])
}
}
result.choices =  arrayToString(result.choicesTextList,false)
}
console.log(result)
return result
}
function getItemByPrefix(obj, prefix, removePrefix){
var result = {}
for(var key in obj){
if(key.includes(prefix)){
if(removePrefix){
result[key.replace(prefix,'')] = obj[key]
}else{
result[key] = obj[key]
}
}
}
return result
}
function arrayToString(array,needQuote){
needQuote = needQuote===undefined?'':needQuote
  if(needQuote){
    return '"' + array.join('","') + '"'
  }
  return array.join(',')
}
}


function dicValueToList(obj) {
function dicValueToList(obj) {
第270行: 第426行:
}
}


function formToJSON(selector, decode, mode) {
function formToJSON (selector, decode) {
    var result = {}
  var result = {}
    var data = ''
  var data
    if (mode === 's') {
  if (typeof selector === 'object') {
        data = $(selector).serialize()
    data = selector.serialize()
    } else if (mode === 't') {
  } else {
        data = selector
    data = $(selector).serialize()
    }
  }


    console.log(data)
  var dataSplitted = data.split('&')
    var dataSplitted = data.split('&')
  for (var i = 0; i < dataSplitted.length; i++) {
    for (var i = 0; i < dataSplitted.length; i++) {
    var value = dataSplitted[i].split('=')[1]
        var value = dataSplitted[i].split('=')[1]
    if (decode === true) {
        var key = dataSplitted[i].split('=')[0]
      value = decodeURIComponent(value)
        if (decode === true) {
            key = decodeURIComponent(key)
            value = decodeURIComponent(value)
        }
        result[key] = value
     }
     }
     return result
     result[dataSplitted[i].split('=')[0]] = value
  }
  return result
}
}


function JSONtoTemplate(json, templateName) {
function JSONtoTemplate(json, templateName) {
     var order = ['inputbox', 'title', 'choices', 'answer', 'explain', 'info']
     var order = ['pos', 'inputbox', 'sourceRange', 'title', 'choices', 'answer', 'explain', 'info']
     // var result = '{{'+templateName +'\n'
     // var result = '{{'+templateName +'\n'
     var result = ''
     var result = ''
第306行: 第459行:
}
}


function newInlineEditor(id, json, hideButton, addHr, parent) {
function alertDialog(title, message, btnLabel, disabled){
    parent = parent !== undefined ? parent : ''
     var messageDialog = new OO.ui.MessageDialog();
    if (addHr === undefined) {
    var windowManager = new OO.ui.WindowManager();
        addHr = true
     $( 'body' ).append( windowManager.$element );
    }
    windowManager.addWindows( [ messageDialog ] );
    if (hideButton === undefined) {
     windowManager.openWindow( messageDialog, {
        hideButton = false
         title:title,
    }
         message: message,
     var type = json.type
         actions: [
    var o = new Object()
             {
    o.temp = {
             action: 'accept',
        main: $('<form name="edit-' + id + '" id="edit-' + id + '" class="type' + type + ' timuEditContainer">' +
             label:  btnLabel,
            '<div style="border: 2px solid red">' +
             flags: 'primary',
            '<p style="color: red" class="editorTipsItem"><b>编辑器Tips</b><br></p>' +
             disabled: disabled,
            '<p class="editorTipsItem"><b>-->请勿同时编辑多个题目</b></p>' +
            '<p class="editorTipsItem"><b>-->本功能处于实验阶段,如果多次出现错误请使用手动编辑</b></p>' +
            '<p class="editorTipsItem"><b>-->本编辑器目前仅可编辑A1/A2, B, C, X型题</b></p></div></form>'),
        subject: $('<div class="subject"></div>'),
        range: $('<div class="sourceRange"></div>'),
        info: $('<textarea name="id=' + id + '&source=' + json.source + '&type=' + type + '&key=info" class="info oo-ui-inputWidget-input"></textarea>'),
        titleCon: $('<div class="titleContainer oo-ui-widget oo-ui-inputWidget oo-ui-textInputWidget oo-ui-textInputWidget-type-text oo-ui-widget-enabled"></div>'),
        source: $('<p class="source"></p>'),
        title: $('<textarea name="id=' + id + '&source=' + json.source + '&type=' + type + '&key=title" class="title-edit oo-ui-inputWidget-input" ></textarea>'),
        options: $('<div class="options"></div>'),
        btn: $('<div class="edit-button-set"><button class="btn button-primary confirm-edit-btn">确认更改</button>' +
            '<button style="margin-left: 5px" class="btn button-caution cancel-edit-btn">取  消</button></div>'),
        ansCon: $('<div id="ansContainer" class="ansContainer oo-ui-widget oo-ui-inputWidget oo-ui-textInputWidget oo-ui-textInputWidget-type-text oo-ui-widget-enabled"></div>'),
        correct: $('<p style="display:inline;"><b>正确答案:</b></p><br><textarea name="id=' + id + '&source=' + json.source + '&type=' + type + '&key=answer" class="correctAnswer oo-ui-inputWidget-input"></textarea><br>'),
        explain: $('<p style="display:inline;"><b>解析: </b></p><br><textarea name="id=' + id + '&source=' + json.source + '&type=' + type + '&key=explain" class="explain oo-ui-inputWidget-input"></textarea><br>'),
        select: $('<select class="button-small button-rounded button"></select>'),
        subTitle: $('<div id=""></div>')
    }
    o.hideButton = hideButton
    o.parent = parent
    if (type !== 'A3' && type !== 'PD') {
        o.temp.btn.children('.confirm-edit-btn').bind("click", function () {
            confirmEdit(id)
        })
     }
    o.temp.btn.children('.cancel-edit-btn').bind("click", function () {
        $('.edit-button-set').remove()
        $('#edit-' + id).remove()
        $('#' + id).fadeIn()
     })
    o.A = function () {
         this.temp.source.text(json.source)
        this.temp.title.html(json.title)
         this.temp.correct.nextAll('.correctAnswer').val(json.answer)
         this.temp.explain.nextAll('.explain').val(json.explain)
        var options = formatAnsDic(json.choices)
        for (var k in options) {
            var label = '<label id="' + k + '" class="oo-ui-widget oo-ui-inputWidget oo-ui-textInputWidget oo-ui-textInputWidget-type-text oo-ui-widget-enabled">' +
                '<p style="display: inline"><b>选项 ' + k + ':</b></p>' +
                '<input class="oo-ui-inputWidget-input option-input" style="display: inline" name="id=' + id + '&source=' + json.source + '&type=' + type + '&key=choices&value=' + k + '"  class="options-edit" type="text" value="' + options[k] + '" />' +
                '</label>'
             this.temp.options.append(label)
        }
        this.temp.titleCon.append(this.temp.source, this.temp.title)
        this.temp.ansCon.append(this.temp.correct, this.temp.explain)
        this.temp.subject.append(this.temp.titleCon, this.temp.options)
        this.temp.main.append(this.temp.subject, this.temp.ansCon)
 
        if (addHr) {
             this.temp.btn.append('<hr>')
        }
        this.temp.main = $('<div></div>').append(this.temp.main, this.temp.btn)
        console.log(this.temp.main)
        return this.temp.main
    }
    o.A2 = function () {
        this.temp.source.text(json.source)
        this.temp.title.html(json.title)
        this.temp.correct.nextAll('.correctAnswer').val(json.answer)
        this.temp.explain.nextAll('.explain').val(json.explain)
        var options = formatAnsDic(json.choices)
        for (var k in options) {
             var label = '<label id="' + k + '" class="oo-ui-widget oo-ui-inputWidget oo-ui-textInputWidget oo-ui-textInputWidget-type-text oo-ui-widget-enabled">' +
                '<p style="display: inline"><b>选项 ' + k + ':</b></p>' +
                '<input class="oo-ui-inputWidget-input option-input" style="display: inline" name="id=' + id + '&source=' + json.source + '&type=' + type + '&key=choices&value=' + k + '" class="options-edit" type="text" value="' + options[k] + '" />' +
                '</label>'
            this.temp.options.append(label)
        }
        this.temp.titleCon.append(this.temp.source, this.temp.title)
        this.temp.ansCon.append(this.temp.correct, this.temp.explain)
        this.temp.subject.append(this.temp.titleCon, this.temp.options)
        this.temp.main.append(this.temp.subject, this.temp.ansCon)
 
        if (addHr) {
             this.temp.btn.append('<hr>')
        }
        this.temp.main = $('<div></div>').append(this.temp.main, this.temp.btn)
        console.log(this.temp.main)
        return this.temp.main
    }
    o.A3 = function () {
        var subIDs = []
        var s = json.source * 1;
        var e = json.source * 1 + json.sourceRange * 1 - 1
        this.temp.range.text('第 ' + s + ' 到 ' + e + ' 题')
        for (var i = 0; i < json.title.length; i++) {
             subIDs.push(id + '-' + i)
            if (json.explain[i] == undefined) {
                json.explain[i] = '暂无解析'
             }
             }
            var data = {
         ]
                "type": "A",
         });
                "source": json.source + '-' + (i + 1),
     return windowManager
                "title": json.title[i],
                "answer": json.answer[i],
                "explain": json.explain[i],
                "choices": json.choices[i],
            }
            var newA = newTimu(id + '-' + i, data, true, false).A()
            render(id + '-' + i, 'A', newA, this.temp.titleCon)
        }
        o.temp.btn.bind("click", function () {
            showChoiceAnswer(subIDs, type, json.answer)
        })
        this.temp.info.text(json.info)
        this.temp.subject.append(this.temp.range, this.temp.info, this.temp.titleCon)
        if (!hideButton) {
            this.temp.main.append(this.temp.btn)
        }
        this.temp.main.append(this.temp.subject)
 
        if (addHr) {
            this.temp.btn.append('<hr>')
        }
        return this.temp.main
    }
    o.B = function () {
        var s = json.source * 1;
        var e = json.source * 1 + json.sourceRange * 1 - 1
        this.temp.range.text('第 ' + s + ' 到 ' + e + ' 题')
 
        var options = formatAnsDic(json.choices)
        for (var k in options) {
            var label = '<li id="' + k + '">' + k + ':<input class="oo-ui-inputWidget-input" name="id=' + id + '&source=' + json.source + '&type=' + type + '&key=choices&value=' + k + '"  class="options-edit" type="text" value="' + options[k] + '" /></li>'
            this.temp.options.append(label)
            this.temp.select.append('<option value="' + k + '">' + k + '</option>')
        }
        for (var i = 0; i < json.title.length; i++) {
            var reg1 = /\(\)/g
            var text = '<textarea name="id=' + id + '&source=' + json.source + '&type=' + type + '&key=title&value=' + i + '" class="title-edit oo-ui-inputWidget-input" >' + json.title[i] + '</textarea>'
            this.temp.subTitle.attr('id', id + '-' + i)
            this.temp.source.text(s + i)
            this.temp.subTitle.html(this.temp.source.prop("outerHTML") + text)
            this.temp.titleCon.append(this.temp.subTitle.prop("outerHTML"))
        }
        var correctAnsEditor = $('<div class="correctAnsEditor"><p><b>编辑答案</b></p></div>')
        for (var i = 0; i < json.answer.length; i++) {
            correctAnsEditor.append('<span>' + (s + i) + ':' + '<input name="id=' + id + '&source=' + json.source + '&type=' + type + '&key=answer&value=' + i + '" value="' + json.answer[i] + '"></span><br>')
        }
        this.temp.correct = correctAnsEditor
        var explain = $('<div class="correctExpEditor"><p><b>编辑解释</b></p></div>')
        for (var i = 0; i < json.explain.length; i++) {
            explain.append('<span>' + (s + i) + ':' + '<textarea class="title-edit oo-ui-inputWidget-input" name="id=' + id + '&source=' + json.source + '&type=' + type + '&key=explain&value=' + i + '">' + json.explain[i] + '</textarea></span><br>')
        }
        this.temp.explain = explain
 
        this.temp.subject.append(this.temp.range, this.temp.options, this.temp.titleCon)
 
         this.temp.ansCon.append(this.temp.correct, this.temp.explain)
        this.temp.main.append(this.temp.subject, this.temp.ansCon)
        if (addHr) {
            this.temp.btn.append('<hr>')
        }
        this.temp.main = $('<div></div>').append(this.temp.main, this.temp.btn)
        return this.temp.main
    }
    o.C = function () {
        var s = json.source * 1;
        var e = json.source * 1 + json.sourceRange * 1 - 1
        this.temp.range.text('第 ' + s + ' 到 ' + e + ' 题')
 
        var options = formatAnsDic(json.choices)
        for (var k in options) {
            var label = '<li id="' + k + '">' + k + ':<input class="oo-ui-inputWidget-input" name="id=' + id + '&source=' + json.source + '&type=' + type + '&key=choices&value=' + k + '"  class="options-edit" type="text" value="' + options[k] + '" /></li>'
            this.temp.options.append(label)
            this.temp.select.append('<option value="' + k + '">' + k + '</option>')
         }
        for (var i = 0; i < json.title.length; i++) {
            var reg1 = /\(\)/g
            var text = '<textarea name="id=' + id + '&type=' + type + '&source=' + json.source + '&key=title&value=' + i + '" class="title-edit oo-ui-inputWidget-input" >' + json.title[i] + '</textarea>'
            this.temp.subTitle.attr('id', id + '-' + i)
            this.temp.source.text(s + i)
            this.temp.subTitle.html(this.temp.source.prop("outerHTML") + text)
            this.temp.titleCon.append(this.temp.subTitle.prop("outerHTML"))
        }
        var correctAnsEditor = $('<div class="correctAnsEditor"><p><b>编辑答案</b></p></div>')
        for (var i = 0; i < json.answer.length; i++) {
            correctAnsEditor.append('<span>' + (s + i) + ':' + '<input name="id=' + id + '&type=' + type + '&source=' + json.source + '&key=answer&value=' + i + '" value="' + json.answer[i] + '"></span><br>')
        }
        this.temp.correct = correctAnsEditor
        var explain = $('<div class="correctExpEditor"><p><b>编辑解释</b></p></div>')
        for (var i = 0; i < json.explain.length; i++) {
            explain.append('<span>' + (s + i) + ':' + '<textarea class="title-edit oo-ui-inputWidget-input" name="id=' + id + '&source=' + json.source + '&type=' + type + '&key=explain&value=' + i + '">' + json.explain[i] + '</textarea></span><br>')
        }
        this.temp.explain = explain
        this.temp.subject.append(this.temp.range, this.temp.titleCon, this.temp.options)
        this.temp.ansCon.append(this.temp.correct, this.temp.explain)
        this.temp.main.append(this.temp.subject, this.temp.ansCon)
        if (addHr) {
            this.temp.btn.append('<hr>')
        }
        this.temp.main = $('<div></div>').append(this.temp.main, this.temp.btn)
        return this.temp.main
    }
    o.X = function () {
        this.temp.source.text(json.source)
        this.temp.title.text(json.title)
        this.temp.correct.nextAll('.correctAnswer').text(json.answer)
        this.temp.explain.nextAll('.correctAnswer').text(json.explain)
        var options = formatAnsDic(json.choices)
        for (var k in options) {
            var label = '<label id="' + k + '">' + k + ':<input class="oo-ui-inputWidget-input" name="id=' + id + '&source=' + json.source + '&type=' + type + '&key=choices&value=' + k + '"  class="options-edit" type="text" value="' + options[k] + '" /></label>'
            this.temp.options.append(label)
        }
 
        this.temp.titleCon.append(this.temp.source, this.temp.title)
        this.temp.ansCon.append(this.temp.correct, this.temp.explain)
        this.temp.subject.append(this.temp.titleCon, this.temp.options)
        this.temp.main.append(this.temp.subject, this.temp.ansCon)
        if (addHr) {
            this.temp.btn.append('<hr>')
        }
        this.temp.main = $('<div></div>').append(this.temp.main, this.temp.btn)
        return this.temp.main
    }
    o.PD = function () {
        this.temp.source.text(json.source)
        this.temp.title.text(json.title)
        this.temp.explain.nextAll('.correctAnswer').text(json.explain)
        var ans = ''
        if (json.answer == 'T' || json.answer == '正确' || json.answer == '1' || json.answer == '√') {
            ans = '正确'
        } else if (json.answer == 'F' || json.answer == '错误' || json.answer == '0' || json.answer == '×') {
            ans = '错误'
        }
        this.temp.correct.nextAll('.correctAnswer').text(ans)
        o.temp.btn.bind("click", function () {
            showChoiceAnswer(id, 'A', ans)
        })
        this.temp.options.append('<label id="正确" style="display: inline;"><input name="singelChoice-' + id + '" type="radio" value="正确" />正确</label>' +
            '<label id="错误" style="display: inline;"><input name="singelChoice-' + id + '" type="radio" value="错误" />错误</label>')
        this.temp.titleCon.append(this.temp.source, this.temp.title)
        this.temp.ansCon.append(this.temp.correct, this.temp.explain)
        this.temp.subject.append(this.temp.titleCon, this.temp.options)
        if (!hideButton) {
            this.temp.main.append(this.temp.btn)
        }
        this.temp.main.append(this.temp.subject, this.temp.ansCon)
 
        if (addHr) {
            this.temp.main.append('<hr>')
        }
        return this.temp.main
    }
    o.TK = function () {
        this.temp.source.text(json.source)
        var form = $('<form id="form-' + id + '" class="title"></form>')
        var pos = json.pos
        var posReg = new RegExp(pos, 'g')
        var posCount = json.title.match(posReg).length
        for (var i = 0; i < posCount; i++) {
            json.title = json.title.replace(pos, '<input name="' + id + '-' + i + '" id="' + id + '-' + i + '" type="text" form="form-' + id + '"/>')
        }
        form.html(json.title)
        this.temp.title.text(json.title)
        this.temp.correct.nextAll('.correctAnswer').text(json.answer)
        this.temp.explain.nextAll('.correctAnswer').text(json.explain)
 
        this.temp.titleCon.append(this.temp.source, form)
        this.temp.ansCon.append(this.temp.correct, this.temp.explain)
        this.temp.subject.append(this.temp.titleCon, this.temp.options)
        if (!hideButton) {
            this.temp.main.append(this.temp.btn)
        }
        this.temp.main.append(this.temp.subject, this.temp.ansCon)
 
        if (addHr) {
            this.temp.main.append('<hr>')
        }
        return this.temp.main
    }
    o.MJ = function () {
        this.temp.source.text(json.source)
        this.temp.title.html(json.title + ':<span class="blur" tabindex="0" style="display:inline;outline=0;" onclick="">' + json.answer + '</span>')
        this.temp.titleCon.append(this.temp.source, this.temp.title)
        this.temp.subject.append(this.temp.titleCon, this.temp.options)
        this.temp.main.append(this.temp.subject)
 
        if (addHr) {
            this.temp.main.append('<hr>')
        }
        return this.temp.main
    }
     return o
}
}


//获取某个页面的历史版本
function getPageRevision(url, title, pageCount) {
    pageCount = pageCount !== undefined ? pageCount : 1
    var PARAMS = {
        "action": "query",
        "format": "json",
        "prop": "revisions",
        "titles": title,
        "utf8": 1,
        "rvprop": "content",
        "rvlimit": pageCount,
        "rvdir": "older",
        'origin': '*',
    }
    var isSuccess = {}
    $.ajax(
        {
            url: url,
            method: "post",
            async: false,
            data: PARAMS,
            timeout: 5000,
            success: function (results) {
                if ('-1' in results.query.pages) {
                    console.log('===无此页面===')
                    isSuccess = {isSuccess: false, result: results}
                } else {
                    isSuccess = {isSuccess: true, result: results}
                }
            }
        })
    return isSuccess
}


function getLatestPageRevision(url, title) {
function sInnerMatchList(obj){
    var pages = getPageRevision(url, title, 1)
sessionStorage.setItem("edit-innerMatchList", JSON.stringify(obj));
    if (pages.isSuccess) {
        pages = pages.result.query.pages
        for (var key in pages) {
            var page = pages[key].revisions[0]['*']
        }
        return page
    } else {
        return false
    }
}
}
 
function gInnerMatchList(){
//编辑页面
return JSON.parse(sessionStorage.getItem("edit-innerMatchList"));
function editpage_common(async, url, token, title, content, model, tags, summary, message) {
    async = async !== undefined ? async : true
    model = model !== undefined ? model : 'wikitext'
    tags = tags !== undefined ? tags : ''
    summary = summary !== undefined ? summary : ''
    message = message !== undefined ? message : ''
    var isSuccess = false
    var PARAMS = {
        "action": "edit",
        "format": "json",
        "title": title,
        "text": content,
        "token": token,
        'contentmodel': model,
        "summary": summary,
        "tags": tags,
    }
    $.ajax({
        url: url,
        method: "post",
        async: async,
        data: PARAMS,
        timeout: 5000,
        success: function (results) {
            var apiResult = results['edit']['result']
            if (apiResult == "Success") {
                isSuccess = [true]
                console.log("===editpage_common 成功===")
                // newMessage('成功:上传成功','#88F888')
            } else {
                isSuccess = [false,results['error']]
            }
            processingOff()
        },
        error: function () {
            // newMessage('失败:上传失败','#ffaca6')
        }
 
    })
    return isSuccess
}
 
//获取token
function get_token(url, origin) {
    var isSuccess = [false, '0']
    var PARAMS = {
        "action": "query",
        "format": "json",
        'meta': 'tokens',
        'origin': origin,
    }
    $.ajax(
        {
            url: url,
            method: "post",
            async: false,
            data: PARAMS,
            timeout: 5000,
            success: function (results) {
                var token = results.query.tokens.csrftoken
                if (token.length >= 5) {
                    isSuccess = {isSuccess: true, token: token}
                }
            }
        })
    return isSuccess
}
}

2023年6月29日 (四) 15:04的最新版本

editUrl = 'https://www.medforest.cn/medf/api.php'
editOrigin = 'https://www.medforest.cn'
inlineEditorPageText = {}

function editThis(id) {
	$('#'+id).fadeOut('fast')
    var timuList = gDomTimuList()
	console.log(timuList)
	var order = timuList.order
	var timu = timuList.timu
    var dataJSON = timu[id].dataJSON
    var inputBoxes = loadPreview(dataJSON)
    
    var form = renderPreviewInputBoxes(inputBoxes, id)
    render(id, dataJSON.type, form,'#'+id,true)
    setTimeout(function(){
    $("html,body").animate({scrollTop:$("#edit-"+id).position().top},500)	
    },250)
    
}

function typeOfObj(object){
	return Object.prototype.toString.call(object);
}

function loadPreview(dataJSON){
    var timuJSON = dataJSON
    console.log(timuJSON)
    var order = ['source', 'pos', 'inputbox', 'sourceRange', 'title', 'choices', 'answer', 'explain', 'info']
    var chineseName = {
        'source':'编号'
        , 'pos':'挖空点符号'
        , 'inputbox':'是否显示输入框'
        , 'sourceRange':'子题目数'
        , 'title':'题目'
        , 'choices':'选项'
        , 'answer':'答案'
        , 'explain':'解释'
        , 'info':'信息'
    }
    var sametypes = [ 'pos', 'inputbox', 'sourceRange', 'info']
    var notsametypes = ['title', 'titlesList', 'optionsDic','optionsList', 'answer', 'answersList', 'explain', 'explainsList']
    var inputboxes = {
        type:timuJSON.type
        ,typeHTML:'<input style="display:none" name="edit-type" value="'+timuJSON.type+'">'
        ,source: '<p class="source">'+timuJSON.type+'型题 '+timuJSON.source+'</p><input style="display:none" name="edit-source" value="'+timuJSON.source+'">'
        ,title:[]
        ,choices:[]
        , answer:[]
        , explain:[]
    }
    for(var i=0;i<sametypes.length;i++){
        if(timuJSON[sametypes[i]]===undefined){
            continue
        }else if(sametypes[i]==='info'){
            inputboxes[sametypes[i]] = textareaGroup(chineseName[sametypes[i]],timuJSON[sametypes[i]],  'edit-'+sametypes[i])
        }else{
            inputboxes[sametypes[i]] = inputGroup(chineseName[sametypes[i]],timuJSON[sametypes[i]],  'edit-'+sametypes[i])
        }
        
    }

    //处理题目
    var isTitleList = typeOfObj(timuJSON.title)==='[object Array]' ? true:false
    var titles = !isTitleList ? [timuJSON.title] :  timuJSON.title
    console.log(titles )
    inputboxes.titlesNum = titles.length
    for(var i=0;i<titles.length;i++){
        inputboxes.title.push(textareaGroup(chineseName['title'],titles[i], 'edit-title-'+i))
    }

    //处理答案
    var isAnswerList = typeOfObj(timuJSON.answer)==='[object Array]' ? true:false
    var answers = !isAnswerList ? [timuJSON.answer] :  timuJSON.answer
    console.log(answers)
    inputboxes.answersNum = answers.length
    for(var i=0;i<inputboxes.titlesNum;i++){//此处以题目数为准,有几个题目生成几个答案和解释框
    	var answerText = answers[i]===undefined?'':answers[i]
        inputboxes.answer.push(inputGroup(chineseName['answer'],answerText, 'edit-answer-'+i))
    }

    //处理解释
    var isExplainList = typeOfObj(timuJSON.explain)==='[object Array]' ? true:false
    var explains = !isExplainList ? [timuJSON.explain] :  timuJSON.explain
    console.log(explains)
    inputboxes.explainsNum = explains.length
    for(var i=0;i<inputboxes.titlesNum;i++){//此处以题目数为准,有几个题目生成几个答案和解释框
    	var explainText = explains[i]===undefined?'':explains[i]
        inputboxes.explain.push(textareaGroup(chineseName['explain'],explainText, 'edit-explain-'+i))
    }

    //处理选项
    var isOptionList = typeOfObj(timuJSON.choices)==='[object Array]' ? true:false
    var options = !isOptionList ? [timuJSON.choices] :  timuJSON.choices
    console.log(options)
    for(var i=0;i<options.length;i++){
        var dic = options[i]
        for(var k in dic){
            options[i][k] = inputGroup(chineseName['choices']+' '+k,options[i][k], 'edit-choice-'+i+'-'+k)
        }
    }
    //检测是否有选项,如果没有则不加
    if(options.length>0){
    	inputboxes.choices = options
    }
    
    console.log(inputboxes)

    return inputboxes
}

function inputGroup(label, value, name, id, classes , placeholder){
	id = id === undefined ?'':id
	classes = classes ===undefined ?'':classes
	placeholder = placeholder===undefined ? '':placeholder
    return $('<div class="mb-1">'+
    '<div class="input-group">'+
    '<div class="input-group-prepend">'+
    ' <div class="input-group-text"><b>'+label+'</b></div>'+
    '</div>'+
    '<input type="text" class="m-0 form-control '+classes+'" id="'+id+'" name="'+name+'" style="height:25px" placeholder="'+ placeholder +'" value="'+value+'">'+
    '</div>'+
    '</div>')
}
function textareaGroup(label, value, name, id, classes){
	id = id === undefined ?'':id
	classes = classes ===undefined ?'':classes
    return $('<div class="mb-1"><div class="input-group">'+
    '<div class="input-group-prepend">'+
      '<span class="input-group-text"><b>'+label+'</b></span>'+
    '</div>'+
        '<textarea class="form-control" '+classes+'" id="'+id+'" name="'+name+'">'+value+'</textarea>'+
    '</div></div>')
}
function renderPreviewInputBoxes(inputBoxes,id){
	console.log(id,inputBoxes)
    var form = $('<form id="edit-'+id+'" name="edit-'+id+'"><input name="edit-titleCount" style="display:none" value="'+inputBoxes.titlesNum+'">'+
    '<br>正在编辑:</form>')
    console.log(form)
    var sametypes = ['typeHTML','source','pos', 'inputbox', 'sourceRange', 'info']
    var differenttypes = ['title', 'choices', 'answer', 'explain']
    for(var i=0;i<sametypes.length;i++){
        form.append(inputBoxes[sametypes[i]])
    }
    if('B,C'.includes(inputBoxes.type)){
        for(var i in inputBoxes.choices){
            console.log(i)
            for(k in inputBoxes.choices[i]){
              form.append(inputBoxes.choices[i][k])  
            }
        }
    }
    for(var i=0;i<inputBoxes.titlesNum;i++){
        var card = 
            $('<div class="card mt-2">'+
                '<div class="card-body p-2">'+
                '</div>'+
            '</div>')
		if(inputBoxes.titlesNum>1){
			card.children('.card-body').append('<h6 class="card-title m-1">子题目-'+(i+1)+'</h5>')
		}
        card.children('.card-body').append(inputBoxes.title[i])
        if('A,A2,A3,X'.includes(inputBoxes.type)){
            for(k in inputBoxes.choices[i]){
                card.children('.card-body').append(inputBoxes.choices[i][k])  
            }
        }
        card.children('.card-body').append(inputBoxes.answer[i])
        card.children('.card-body').append(inputBoxes.explain[i])
        form.append(card)
    }
    var submitBtn = new OO.ui.ButtonWidget( {
	label: '提交',
	flags: [
		'primary',
		'progressive'
			]
		} )
	var cancelBtn = new OO.ui.ButtonWidget( {
	label: '取消',
	flags: [
		'destructive'
			]
		} )
	submitBtn.$element.bind('click',function(){confirmEditAndCheckDifference(id)})
	cancelBtn.$element.bind('click',function(){cancelEdit(id)})
	var btns = $('<div class="m-1"></div>')
	btns.append(submitBtn.$element, cancelBtn.$element)
	form.append(btns,'<hr>')
    console.log(form)
    return form
}
function cancelEdit(id){
	$('#'+id).fadeIn('fast')
	$('#edit-'+id).fadeOut('fast')
	setTimeout(function(){
    	$("html,body").animate({scrollTop:$("#"+id).position().top},500)	
    },250)
}
function confirmEditAndCheckDifference(id){
	var formatedData = formatEditText(id)
	var oldData = gDomTimuList().timu[id].dataJSON
	var compareChanges = findChangedItem(oldData,formatedData )
	console.log(formatedData, oldData, compareChanges)
	var afterEditWikiText = JSONtoTemplate(formatedData)
	console.log(afterEditWikiText)
	var namespace = $('.mw-page-title-namespace').text()===''?'':$('.mw-page-title-namespace').text()+':'
	var pageName = namespace+$('.mw-page-title-main').text()
	//设置弹出框按钮功能
	var processDialog = newProcessDialog()
	var MyProcessDialog = processDialog.MyProcessDialog
	$('.oo-ui-windowManager').remove()
	var windowManager = new OO.ui.WindowManager();
	$( document.body ).append( windowManager.$element );
	
	MyProcessDialog.prototype.getActionProcess = function ( action ) {
	    var dialog = this;
	    if( action === 'submit'){
	    	submitChange(pageName,afterEditWikiText)
	    }
	    if ( action ) {
	        return new OO.ui.Process( function () {
	            dialog.close( { action: action } );
	        } );
	    }
	    return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
	};
	openWindows(MyProcessDialog,windowManager)
	
	//获取页面内容

	getOriginalText(pageName,formatedData)
	$('#newWikiText').html('<pre>'+afterEditWikiText+'</pre>')
}
function getOriginalText(pageTitle, timuData, editedText) {
	var api = new mw.Api();
	api.get( {
        "action": "query",
        "format": "json",
        "prop": "revisions",
        "titles": pageTitle,
        "utf8": 1,
        "rvprop": "content",
        "rvlimit": 1,
        "rvslots": "*",
        "rvdir": "older"
    } ).done( function ( data ) {
    	var pages = data.query.pages
	    console.log( data );
	    if(pages[-1]===undefined){
	    	var wikitext = ''
	    	for(var i in pages){wikitext = pages[i].revisions[0].slots.main['*']}
	    	console.log(wikitext)
	    	var regMatchInner = new RegExp('(?<=\\{\\{' + timuData.type + '型题\\n\\|source=' + timuData.source + '\\n)[^}}]*(?=\\}\\}?)', 'g')
		    var regMatchFull = new RegExp('(\\{\\{' + timuData.type + '型题\\n\\|source=' + timuData.source + '\\n)[^}}]*(\\}\\})', 'g')
		    
		    console.log(regMatchInner)
		    var inner = wikitext.match(regMatchInner)
		    sInnerMatchList(inner)
		    console.log(inner)
			var options = $('<div></div>')
			if(inner.length>0){
				for(var i=0;i<inner.length;i++){
					if(i===0){
						options.append($('<label style="display: flex;"><input checked type="radio" style="margin-right:5px" name="multiMatchInner" value="'+i+'"><pre>'+inner[i]+'</pre></label>'))
					}else{
						options.append($('<label style="display: flex;"><input type="radio" style="margin-right:5px" name="multiMatchInner" value="'+i+'"><pre>'+inner[i]+'</pre></label>'))
					}
				}
			}
			
		    $('#oldWikiText').html(options)
	    }
	    
	} );
    
}
function submitChange(pageTitle,newText){
	var selectedOldText = gInnerMatchList()[$('input:radio[name="multiMatchInner"]:checked').val()]
	console.log(selectedOldText)
	new mw.Api().edit(
    pageTitle,
    function ( revision ) {
        return {
            text: revision.content.replace( selectedOldText, newText ),
            summary: newText+'替换'+selectedOldText,
            tags:"tiku-inline-editor"
	        };
	    }
	)
	.then( function () {
		alertDialog('成功',"编辑成功",'三秒后将自动刷新页面',false)
		setTimeout(function(){location.reload()},3000)
	    console.log( 'Saved!' );
	} );
}
function findChangedItem(oldObj, newObj ){
	var lenOld = dicLen(oldObj)
	var lenNew = dicLen(newObj)
	var result = []
	for(var i in oldObj){
		if(newObj[i] === undefined){
			result.push({key:i,status:'deleted'})
		}
		if(oldObj[i]!==newObj[i]){
			result.push({key:i,status:'changed'})
		}
	}
	for(var i in newObj){
		if(oldObj[i] === undefined){
			result.push({key:i,status:'new'})
		}
	}
	return result
}
function newProcessDialog(){
	// Example: Creating and opening a process dialog window.
	MyProcessDialog = function ( config ) {
	    MyProcessDialog.super.call( this, config );
	}
	OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
	
	MyProcessDialog.static.name = 'myProcessDialog';
	MyProcessDialog.static.title = '上传前检查';
	MyProcessDialog.static.actions = [
	    { action: 'submit', label: '确认提交', flags: [ 'primary', 'progressive' ] },
	    { label: '返回', flags: 'safe' }
	];
	MyProcessDialog.static.size='full'
	
	MyProcessDialog.prototype.initialize = function () {
	    MyProcessDialog.super.prototype.initialize.apply( this, arguments );
	    this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
	    this.content.$element.append( '<div id="process-header"></div><div id="process-content"><h3>编辑前的文本(如有多个可能是编号相同,请选择与本题相应文本)</h3><form id="oldWikiText"></form><h3>编辑后</h3><div id="newWikiText"></div></div><div id="process-append"></div>' );
	    this.$body.append( this.content.$element );
	};

	return {MyProcessDialog:MyProcessDialog}
}
function openWindows(MyProcessDialog,windowManager){
	var dialog = new MyProcessDialog();
	windowManager.addWindows( [ dialog ] );
	windowManager.openWindow( dialog );
	return windowManager
}
function formatEditText(id) {
	var formData = formToJSON($('#edit-'+id),true)
	var titleCount = formData['edit-titleCount']*1
	console.log(titleCount,formData)
	var sametypes = [ 'type','source','pos', 'inputbox', 'sourceRange', 'info']
	
	var result = {
		titlesList:[],
		answersList:[],
		explainsList:[],
	}
	for(var i=0;i<sametypes.length;i++){
		if(formData['edit-'+sametypes[i]]!==undefined){
			result[sametypes[i]] = formData['edit-'+sametypes[i]]
		}
	}
	
	//处理title,answers,explain
	for(var i=0;i<titleCount;i++){
		result.titlesList.push(formData['edit-title-'+i])
		result.answersList.push(formData['edit-answer-'+i])
		result.explainsList.push(formData['edit-explain-'+i])
	}
	result.title = arrayToString(result.titlesList, false)
	result.answer = arrayToString(result.answersList, false)
	result.explain = arrayToString(result.explainsList, false)
	
	//处理选项
	console.log(getItemByPrefix(formData,'edit-choice-',true))
	if(dicLen(getItemByPrefix(formData,'edit-choice-',true))>0){
		result.choicesDicList=[],
		result.choicesTextList=[],
		result.choices=''
		for(var i=0;i<titleCount;i++){
			var optionsRelatedToThis = getItemByPrefix(formData,'edit-choice-'+i+'-',true)
			result.choicesDicList.push(optionsRelatedToThis)
			console.log(formData.type)
			if(formData['edit-type']==='A3'){
				result.choicesTextList.push('{'+JSON.stringify(optionsRelatedToThis).match(RegExp(/(?<=\{).+(?=\})/))[0]+'}')
			}else{
				console.log(JSON.stringify(optionsRelatedToThis))
				result.choicesTextList.push(JSON.stringify(optionsRelatedToThis).match(RegExp(/(?<=\{).+(?=\})/))[0])
			}
	
		}
	result.choices =  arrayToString(result.choicesTextList,false)
	}
	
	console.log(result)
	return result
}
function getItemByPrefix(obj, prefix, removePrefix){
	var result = {}
	for(var key in obj){
		if(key.includes(prefix)){
			if(removePrefix){
				result[key.replace(prefix,'')] = obj[key]
			}else{
				result[key] = obj[key]
			}
		}
	}
	return result
}
function arrayToString(array,needQuote){
	needQuote = needQuote===undefined?'':needQuote
  if(needQuote){
    return '"' +  array.join('","') + '"'
  }
  return array.join(',')
}



function dicValueToList(obj) {
    var result = []
    for (var i in obj) {
        result.push(obj[i])
    }
    return result
}

function formToJSON (selector, decode) {
  var result = {}
  var data
  if (typeof selector === 'object') {
    data = selector.serialize()
  } else {
    data = $(selector).serialize()
  }

  var dataSplitted = data.split('&')
  for (var i = 0; i < dataSplitted.length; i++) {
    var value = dataSplitted[i].split('=')[1]
    if (decode === true) {
      value = decodeURIComponent(value)
    }
    result[dataSplitted[i].split('=')[0]] = value
  }
  return result
}

function JSONtoTemplate(json, templateName) {
    var order = ['pos', 'inputbox', 'sourceRange', 'title', 'choices', 'answer', 'explain', 'info']
    // var result = '{{'+templateName +'\n'
    var result = ''
    for (var i = 0; i < order.length; i++) {
        if (json[order[i]] !== undefined) {
            result += '|' + order[i] + '=' + json[order[i]].replace('\n') + '\n'
        }
    }
    // result += '}}\n\n'
    return result
}

function alertDialog(title, message, btnLabel, disabled){
    var messageDialog = new OO.ui.MessageDialog();
    var windowManager = new OO.ui.WindowManager();
    $( 'body' ).append( windowManager.$element );
    windowManager.addWindows( [ messageDialog ] );
    windowManager.openWindow( messageDialog, {
        title:title,
        message: message,
        actions: [
            {
            action: 'accept',
            label:  btnLabel,
            flags: 'primary',
            disabled: disabled,
            }
        ]
        });
    return windowManager
}


function sInnerMatchList(obj){
	sessionStorage.setItem("edit-innerMatchList", JSON.stringify(obj));
}
function gInnerMatchList(){
	return JSON.parse(sessionStorage.getItem("edit-innerMatchList"));
}