var $ = require("jquery");
var { post,config,getUrlArgObject,openNewWin,isIe8 ,openNewWin} = require('./promise.js');
let showImg = require('./../images/show.png').replace(/^undefined/g, '')
let collapseImg = require('./../images/collapse.png').replace(/^undefined/g, '')
let emptyImg = require('./../images/empty3.png').replace(/^undefined/g, '')
let lisStrFrontIcon = require('./../images/lisStrFront-icon.png').replace(/^undefined/g, '')
let pacsStrFrontIcon = require('./../images/pacsStrFront-icon.png').replace(/^undefined/g, '')
let rightIcon = require('./../images/right-icon.png').replace(/^undefined/g, '')
function getFollowUp(msg) {
    return post(config.followUp, msg)
}
let hospitalId = getUrlArgObject('hospitalId') || ''
let mrId = getUrlArgObject('mrId')
function renderFollowUp(msg, type) {
    getFollowUp(msg).then(res => {
        if (res.data.code === "0") {
            const result = res.data.data && res.data.data.pushPlans || []
            if (result.length === 0 || (result[0] && result[0].item && JSON.stringify(result[0].item) === "{}")) {
                followEmpty()
                return
            }
            renderPage(result, type)
        } else {
            followEmpty()
        }
    })
}
function renderPage(data, type) {
    const operaItem = data[0] || {}
    const operaItemName = operaItem.item || {}
    let operaItemDetail = operaItem.pushPlanDetails || []
    renderName(operaItemName)
    if (type) {
        operaItemDetail = operaItemDetail.filter((it)=>it.history===0)||[];
        renderDetailHorizontal(operaItemDetail[0])
    } else {
        renderBtn(operaItemDetail[0])
        renderDetail(operaItemDetail[0])
        //checkDom()
    }
}
function renderName(data) {
    const operationTime = data.dateValue && getTime(data.dateValue)
    const operationName = data.name || ""
    const str = `<div class="operaNameWrap" id="operaNameWrap"><div class="operaNameBox">患者于<span class="operaNameBold">${operationTime}</span>进行<span class="operaNameBold">${operationName}</span>。根据临床路径要求，特制订检验检查计划如下。</div></div>`
    $(".followUpWrap").append(str)
}
function renderDetailHorizontal(data) {
    let str = ``
    for (let i = 0; i < data.length; i++) {
        const item = data[i]
        const lisArr = item.lis || []
        const pacsArr = item.pacs || []
        let lisStr = ``
        let pacsStr = ``
        let title = `<p>${getTime(item.examineDate)}（${item.description && (item.description)}）</p>`
        for (let i = 0; i < lisArr.length; i++) {
            lisStr += `<div style="position:relative"><span class="circle"></span>${lisArr[i]}</div>`
        }
        for (let i = 0; i < pacsArr.length; i++) {
            pacsStr += `<div style="position:relative"><span class="circle"></span>${pacsArr[i]}</div>`
        }
        str += `<div class="infoBox">
            ${title}
            <div class="checkFront lisBox">
            <div class="lisStrFront">
                <img src="${lisStrFrontIcon}" alt="" />
                <span>检验</span>
            </div>
            
            <div>${lisStr}</div>
           </div>
           <div class="checkFront pacsBox">
           <div class="pacsStrFront">
           <img src="${pacsStrFrontIcon}" alt="" />
            <span>检查</span>
           </div>
            
            <div>${pacsStr}</div>
           </div>
       </div>`
    }
    $(".followUpWrap").append(`<div class="infoWrap">${str}<div class="readMorePlan"><a>查看更多计划</a>
        <img src="${rightIcon}" alt="" />
    </div></div>`)
    showMoreCheck()
}
function showMoreCheck() {
    $(".readMorePlan").on("click", function () {
        openNewWin(`cdssPlan.html?mrId=${mrId}&hospitalId=${hospitalId}`)
    })
}
function renderDetail(data) {
    let historyStr = ``
    let laterStr = ``
    for (let i = 0; i < data.length; i++) {
        const item = data[i]
        const lisArr = item.lis || []
        const pacsArr = item.pacs || []
        let lisStr = ``
        let pacsStr = ``
        let title = `<p class="infoBoxTitle">${getTime(item.examineDate)}${item.description ? '(' + item.description + ')' : ''} <img class="toggleInfo" src="${showImg}"/></p>`
        for (let i = 0; i < lisArr.length; i++) {
            lisStr += `<div class="lisItem"><span class="circle"></span>${lisArr[i]}</div>`
        }
        for (let i = 0; i < pacsArr.length; i++) {
            pacsStr += `<div  class="lisItem"><span class="circle"></span>${pacsArr[i]}</div>`
        }
        if (item.history === 1) {
            historyStr += `<div class="infoBox historyBox" >
            ${title}
            <div class="childrenBox">
                ${lisArr.length > 0 ? `<div class="lisBox"><span class="itemBoxTitle">检验</span>${lisStr}</div>` : ""}
                ${pacsArr.length > 0 ? `<div class="pacsBox"><span class="itemBoxTitle">检查</span>${pacsStr}</div>` : ""}
            </div>
        </div>`
        } else {
            laterStr += `<div class="infoBox">
            ${title}
            <div class="childrenBox">
                ${lisArr.length > 0 ? `<div class="lisBox"><span class="itemBoxTitle">检验</span>${lisStr}</div>` : ""}
                ${pacsArr.length > 0 ? `<div class="pacsBox"><span class="itemBoxTitle">检查</span>${pacsStr}</div>` : ""}
            </div>
        </div>`
        }

    }
    $(".followUpWrap").append(`<div class="infoWrap" id="infoWrap">
        <div class="historyWrap">${historyStr}</div>
        <div class="laterWrap">${laterStr}</div>
    </div>`)
    //最近一次计划默认展开
    $(".laterWrap .infoBox:first-child .childrenBox").show();
    $(".laterWrap .infoBox:first-child .toggleInfo").attr("src",collapseImg)
    // adjustHeight()
    bindToggleInfo()

}
function renderBtn(data){
    const hasBtn = data[0]&&data[0].history&&data[0].history === 1
    if(!hasBtn){
        return
    }
    const str = `<div class="btnBox" id="btnBox"><span class="btnName">显示历史计划</span></div>`
    $(".operaNameWrap").append(str)
    bindToggleHistory()

}
function adjustHeight() {
    var containerHt = $(".contentWrapper").height()
    var ht1 = $(".operaNameWrap").height()
    var ht2 = $(".btnBox").height()
    $(".followUpWrap  .infoWrap").height(containerHt -ht1- ht2 + "px");
    $(".infoWrap").preventScroll();  
}
function getTime(time) {
    if (!time) {
        return ``
    }
    date = time.replace('-', '/')
    const year = new Date(date).getFullYear()
    const month = new Date(date).getMonth() + 1
    const day = new Date(date).getDate()
    return `${year}年${month}月${day}日`
}

