var request = getRequest(), 
    fv_id = request.fv_id,
    pro_id = request.pro_id,
    title = request.title,
    fv_class = request.fv_class,
    patiCode = request.patiCode;

var docInfo = window.localStorage.getItem('docInfo');
if(docInfo){
    docInfo = JSON.parse(docInfo);
}

$(function(){
    initPage();
    bindEvents();
})

function initPage(){
    var params = {
        id: fv_id
    };
    followupAPI.getFollowupDrugs(params).then(function(res){
        if(res.status == 200){
            var data = res.data.DRUG_LIST,
                regular = res.data.DRUG_COMPLIANCE_CODE,
                hasInsulin=[],
                noInsulin=[];
            
            $("[name=DRUG_COMPLIANCE_CODE]").val(regular);
            if(data.length>0){
                for(var i=0;i<data.length;i++){
                    var unitInfo = _.findWhere(measure_unit_dict, {key: data[i].unit}),
                        frequency = _.findWhere(recipe_frequency_dict, {key: data[i].frequency});
                        
                    data[i].unitName = unitInfo.name;
                    data[i].frequencyName = frequency.name;
                    if(data[i].drugsGroup == 'insulin'){//胰岛素药品
                        hasInsulin.push(data[i])
                    }else{
                        noInsulin.push(data[i])
                    }
                }
            }
            var hasInsulinLen = hasInsulin.length,
                noInsulinLen = noInsulin.length,
                noInsulinEmptyList = new Array(6 - noInsulinLen), //非胰岛素药品最多只能增加6种
                hasInsulinEmptyList = new Array(3 - hasInsulinLen); //胰岛素药品最多只能增加3种
            var html1 = template("drug_tmp", {dataList: noInsulin, emptyList: noInsulinEmptyList}),
                html2 = template("drug_tmp", {dataList: hasInsulin, emptyList: hasInsulinEmptyList});
                
            $("#table1 tbody").append(html1);
            $("#table2 tbody").append(html2);
            
            initDrugNameSuggestInput();
            initUnitInput();
            initFreqSuggestInput();
        }else{
            showErrorMsg(res.msg);
        }
    })
}

function bindEvents(){
    $(".link-red").on("click", function(){
        layer.confirm('您确定要清空用药信息吗？', {
            btn: ['是的','取消'], //按钮
            shade: false //不显示遮罩
        }, function(){
            //清空数据
            clearDrugsInfo();
            layer.close(layer.index);
        });
    });
    
    $("#getPrescription").on("click", function(){
        //弹出层是加载在top上的，目前项目的top层是index.html页面层。所以路径需要相对index.html页面
        top.layer.open({
            type: 2,
            type: 2,
            title: '<img src="img/shezi_tankuang_icon.png" class="mr10">用药记录',
            shadeClose: true,
            area: ['700px', '500px'],
            content: '/PC-prescription/page/followup/followup-prescriptions.html'+location.search
        });
    });
    
    $("#submitBtn").on("click", function(){
        //保存
        var complianceCode = $("[name=DRUG_COMPLIANCE_CODE]").val(),
            $trs1 = $("#table1 tbody tr"),
            $trs2 = $("#table2 tbody tr"),
            drugs = [];
        for(var i=0; i<6; i++){
            var $tr = $($trs1[i]),
                $drug = $tr.find(".j-drugName"),
                $dose = $tr.find(".dose"),
                $unit = $tr.find(".unit-select"),
                $freq = $tr.find(".frequency-select");
                
            var obj = {},
                drugsGroup = 'normal',
                drugsCode = $drug.attr("data-id"),
                drugsName = $drug.val(),
                frequency = $freq.attr("data-id"),
                unit = $unit.attr("data-id"),
                dose = $dose.val();
            if(drugsCode && drugsName && dose && unit && frequency){
                obj = {
                    drugsGroup : 'normal',
                    drugsCode : drugsCode,
                    drugsName : drugsName,
                    frequency : frequency,
                    unit : unit,
                    dose : dose
                };
                drugs.push(obj);
            }else if(drugsCode || drugsName || dose || unit || frequency){
                //如果药品信息中填写了部分，则需要将未填写的内容补全
                showWarningMsg("请补全未填写完成的药品信息");
                return false;
            }
        }
        for(var j=0; j<3; j++){
            var $tr = $($trs2[j]),
                $drug = $tr.find(".j-drugName"),
                $dose = $tr.find(".dose"),
                $unit = $tr.find(".unit-select"),
                $freq = $tr.find(".frequency-select");
                
            var obj = {},
                drugsGroup = 'insulin',
                drugsCode = $drug.attr("data-id"),
                drugsName = $drug.val(),
                frequency = $freq.attr("data-id"),
                unit = $unit.attr("data-id"),
                dose = $dose.val();
            if(drugsCode && drugsName && dose && unit && frequency){
                obj = {
                    drugsGroup : 'normal',
                    drugsCode : drugsCode,
                    drugsName : drugsName,
                    frequency : frequency,
                    unit : unit,
                    dose : dose
                };
                drugs.push(obj);
            }else if(drugsCode || drugsName || dose || unit || frequency){
                //如果药品信息中填写了部分，则需要将未填写的内容补全
                showWarningMsg("请补全未填写完成的药品信息");
                return false;
            }
        }
        
        
        if(complianceCode == "undefined"){
            complianceCode = "";
        }
        var followupProjectData = {'DRUG_COMPLIANCE_CODE': complianceCode};
        console.log(followupProjectData);
        var projectData = {
            id: fv_id,
            followupProject: pro_id,
            followupProjectData: JSON.stringify(followupProjectData)
        },
        drugData = {
            id: fv_id,
            drugsData: JSON.stringify(drugs)
        };
        Promise.all([
            followupAPI.saveFollowupProjectData(projectData),
            followupAPI.saveFollowupDrugs(drugData)
        ]).then(function(ress){
            if(ress[0].status == 200 && ress[1].status == 200){
                top.goFollowupNextQuestionaire();
            }else if(ress[0].status != 200){
                showErrorMsg(ress[0].msg);
            }else if(ress[1].status != 200){
                showErrorMsg(ress[1].msg);
            }
        })
    })
}

