const $ = require("jquery");
const { openNewWin,imageUrlPrefix } = require('./promise.js');
const { bindTipsEvent } = require('./popupEdit.js');

function renderRecommendInfo(showNum,className,title,data, hasInfo, type, position) {
    let showNumCopy = showNum || 5
    const dataLen = data.length
    const str = `<div class="recommendInfoWrapper ${className}">
                    <h4><i></i>${title}</h4>
                    <div class="recommendInfoBox">
                        <div class="clearfix recommendInfoItemBox ${className + 'box'}">
                        </div>
                    </div>
                </div>`
    $('.recommendWrap').append(str)
    let dataShort
    if(showNumCopy&& dataLen > showNumCopy) {
        dataShort = data.slice(0, showNumCopy)
    } else {
        dataShort = data
    }
    let childrenNodeStrShort = ''
    let childrenNodeStrLong = ''
    if(hasInfo) {
        for (let i = 0; i < dataShort.length; i++) {
            childrenNodeStrShort += `<span class="recommendInfoItem recommendInfoItemHasInfo">
                                    ${dataShort[i].name}
                                    <span  title="点击i图标可查看详细说明" class="infoMsg" data-name=${dataShort[i].name}></span>
                                </span>`
        }
        for (let i = 0; i < data.length; i++) {
            childrenNodeStrLong += `<span class="recommendInfoItem recommendInfoItemHasInfo">
                                    ${data[i].name}
                                    <span  title="点击i图标可查看详细说明" class="infoMsg" data-name=${data[i].name}></span>
                                </span>`
        }
    } else {
        for (let i = 0; i < dataShort.length; i++) {
            childrenNodeStrShort += `<span class="recommendInfoItem" data-name="${dataShort[i].name}">
                                    ${dataShort[i].name}
                                </span>`
        }
        for (let i = 0; i < data.length; i++) {
            childrenNodeStrLong += `<span class="recommendInfoItem" data-name="${data[i].name}">
                                    ${data[i].name}
                                </span>`
        }
    }
    if(!childrenNodeStrShort) {
        childrenNodeStrShort='<span class="recommendNull">暂无推荐</span>'
    }
    
    $('.'+className + 'box').append(childrenNodeStrShort)
    $('.'+className + 'box' +' .infoMsg').on('click', function(){
        const infoMsgName = $(this).attr('data-name')
        openNewWin(`information.html?type=${encodeURIComponent(type)}&position=${encodeURIComponent(position)}&name=${encodeURIComponent(infoMsgName)}`)
    })
    if(dataLen > showNumCopy) {
        slideToggle($("."+className+"box"), childrenNodeStrShort,childrenNodeStrLong)
    }
}

function renderMultRecommendInfo(className,title,data, hasInfo, type, position) {
    const str = `<div class="recommendInfoWrapper ${className}">
                    <h4><i></i>${title}</h4>
                    <div class="recommendInfoBox ${className + 'box'}"></div>
                </div>`
    $('.recommendWrap').append(str)
    let hasDataNum = 0
    for(let i = 0; i < data.length; i++) {
        const showNum = data[i].showNum || 5
        const dataLen = data[i].data.length
        if(dataLen === 0) {
            continue
        }
        hasDataNum++
        if(hasDataNum > 1) {
            $('.'+className + 'box').append('<div class="line"></div>')
        }
        let childrenNodeBoxStr  = `<div class="labAndPacsBox ${data[i].className} clearfix"> </div>`
        let childrenNodeStrShort =  `<span class="labAndPacsTitle">${data[i].title}<i></i></span>`
        let childrenNodeStrLong =  `<span class="labAndPacsTitle">${data[i].title}<i></i></span>`
        let dataShort
        if(showNum&& dataLen > showNum) {
            dataShort = data[i].data.slice(0, showNum)
        } else {
            dataShort = data[i].data
        }
        for(let j = 0; j < dataShort.length; j++) {
            childrenNodeStrShort += `<span class="labAndPacsItem">${dataShort[j].name}</span>`
        }
        for(let j = 0; j < data[i].data.length; j++) {
            childrenNodeStrLong += `<span class="labAndPacsItem">${data[i].data[j].name}</span>`
        }
        if(data[i].data.length == 0) {
            childrenNodeStrShort +='<span class="recommendNull">暂无推荐</span>'
        }
        $('.'+className + 'box').append(childrenNodeBoxStr)
        $('.'+data[i].className).append(childrenNodeStrShort)
        if(dataLen > showNum) {
            slideToggle($("."+data[i].className), childrenNodeStrShort,childrenNodeStrLong)
        }
    }

}