//  声明定时器
var cheakDomTimer = null
//  检查dom是否执行完成
function checkDom() {
    let dom1Hei = $("#operaNameWrap").height()
    let dom2 = document.getElementById('btnBox')
    let dom3 = document.getElementById('infoWrap')
    let dom2Hei = $("#btnBox").height()
    if (dom1Hei !== 0 && (dom2 && dom2Hei != 0 || !dom2) && dom3) {
        //  执行dom加载完成后的操作

        adjustHeight()
        //  清除定时器
        if (!cheakDomTimer) {
            clearTimeout(cheakDomTimer)
        }
    } else {
        //  自我调用
        cheakDomTimer = setTimeout(checkDom, 200)
    }
}
function bindToggleHistory() {
    $(".followUpWrap .btnName").off("click").on("click",function () {
        const btnText = $(".btnName").text()
        if (btnText === "显示历史计划") {
            $(".btnName").text("隐藏历史计划")
        } else {
            $(".btnName").text("显示历史计划")
        }
        $(".historyWrap").slideToggle()
    })
}
function bindToggleInfo(){
    $(document).off("click").on("click",".infoBoxTitle",function(){
        const img =  $(this).parents(".infoBox").find(".toggleInfo").attr("src")
        if(img === showImg){
            $(this).parents(".infoBox").find(".toggleInfo").attr("src",collapseImg)
        }else{
            $(this).parents(".infoBox").find(".toggleInfo").attr("src",showImg)
        }
        $(this).parents(".infoBox").find(".childrenBox").slideToggle()
    })
}
function followEmpty() {
    let str = `<div class="emptyBox">
        <img class="emptyImg" src=${emptyImg}>
        <p class="emptyTxt">暂无随访计划</p>
    </div>`
    $(".followUpWrap").append(str)
}

/*$(window).on('resize', function () {
    if (window.location.href.indexOf('cdssHorizontal') > -1) {
        return
    }
    adjustHeight()
})*/

module.exports = {
    renderFollowUp,
    followEmpty
}