function initDrugNameSuggestInput() {
    $("input.j-drugName").bsSuggest({
        url: APIService.server+'doctor/prescriptionInfo/findDictByName?name=',
        getDataMethod:'url',
        idField: "drugCode",
        keyField: "drugName",
        effectiveFields: ['drugName','drugFormat'],
        effectiveFieldsAlias:{drugName: "药品名称",drugFormat:"规格"},
        ignorecase: true,
        fnProcessData: function(res) {
            return {
                value: res.data
            }
        }
    }).on('onSetSelectValue', function (e, v) {
        var rowData = v.json;
        rowData = JSON.parse(rowData);
        var $tr = $(this).closest("tr"),
            $unit = $tr.find(".unit-select");
        $unit.val(rowData.physicDoseUnitName);
        $unit.attr("data-id", rowData.physicDoseUnit);
    })
}

function initFreqSuggestInput(){
    $("input.frequency-select").bsSuggest({
        data: {value: recipe_frequency_dict},
        idField: "key",
        keyField: "name",
        getDataMethod:'data',
        effectiveFields: ['name'],
        ignorecase: true
    })
}

function initUnitInput(){
    $("input.unit-select").bsSuggest({
        data: {value: measure_unit_dict},
        idField: "key",
        keyField: "name",
        getDataMethod:'data',
        effectiveFields: ['name'],
        ignorecase: true
    })
}

//清空药品信息
function clearDrugsInfo(){
    var $trs = $("tbody tr");
    
    for(var i=0; i<9; i++){
        var $tr = $($trs[i]),
            $inputs = $tr.find("input"),
            len = $inputs.length;
        for(var j=0; j<len; j++){
            var $input = $($inputs[j]);
            $input.val("");
            $input.attr("data-id", "");
        }
    }
}

function fillDrugsInfo(){
    //从缓存中获取选中的药品信息
    var drugsData = window.sessionStorage.getItem("chooseDrugs");
    if(drugsData){
        drugsData = JSON.parse(drugsData);
        var len = drugsData.length;
        
        if(len == 0){
            return false;
        }
        //先将药品分类
        var insulinList = [],
            normalList = [];
        for(var i=0; i<len; i++){
            var obj = drugsData[i];
            if(obj.subjectClass.substr(0,2)=='010' && obj.name.indexOf('胰岛素')>0){
                //胰岛素药品
                insulinList.push(obj);
            }else{
                normalList.push(obj)
            }
        }
        //如果表格中药品名称没有填写的均可以被覆盖，如果已填写的药品与处方中的药品名称一致，设定为相同药品
        
        var $trs1 = $("#table1 tbody tr"),
            $trs2 = $("#table2 tbody tr"),
            len1 = normalList.length,
            len2 = insulinList.length;
        
        if(len1 > 0){
            //填充普通药品
            var index1 = 0;
            for(var i1=0; i1<6; i1++){
                var $tr = $($trs1[i1]),
                    $drugName = $tr.find(".j-drugName"),
                    $unit = $tr.find(".unit-select"),
                    $frequency = $tr.find(".frequency-select");
                if($drugName.val() == ''){
                    if(index1 < len1){
                        var obj1 = normalList[index1];
                        $drugName.val(obj1.drugName);
                        $drugName.attr("data-id", obj1.drugCode);
                        $tr.find(".dose").val(obj1.physicDose);
                        $unit.val(obj1.physicDoseUnitName);
                        $unit.attr("data-id", obj1.physicDoseUnit);
                        index1 ++;
                    }else{
                        break;
                    }
                }else{
                    var name = $drugName.val();
                    //如果已经填写了内容，则判断药品名称是否一样
                    for(var j1=0; j1<len1; j1++){
                        var obj1 = normalList[j1];
                        if(name == obj1.drugName){
                            //从列表中删除这个对象
                            normalList.splice(j1, 1);
                            len1 --;
                            break;
                        }
                    }
                }
            }
        }
        
        if(len2 >0){
            //填充胰岛素药品
            var index2 = 0;
            for(var i2=0; i2<6; i2++){
                var $tr = $($trs2[i2]),
                    $drugName = $tr.find(".j-drugName"),
                    $unit = $tr.find(".unit-select"),
                    $frequency = $tr.find(".frequency-select");
                if($drugName.val() == ''){
                    if(index2 < len2){
                        var obj2 = insulinList[index2];
                        $drugName.val(obj2.drugName);
                        $drugName.attr("data-id", obj2.drugCode);
                        $tr.find(".dose").val(obj2.physicDose);
                        $unit.val(obj2.physicDoseUnitName);
                        $unit.attr("data-id", obj2.physicDoseUnit);
                        index2 ++;
                    }else{
                        break;
                    }
                }else{
                    var name = $drugName.val();
                    //如果已经填写了内容，则判断药品名称是否一样
                    for(var j2=0; j2<len2; j2++){
                        var obj2 = normalList[j2];
                        if(name == obj2.drugName){
                            //从列表中删除这个对象
                            insulinList.splice(j2, 1);
                            len2 --;
                            break;
                        }
                    }
                }
            }
        }
    }
}
top.fillChooseDrugs = fillDrugsInfo;