function renderTipsInfo(className,title, data) {
    const str = `<div class="recommendInfoWrapper ${className}">
                    <h4><i></i>${title}</h4>
                    <div class="recommendInfoBox clearfix ${className + 'box'} disCopy"></div>
                </div>`
    $('.recommendWrap').append(str)
    if(data.length > 0) {
        for(let i = 0; i < data.length; i++) {
            renderTipsInfoMsg('tipsInfo'+i, data[i], data[i].details, className+'box')

        }
    } else {
        // renderTipsInfoMsg('tipsInfo', data.name, data.details, className+'box')
        $('.' + className+'box').append('<p class="TipsInfoNull">暂无数据</p>')
    }
    $('.' + className + 'box' + ' img').bind('contextmenu', function(){
        return false
    })
}

function renderKnowledgeInfo(className,title, data) {
    const str = `<div class="recommendInfoWrapper ${className}">
                    <h4><i></i>${title}</h4>
                    <div class="recommendInfoBox clearfix ${className + 'box'}"></div>
                </div>`
    $('.recommendWrap').append(str)
    $('.' + className+'box').append('<p class="TipsInfoNull staticWin">'+data+'</p>')
    $('.'+className+' .staticWin' ).on('click', function(){
        openNewWin(`staticSearch.html?msg=${encodeURIComponent(JSON.stringify(msg))}`)
    })
}

function renderScaleInfo(className,title, data) {
    const str = `<div class="recommendInfoWrapper ${className}">
                    <h4><i></i>${title}</h4>
                    <div class="recommendInfoBox clearfix ${className + 'box'}"></div>
                </div>`
    $('.recommendWrap').append(str)
    $('.' + className+'box').append('<p class="TipsInfoNull staticWin">'+data+'</p>')
    $('.'+className+' .staticWin' ).on('click', function(){
        openNewWin(`staticSearch.html?msg=${encodeURIComponent(JSON.stringify(msg))}`)
    })
}

function renderTipsInfoMsg(className,item,data, parentNode) {
    const childrenNodeBoxStr = `
        <div class = "treatItemBox ${className + 'box'} disCopy">
            <p class="treatItemTitle">${item.name} <span class="moreInfo" data-name="${item.name}" data-type="${item.type}"}>详情</span></p>
            <p class="${className + 'Info'} clearfix"></p>
        </div>
    `
    $('.' + parentNode).append(childrenNodeBoxStr)
    let dataStr = ``
    if(data.length === 0) {
        dataStr += `<p class="TipsInfoNull">暂无数据</p>
                            `
    } else {
        for(let i = 0; i < data.length; i++) {
            dataStr += `<p>${data[i].title}</p>
                                    ${data[i].content.replace(/{imageUrlPrefix}/g, imageUrlPrefix)}
                        `
        }
    }
    $('.' + className+'Info').html(dataStr)
}

function renderTreat(className,title, data) {
    const str = `<div class="recommendInfoWrapper ${className}">
                    <h4><i></i>${title}${msg.diseaseName?'('+msg.diseaseName.uniqueName+')':''}</h4>
                    <div class="recommendInfoBox clearfix ${className + 'box'}"></div>
                </div>`
    $('.recommendWrap').append(str)
    const commonTreatmentInfo = data.commonTreatment&&data.commonTreatment.content || ""
    const treatmentList = data.treatmentPlan || []
    renderTreatText('commonTreatment', '一般治疗', commonTreatmentInfo, className+'box')
    renderTreatDrug('drugTreatment', '推荐药物', treatmentList, className+'box')
}

