var request = getRequest(),
    tab = request.tab || 0,
    sessionId = request.sessionId, //续方咨询的sessionId 格式: 居民code+咨询code+咨询类型（ 8 ）
    patiCode = request.patiCode || '',
    patiName = request.patiName ? decodeURI(request.patiName) : '',
    consultCode,
    prescriptionCode = request.code || '',
    teamCode = request.teamCode || '',
    jwCode, //基卫那边存储的原处方的code
    fv_id, //随访的id
    fv_class; //随访的类别

var docInfo = window.localStorage.getItem("docInfo");
docInfo = JSON.parse(docInfo);

var fromTabIdx = request.fromTabIdx; // 记录前一个Tab索引，用于返回按钮
var reqLinkList = []; //记录切换tab时访问的路径集合，方便返回操作时，不修改之前请求路径的参数

//初始tab的链接
var links = [{
    index: 1,
    url: 'prescription-consulting.html?from=tab&sessionId='+sessionId,
    name: '咨询',
    class: ''
},{
    index: 2,
    url: 'prescription-detail.html?from=tab&code='+prescriptionCode+'&id='+teamCode,
    name: '续方详情',
    class: ''
},{
    index: 3,
    url: 'order-tracking.html?from=tab&code='+prescriptionCode,
    name: '订单跟踪',
    class: '',
},{
    index: 4,
    url: 'body-record.html?from=tab&patiCode='+patiCode,
    name: '体征记录',
    class: ''
},{
    index: 5,
    url: 'jianchajianyan.html?from=tab&patient='+patiCode,
    name: '检查检验',
    class: ''
},{
    index: 6,
    url: 'jw-prescription-list.html?from=tab&patient='+patiCode,
    name: '诊断/处方',
    class: ''
},{
    index: 7,
    url: 'prescription-list.html?from=tab&teamCode='+teamCode+'&patient='+patiCode,
    name: '历史续方',
    class: ''
},{
    index: 8,
    url: 'fv-survey.html?from=tab&fv_id='+fv_id+'&code='+prescriptionCode,
    name: '问卷调查',
    class: ''
},{
    index: 9,
    url: 'page/followup/followup-main.html?fv_id='+fv_id+'&patiCode='+patiCode+'&fv_class='+fv_class,
    name: '随访记录',
    class: ''
}];

$(function(){
    setTitle(patiName+"续方咨询");
    if(!prescriptionCode){
        //没有续方的code，就从咨询中获取对应的code
        //这种情况下，患者的签约团队一定是医生所在的团队的id
        teamCode = docInfo.adminTeamCode;
        getPrescriptionInfo();
    }else{
        //有续方的code，通过code获得续方详情
        getPrescriptionInfoByCode();
    }
})

// 判断是否有体征设备
function judgeDeviceFn() {
	var recordDevice = {patient: patiCode, page: 1, pagesize: 1};
	bodyRecordApis.getPatientDevice({data: recordDevice}).then(function(res){
		if(res.status == 200){
			if(res.data.length == 0){
                //没有绑定设备
                links[3].class="hidden";
                initPage();
           } else {
           		judgeRecordFn()
           }
    	}else{
        	showWarningMsg(res.msg)
    	}
	})
}

// 判断是否有体征记录
function judgeRecordFn() {
	var recordData = {patient: patiCode};
	bodyRecordApis.getBodyRecoredLast({data: recordData}).then(function(res){
		if(res.status == 200){
			if(!res.data.xt && !res.data.xy) {
				links[3].class="hidden";
			}
			initPage();
    	}else{
        	showWarningMsg(res.msg)
    	}
	})
}

function initPage(){
    links[tab].class="active";
    var html = template('tab_tmp', {list: links});
    $("#tabs").append(html);
    parent.document.getElementById('main').src = links[tab].url;
    reqLinkList.push(links[tab].url);
    
    $("#tabs").on('click', 'a', function(){
        var $this = $(this),
            $li = $this.parent();
        
        if($this.text() == "随访记录"){
            tab = $this.data('index');
            top.layer.open({
                type: 2,
                title: '随访记录',
                shadeClose: true,
        //      shade: false,
        //      maxmin: true, //开启最大化最小化按钮
                area: ['800px', '570px'],
                content: links[tab].url
            });
            return false;
        }else{
            fromTabIdx = $("#tabs li.active").index();  
            $li.siblings().removeClass("active");
            $li.addClass("active");
            tab = $this.data('index');
            reqLinkList.push(links[tab].url+'&from=tab&fromTabIdx='+fromTabIdx);
            var url = links[tab].url+'&from=tab&fromTabIdx='+fromTabIdx;
        }
        
        parent.document.getElementById('main').src = url;
    })
}

