const $ = require("jquery");
const { openNewWin, imageUrlPrefix, isIe8 } = require('./promise.js');
const { bindTipsEvent } = require('./popupEdit.js');
let showImg = require('./../images/show.png')
let collapseImg = require('./../images/collapse.png')


const is8Ie = isIe8() //判断是否为IE8
if(is8Ie) {
  let reg = /undefined/g
  showImg = showImg.replace(reg, '')
  collapseImg = collapseImg.replace(reg, '')
}

//推荐诊断等单种类型的
function renderRecommendInfo(showNum, icon, className,title,data, hasInfo, type, position) {
    let showNumCopy = showNum || 5
    const dataLen = data.length
    const str = `<div class="recommendInfoWrapper ${className} clearfix">
                    <h4><img src=${icon} title="${title}" class="icon">${title}:</h4>
                    <div class="recommendInfoBox">
                        <div class="clearfix recommendInfoItemBox ${className + 'box'}">
                        </div>
                    </div>
                </div>`
    $('.push').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">
                                    ${data[i].name}
                                    <span  title="点击i图标可查看详细说明" class="infoMsg" data-name=${data[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="${data[i].name}">
                                    ${data[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)
    let childrenNodeStrAll = `<div class="${className+'boxAll'} itemAllBox">
            <h4>${title}:</h4>
            <div class="itemAll">
                ${childrenNodeStrLong}
            </div>
            <span class="slideup"><img src="${collapseImg}"></span>
        </div>`

    $('.push').append(childrenNodeStrAll)
    $('.'+className + 'box' +' .infoMsg').on('click', function(){
        const infoMsgName = $(this).attr('data-name')
        openNewWin(`information.html?type=${type}&position=${position}&name=${infoMsgName}`)
    })
    $('.'+className + 'boxAll' +' .infoMsg').on('click', function(){
        const infoMsgName = $(this).attr('data-name')
        openNewWin(`information.html?type=${type}&position=${position}&name=${infoMsgName}`)
    })
    slideToggle("."+className+"box", showNumCopy, dataLen)

}

//化验和辅检等多种类型
function renderMultRecommendInfo(labsAndPacMode,icon, className,title,data, hasInfo, type, position) {
    const str = `<div class="recommendInfoWrapper ${className} clearfix">
                    <h4 class ="${+labsAndPacMode === 1 ? 'showTopTitle':'showRightTitle'}"><img src=${icon} title="${title}" class="icon">${title}:</h4>
                    <div class="recommendInfoBox ${className + 'box'} ${+labsAndPacMode === 1 ? 'showTopInfo':'showRightInfo'}"></div>
                </div>`
    $('.push').append(str)
    let hanContentNum = 0
    for(let i = 0; i < data.length; i++) {
        if(data[i].data === 0) {
            continue
        }
        const showNum = data[i].showNum || 5
        const dataLen = data[i].data.length
        if(dataLen === 0) {
            continue
        }
        let childrenNodeBoxStr  = `<div class="labAndPacsWrapper ${data[i].className+'wrapper'}">
                <div class="labAndPacsBox ${data[i].className+'box'} clearfix"> 
                </div>
            </div>`
        let childrenNodeStr =  `<span class="labAndPacsTitle ${+labsAndPacMode === 1 ? 'topSmallTitle':'rightSmallTitle'}"">${data[i].title}<i></i></span>`
        let childrenNodeItemStrAll =  '' //更多展开框中的字符串
        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++) {
            childrenNodeStr += `<span class="labAndPacsItem">${dataShort[j].name}</span>`
        }
        for(let j = 0; j < data[i].data.length; j++) {
            childrenNodeItemStrAll += `<span class="labAndPacsItem">${data[i].data[j].name}</span>`
        }
        if(data[i].data.length == 0) {
            childrenNodeStr +='<span class="recommendNull">暂无推荐</span>'
        }
        $('.'+className + 'box').append(childrenNodeBoxStr)
        $('.'+data[i].className+'box').append(childrenNodeStr)
        let childrenNodeStrAll = `<div class="${data[i].className+'boxAll'} itemAllBox">
            <h4>${data[i].title}:</h4>
            <div class="itemAll">
                ${childrenNodeItemStrAll}
                <span class="slideup"><img src="${collapseImg}"></span>
            </div>
        </div>`

        $('.push').append(childrenNodeStrAll)
        slideToggle("."+data[i].className+"box", showNum, dataLen)
    }

}

function renderTreat(icon, className,title, data) {
    $('.infoTabBox').append(`<span class="infoTab treatTab boldFont"  data-box="${className}">${title}</span>`)
    const str = `<div class="informationBox recommendInfoWrapper ${className} clearfix">
                    <p class="diagName boldFont">${msg.diseaseName.uniqueName?msg.diseaseName.uniqueName:''}</p>
                    <div class="recommendInfoBox clearfix ${className + 'box'}"></div>
                </div>`
    $('.infomationBox').append(str)
    const commonTreatmentInfo = data.commonTreatment&&data.commonTreatment.content || ""
    const treatmentList = data.treatmentPlan || []
    renderTreatText('commonTreatment', '一般治疗', commonTreatmentInfo, className+'box')
    renderTreatDrug('drugTreatment', '推荐药物', treatmentList, className+'box')
}
function renderKnowledgeInfo(icon, className,title, data) {
    $('.infoTabBox').append(`<span class="infoTab tipsTab boldFont"  data-box="${className}">${title}</span>`)
    const str = `<div class="informationBox staticWin recommendInfoWrapper ${className} clearfix">
                    <p class="diagName">${data}</p>
                </div>`
    $('.infomationBox').append(str)
    $('.'+className+'.staticWin' ).on('click', function(){
        openNewWin(`staticSearch.html?msg=${encodeURIComponent(JSON.stringify(msg))}`)
    })
}
function renderScaleInfo(icon, className,title, data) {
    $('.infoTabBox').append(`<span class="infoTab tipsTab boldFont"  data-box="${className}">${title}</span>`)
    const str = `<div class="informationBox staticWin recommendInfoWrapper ${className} clearfix">
                    <p class="diagName">${data}</p>
                </div>`
    $('.infomationBox').append(str)
    $('.'+className+'.staticWin' ).on('click', function(){
        openNewWin(`staticSearch.html?msg=${encodeURIComponent(JSON.stringify(msg))}`)
    })
}

function renderTreatText(className,title,data, parentNode) {
    const childrenNodeBoxStr = `
        <div class = "treatItemBox ${className + 'box'} disCopy">
            <p class="treatItemTitle">${title}:</p>
            <div class="treatTextBox">
                <p class="${className + 'Info'} clearfix"></p>
            </div>
        </div>
    `
    $('.' + parentNode).append(childrenNodeBoxStr)
    if(!data) {
        data = '<span class="recommendNull">暂无推荐</span>'
    }
    $('.' + className+'Info').html(data)
    var commonTreatHeight = $(".commonTreatmentInfo").height()
    if(commonTreatHeight > 75){
        $(".treatTextBox").append('<span class="more">更多</span>')
    }
    $(".infomationBox .treatTextBox").on('click',".more",function(){
        openNewWin(`treatplan.html?msg=${encodeURIComponent(JSON.stringify(msg))}`)
    })
    $('.' + className + 'box' + ' 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="more">更多</span>'}</p>
            <div class="treatDrugBox">
                <p class="${className + 'Info'}"></p>
            </div>
        </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 ellipsis"><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="diaDescription">${data[i].meditionDetails[j].description}</p>`
            //     }
            // }
            childrenNodeStr +=`</div>`
        $('.' + className+'Info').append(childrenNodeStr)
    }
    // 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' : '' )}">${data[i].medicitionsList[j].medicitionName}`
    //         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 drugTreatmentHeight = $(".drugTreatmentInfo").height()
    // if(drugTreatmentHeight > 75){
    //     $(".treatDrugBox").append('<span class="more">更多</span>')
    // } else if(drugTreatmentHeight > 30) {
    //     $(".drugTreatmentInfo").append('<span class="more">更多</span>')
    // }
    $(".infomationBox .drugTreatmentbox").on('click',".more",function(){
        openNewWin(`treatplan.html?msg=${encodeURIComponent(JSON.stringify(msg))}`)
        // openNewWin(`treatplan.html?age=${msg.age}&sex=${msg.sex}&symptomJson=${msg.symptom}&vitalJson=${msg.vital}&lisJson=${msg.lis}&pacsJson=${msg.pacs}&diseaseName=${msg.diseaseName}&diagJson=${msg.diag}&otherJson=${msg.other}&hospitalCode=${msg.hosCode}`)
      })
    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 renderTipsInfo(icon, className,title,data) {
    $('.infoTabBox').append(`<span class="infoTab tipsTab boldFont" data-box="${className}">${title}</span>`)
    let str
    if(data.length === 0) {
        str = `<div class="informationBox tipsInfoWrapper ${className} clearfix">
            <p class="diagName recommendNull">暂无数据</p>
            <div class="tipsInfoBox clearfix ${className + 'box'} disCopy"></div>
        </div>`
    } else {
        str = `<div class="informationBox tipsInfoWrapper ${className} clearfix">
                    <div class="tipsInfoBox clearfix ${className + 'box'} disCopy">
                    </div>
                </div>`
    }
    
    $('.infomationBox').append(str)
    for(let i = 0; i < data.length; i++) {
        renderTipsInfoText('','诊断依据',data[i],className + 'box')
    }
    $('.' + className + 'box' + ' img').bind('contextmenu', function(){
        return false
    })
    // if(data.name) {
    //     renderTipsInfoText('','诊断依据',data.details,className + 'box')
    // }
    if(data.length > 1) {
        $('.tipsInfoItem').each(function(i, obj){
            var lineHeight = parseInt($(this).css("line-height"));
            var height = parseInt($(this).height());
            if((height / lineHeight) >3 ){
                $(this).addClass("hasMore")
                $(this).css("height","60px");    
            }else{
                $(this).removeClass("hasMore");
            }
        });
    }
   
}


function renderTipsInfoText(className,title,data, parentNode) {
    let childrenNodeBoxStr = `<p class="diagName boldFont">${data.name} <span class="moreInfo"  data-name="${data.name}" data-type="${data.type}">详情</span></p>`
    if(data.details.length === 0) {
        childrenNodeBoxStr += `<p class="recommendNull">暂无数据</p>
                            `
    } else {
        for(let i = 0; i < data.details.length; i++) {
            childrenNodeBoxStr += `<div class="tipsInfoItem">
                                        <p class="tipsInfoItemTitle">${data.details[i].title}</p>
                                        ${data.details[i].content.replace(/{imageUrlPrefix}/g, imageUrlPrefix)}
                                   </div>
                                `
        }
    }
   
    $('.' + parentNode).append(childrenNodeBoxStr)
  
   
}

function renderRecommendConditTips(icon, className,title,data) {
    const str = `<div class="recommendInfoWrapper ${className} clearfix">
                    <h4><img src=${icon} title="${title}" class="icon">${title}:</h4>
                    <div class="recommendInfoBox  ${className + 'box'}"></div>
                </div>`
    $('.push').append(str)
    if(data.length == 0) {
        $("."+className+"box").append('<span class="recommendNull">暂无推荐</span>')
    }
    /*let names = [];*/
    for(var k = 0;k < data.length;k++){
        var 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 == 4){
            // tmpBqDetailStr+=`<span class="sriticalinfo">&nbsp;${tmpBqDetail.content.name}(诊断要点)</span>`
          }
        
        }
        /*if(tmpBqStr){*/
          $("."+className+"box").append('<div class="conditionMain ellipse clearfix">'+tmpBqStr+'<div class="alertModal">'+tmpBqDetailStr+'</div><span class="more">更多</span></div>')
        //}
        //$("."+className+"box").append('<div class="conditionMain ellipse clearfix">'+tmpBqStr+'<div class="alertModal">'+tmpBqDetailStr+'</div><span class="more">更多</span></div>')
      }
      $('.mayIllness .infoMsg').on('click', function(){
        const infoMsgName = $(this).attr('data-name')
        openNewWin(`information.html?type=22&position=2&name=${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))}`)
      })
      $(".conditTipsbox").on('click',".more",function(){
        // openNewWin(`illness.html?age=${msg.age}&sex=${msg.sex}&symptomJson=${msg.symptom}&vitalJson=${msg.vital}&lisJson=${JSON.stringify(msg.lis)}&pacsJson=${msg.pacs}&diagJson=${msg.diag}&diseaseName=${msg.diseaseName}&otherJson=${msg.other}&hospitalCode=${msg.hosCode}&msg=${JSON.stringify(msg)}`)
        openNewWin(`illness.html?msg=${encodeURIComponent(JSON.stringify(msg))}`)

      })
      bindTipsEvent()
}
function slideToggle(className, showNum, dataLen){//展开收起
    const domName = $(className)
    const domNameBoxAll = $(className+'All')
    setTimeout(() => {
        if(showNum < dataLen){
          domName.append(`<span class="slideDown"><img src="${showImg}"></span>`)
        }
    });
    domName.on('click',".slideDown",function(){
        $(".itemAllBox").css('display', 'none')
        $(domNameBoxAll).css('display', 'block')
      
    })
    domNameBoxAll.on('click',".slideup",function(){
        $(domNameBoxAll).css('display', 'none')
    })
  }

//打开免责申明
  $(".disclaimer .logo").on("click",function() {
    openNewWin("disclaimer.html");
  });

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