function renderTreatText(className,title,data, parentNode) {
    const childrenNodeBoxStr = `
        <div class = "treatItemBox ${className + 'box'} disCopy">
            <p class="treatItemTitle">${title}</p>
            <p class="${className + 'Info'} clearfix"></p>
        </div>
    `
    $('.' + parentNode).append(childrenNodeBoxStr)
    if(!data) {
        data = '<span class="recommendNull">暂无推荐</span>'
    }
    $('.' + className+'Info').html(data)
    var commonTreatHeight = $(".commonTreatmentInfo").height()
    if(commonTreatHeight > 75){
        $(".commonTreatmentInfo").addClass('commonTreatmentInfoLimit').append('<span class="slideDown">更多 <i></i></span>')
    }
    $(".treatItemBox").on('click',".slideDown",function(){
        openNewWin(`treatplan.html?msg=${encodeURIComponent(JSON.stringify(msg))}`)
    })
    $('.' + className + 'Info' + ' img').bind('contextmenu', function(){
        return false
    })
}
function renderTreatDrug(className,title,data, parentNode) {
    const childrenNodeBoxStr = `
        <div class = "treatItemBox ${className + 'box'}">
            <p class="treatItemTitle">${title} ${data.length ==0 ?'':'<span class="slideDown">更多 <i></i></span>'}</p>
            <p class="${className + 'Info'}"></p>
        </div>
    `
    $('.' + parentNode).append(childrenNodeBoxStr)
    if(data.length ==0) {
        $('.' + className+'Info').append('<span class="recommendNull">暂无推荐</span>')
    }
    for(let i = 0; i <  data.length; i++) {
        let childrenNodeStr =`<div class = "drugTreatmentInfoItemBox">
            <p class="diagTitle"><i></i>${data[i].title}</p>`
            //二级标题暂时不放
            // for(let j = 0; j < data[i].meditionDetails.length; j++) {
            //     if(data[i].meditionDetails[j].description) {
            //         childrenNodeStr += `<p class="diagDescription">${data[i].meditionDetails[j].description}</p>`
            //     }
            // }
            childrenNodeStr +=`</div>`
        $('.' + className+'Info').append(childrenNodeStr)
    }
    $(".treatItemTitle").on('click',".slideDown",function(){
        openNewWin(`treatplan.html?msg=${encodeURIComponent(JSON.stringify(msg))}`)
    })
    // for(let i = 0; i < data.length; i++) {
    //     let childrenNodeStr = `<p class="drugTreatmentInfoItemBox">
    //         ${i+1}.${data[i].bigdrugsName}${data[i].subdrugsName&&"("+data[i].subdrugsName+")"}:`
        // for (let j = 0; j < data[i].medicitionsList.length; j++) {
        //     childrenNodeStr += `<span class="durgNameBox ${(data[i].medicitionsList[j].forbidden == '2' ? 'medicineWaringDis' : '' )}"><span class="durgName">${data[i].medicitionsList[j].medicitionName}</span>`
        //     if(data[i].medicitionsList[j].forbidden == '1') {
        //         childrenNodeStr += `<span class="medicineWaring">慎用</span>`
        //     } else if(data[i].medicitionsList[j].forbidden == '2') {
        //         childrenNodeStr += `<span  class="medicineWaringDisMsg">禁用</span>`
        //     }
        //     childrenNodeStr += `<span  title="点击i图标可查看详细说明" class="infoMsg" data-name=${data[i].medicitionsList[j].medicitionName}></span>`
        //     if(j !== data[i].medicitionsList.length-1) {
        //         childrenNodeStr += ','
        //     }
        //     childrenNodeStr += '</span></span>'
        //     //隐藏使用率
        //     // childrenNodeStr += `<span class="${(data[i].medicitionsList[j].forbidden == '2' ? 'medicineWaringDis' : '' )}">使用率${data[i].medicitionsList[j].rate}</span>`
        //     // if(j === data[i].medicitionsList.length-1) {
        //     //     childrenNodeStr += ';'
        //     // } else {
        //     //     childrenNodeStr += ','
        //     // }
        // }
        // childrenNodeStr += ` </p>`
        // $('.' + className+'Info').append(childrenNodeStr)
    // }
    // $('.' + className+'Info'+ ' .infoMsg').on('click', function(){
    //     const infoMsgName = $(this).attr('data-name')
    //     openNewWin(`information.html?type=8&position=5&name=${infoMsgName}`)
    // })
    // var treatList = $(".drugTreatmentInfo").find(".drugTreatmentInfoItemBox")
    // for(var h = 0;h < treatList.length;h++){ 
    //     if($(treatList[h]).height() > 25){
    //     $(treatList[h]).addClass('recommendInfoItemBoxLimit').append('<span class="slideDown">更多 <i></i></span>')
    //     }
    //     $(".drugTreatmentInfo").on('click',".slideDown",function(){
    //     $(this).parents(".drugTreatmentInfoItemBox ").removeClass("recommendInfoItemBoxLimit").append('<span class="slideup">收起 <i></i></span>')
    //     $(this).remove()
    //     })
    //     $(".drugTreatmentInfo").on('click',".slideup",function(){
    //     $(this).parents(".drugTreatmentInfoItemBox ").addClass("recommendInfoItemBoxLimit").append('<span class="slideDown">更多 <i></i></span>')
    //     $(this).remove()
    //     })
    // }
}