function toPrePrescriptionTab() {
    //页面返回的操作不做trigger操作
	var oldUrl = reqLinkList.pop();
	var fromTabIdx = oldUrl.split("fromTabIdx=")[1];
	var length = reqLinkList.length;
	if(length>0){
	    //应跳转去的页面是
//      var url = reqLinkList[reqLinkList.length -1];
        if(fromTabIdx){
            $("#tabs li").removeClass("active");
            $("#tabs li").eq(fromTabIdx).addClass("active");
        }
	}
    history.go(-1);
}

top.toPrePrescriptionTab = toPrePrescriptionTab;

//跳转去置顶的tab
function gotoPrescriptionTab(index){
    console.log(index);
    var url = links[index -1].url;
    console.log(url);
    $("#tabs li").removeClass("active");
    $("#tabs li").eq(index -1).addClass("active");
    reqLinkList.push(url);
    parent.document.getElementById('main').src = url;
}
parent.gotoPrescriptionTab = gotoPrescriptionTab;

function getPrescriptionInfo(){
    patiCode = sessionId.split("_")[0];
    consultCode = sessionId.split("_")[1];
    var params = { consult: consultCode};
    consultingAPI.getPrescriptionInfo({data: params}).then(function(res){
        if(res.status == 200){
            prescriptionCode = res.data.code;
            jwCode = res.data.jwCode;
            var followup = res.data.followup;
            if(followup){
                followup = JSON.parse(followup);
                fv_id = followup.id;
                fv_class = followup.followupClass;
            }
            updateLinkInfo();
            if(res.data.status < 50){ //支付成功前不会有订单记录
                links[2].class="hidden";
            }
            if(!followup){
                links[7].class="hidden";
                links[8].class="hidden";
            }
            judgeDeviceFn();
        }else{
            showWarningMsg(res.msg);
        }
    });
}

function getPrescriptionInfoByCode(){
    var params = {
        code: prescriptionCode,
        type: docInfo.isLeader == '1' ? 1 : 2
    };
    consultingAPI.getPrescriptionInfoByCode({data: params}).then(function(res){
        if(res.status == 200){
            patiCode = res.data.patient.code;
            jwCode = res.data.prescription.jwCode;
            consultCode = res.data.prescription.consult;
            sessionId = patiCode + '_' + consultCode+'_8';
            //获得随访的信息
            fv_id = res.data.followup.id;
            fv_class = res.data.followup.followupClass;
            updateLinkInfo();
            //如果不是该续方所在团队的团队长，则不可以显示咨询tab,也不显示随访tab
            if(res.data.prescription.doctor != docInfo.code){
                links[0].class="hidden";
                links[7].class="hidden";
                links[8].class="hidden";
            }
            if(res.data.prescription.status < 50){ //支付成功前不会有订单记录
                links[2].class="hidden";
            }
            judgeDeviceFn();
        }else{
            showWarningMsg(res.msg);
        }
    });
}

function updateLinkInfo(){
    links = [{
        index: 1,
        url: 'prescription-consulting.html?from=tab&sessionId='+sessionId,
        name: '咨询',
        class: ''
    },{
        index: 2,
        url: 'prescription-detail.html?from=tab&code='+prescriptionCode+'&id='+teamCode,
        name: '续方详情',
        class: ''
    },{
        index: 3,
        url: 'order-tracking.html?from=tab&code='+prescriptionCode,
        name: '订单跟踪',
        class: '',
    },{
        index: 4,
        url: 'body-record.html?from=tab&patiCode='+patiCode,
        name: '体征记录',
        class: ''
    },{
        index: 5,
        url: 'jianchajianyan.html?from=tab&patient='+patiCode,
        name: '检查检验',
        class: ''
    },{
        index: 6,
        url: 'jw-prescription-list.html?from=tab&patient='+patiCode,
        name: '诊断/处方',
        class: ''
    },{
        index: 7,
        url: 'prescription-list.html?from=tab&teamCode='+teamCode+'&patient='+patiCode,
        name: '历史续方',
        class: ''
    },{
        index: 8,
        url: 'fv-survey.html?from=tab&fv_id='+fv_id+'&code='+prescriptionCode,
        name: '问卷调查',
        class: ''
    },{
        index: 9,
        url: 'page/followup/followup-main.html?fv_id='+fv_id+'&patiCode='+patiCode+'&fv_class='+fv_class,
        name: '随访记录',
        class: ''
    }];
}