function renderRecommendConditTips(className,title,data) {
    const str = `<div class="recommendInfoWrapper ${className}">
                    <h4><i></i>${title}</h4>
                    <div class="recommendInfoBox  ${className + 'box'}"></div>
                </div>`
    $('.recommendWrap').append(str)
    if(data.length == 0) {
        $("."+className+"box").append('<span class="recommendNull">暂无推荐</span>')
    };
    //let names = [];
    for(var k = 0;k < data.length;k++){
        let tmpBq = data[k];
        let hasSritical = false
        let tmpBqStr;
        if(tmpBq.details) {
            for(let i = 0; i < tmpBq.details.length; i++) {
                if(tmpBq.details[i].type == 4) {
                    hasSritical= true
                }
            }
        }
        if(hasSritical) {
            /*if(names.includes(tmpBq.name)){    //name相同去重
              tmpBqStr='';
            }else{
              names.push(tmpBq.name);*/
              tmpBqStr = `<p class="mayIllness">
              <span class="sriticalNameBox"><span class="sriticalName">${tmpBq.name}</span>
                </span>
            </span></p>`
            //}
        } else {
            tmpBqStr = `<p class="mayIllness">
                            患者可能有 <span class="diagNameBox"><span class="diagName">${tmpBq.name}:</span>
                                <span title="点击该名称可看详细说明" class="infoMsg" data-name=${tmpBq.name}></span>
                            </span>
                        </span></p>`
        }
         
        var tmpBqDetailStr = ''
        for(var m = 0;m < tmpBq.details.length;m++){
          var tmpBqDetail = tmpBq.details[m]
          if(tmpBqDetail.type == 1){
            tmpBqDetailStr+=`<span data-scaleName=${tmpBqDetail.content.name} class="illnessTable">【${tmpBqDetail.content.name}】</span>`
          }
          if(tmpBqDetail.type == 2){
            var deepDetailName = `<div class="modalTitle">${tmpBqDetail.content.name}<i class="closeModal"></i></div>`
            var deepDetailStr = ''
            var deepDetailResultStr = ''
            for(var n = 0;n < tmpBqDetail.content.details.length;n++){
              var deepDetail = tmpBqDetail.content.details[n]
              if(deepDetail.controlType == 2){//0-radio,1-checkbox,2-text,3-dropdownlist
                if(deepDetail.isShow == 0) {
                    deepDetailStr+=`<li class="radioCheck"><span class="modalMaintltle">${deepDetail.name}: </span>${deepDetail.value} ${deepDetail.uint}</li>`
                } else {
                    deepDetailStr+=`<li class="radioCheck"><span class="modalMaintltle">请输入${deepDetail.name}: </span><input type="text" class="${tmpBqDetail.content.name+deepDetail.name}" ${deepDetail.isShow=='0' ? 'readonly':''} placeholder="请输入" value=${deepDetail.value}><i class="uint">${deepDetail.uint}</i></li>`
                }
              }
              if(deepDetail.controlType == 0){
                let tooDeepDetailStr = ''
                for(var f = 0;f<deepDetail.details.length;f++){
                  var tooDeepDetail = deepDetail.details[f]
                  if(deepDetail.isShow == '0'){
                    if(tooDeepDetail.state == 1) {
                      tooDeepDetailStr+='<li class="radioChecks" data-select="'+(tooDeepDetail.state == 1?"select":"")+'"><span>'+tooDeepDetail.detailName+'</span></li>'
                    }
                  }else{
                    tooDeepDetailStr+='<li class="radioChecks"><i></i><span>'+tooDeepDetail.detailName+'</span>'+(tooDeepDetail.state == 1?"<a>（智能推荐）</a>":"")+'</li>'
                  }
                }
                
                
                deepDetailStr+=`<li class="radioCheck"><span class="modalMaintltle">${deepDetail.name}: </span>
                                <ul class="clearfix caculateLis" data-isShow = ${deepDetail.isShow}>
                                    ${tooDeepDetailStr}
                                </ul>
                            </li>`
                  
              }
            }
            for(var v = 0;v < tmpBqDetail.content.result.length;v++){
              deepDetailResultStr+='<p class="result"><span class="calculateName">'+tmpBqDetail.content.result[v].name+'：</span><span class="calculateResult"></span></p>'
            }
            tmpBqDetailStr+=`<div class="mayResult">
                计算公式结果：
                <span class="mayResultSelect" data-num="${k}">
                    <span class="makesureResult">请选择</span>
                    <span class="sanjiao"></span>
                    <div class="popupModal">
                        ${deepDetailName}
                        <div class="modalMainTwo">
                            <ul class="clearfix">
                                ${deepDetailStr}
                            </ul>
                            <div class="calculate" data-num="${k}">计算</div>
                            <p class="calculateError">请填写计算公式内容</p>
                            <div class="resultLis">
                                ${deepDetailResultStr}
                            </div>
                        </div>
                        <div class="btnWrap clearfix">
                            <div class="sureScore" data-type="2">关闭</div>
                        </div>
                    </div>
                </span>
            </div>`
            
          }
          if(tmpBqDetail.type == 3){
            var deepDetailName = '<span class="modalMaintltle">'+tmpBqDetail.content.name+': </span>'
            var deepDetailStr = ''
            for(var n = 0;n < tmpBqDetail.content.details.length;n++){
              var deepDetail = tmpBqDetail.content.details[n]
              deepDetailStr+='<li class="radioChecks"><i></i><span>'+deepDetail.detailName+'</span>'+(deepDetail.state == 1?"<a>（智能推荐）</a>":"")+'</li>'
            }

              tmpBqDetailStr+=`<div class="mayResult">
                可能结果：
                <span class="mayResultSelect" data-num="${k}"><span class="makesureResult">请选择</span><i class="sanjiao"></i>
                    <div class="popupModal">
                    <div class="modalTitle">
                        结果选择<i class="closeModal"></i>
                    </div>
                    <div class="modalMainOne">
                        ${deepDetailName}
                        <ul class="clearfix">
                            ${deepDetailStr}
                        </ul>
                    </div>
                    <div class="btnWrap clearfix">
                        <div class="sureScore" data-type="3" data-num="${k}">确定</div>
                    </div>
                </div>
                </span>
            </div>`
          }
          if(tmpBqDetail.type == 4){
            // tmpBqDetailStr+=`<div class="sriticalinfo">诊断要点：${tmpBqDetail.content.name}</div>`
          }
        }
        if(tmpBqStr != '' || tmpBqDetailStr != ''){
          $(".conditionHintTipsNull").css("display","none")
        }
        // $(".conditionHintTips").append('<div class="conditionMain clearfix">'+tmpBqStr+'<div class="alertModal">'+tmpBqDetailStr+'</div></div>')
        $("."+className+"box").append('<div class="conditionMain clearfix">'+tmpBqStr+'<div class="alertModal">'+tmpBqDetailStr+'</div></div>')
      }
      $('.mayIllness .infoMsg').on('click', function(){
        const infoMsgName = $(this).attr('data-name')
        openNewWin(`information.html?type=22&position=2&name=${encodeURIComponent(infoMsgName)}`)
      })
      $('.alertModal .illnessTable').on('click', function(){
        const msg1 = JSON.parse(JSON.stringify(msg))
        msg1.scaleName = $(this).attr('data-scaleName')
        msg1.featureType = 21
        openNewWin(`scale.html?msg=${encodeURIComponent(JSON.stringify(msg1))}`)
      })
      bindTipsEvent()
}
function slideToggle(domName,childrenNodeStrShort,childrenNodeStrLong){//展开收起
    domName.append('<span class="slideDown">更多 <i></i></span>')
    domName.on('click',".slideDown",function(){
        domName.html(childrenNodeStrLong)
        domName.append('<span class="slideup">收起 <i></i></span>')
        $(this).remove()
    })
    domName.on('click',".slideup",function(){
        domName.html(childrenNodeStrShort)
        domName.append('<span class="slideDown">更多 <i></i></span>')
        $(this).remove()
    })
  }

module.exports = {
    renderRecommendInfo,
    renderMultRecommendInfo,
    renderTreat,
    renderRecommendConditTips,
    renderTipsInfo,
    renderKnowledgeInfo,
    renderScaleInfo
}
