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);
}

var requiredFields=[];

var project_data = gTemplate[pro_id]; //获得模板中的数据显示
    
$(function(){
    if(pro_id == 9){
        $("#submitBtn").text("保存");
    }
    getProjectData();
    bindEvents();
});

function getProjectData(){
    var params = {
        id: fv_id,
        followupProject: pro_id
    }
    followupAPI.getFollowupProjectData(params).then(function(res){
        if(res.status == 200){
            if(pro_id == 5){
                if(fv_class == 1){//高血压
                    project_data = _.pick(project_data, 'HYP_FOLLOWUP_TYPE_CODE', 'HYP_COMPLICATION_DETAIL');
                }else if(fv_class == 2){//糖尿病
                    project_data = _.pick(project_data, 'DIA_FOLLOWUP_TYPE_CODE', 'DIA_COMPLICATION_DETAIL');
                }
            }
            
            for(key in project_data){
                project_data[key].value = res.data?res.data[key]:'';
                if(project_data[key].type==4 || project_data[key].type==3) {
                    if(project_data[key].value){
                        project_data[key].valueLength = project_data[key].value.length;
                    }
                }
                if(project_data[key].type==5){
                    var isRequired = project_data[key].required;
                    for(var i = 0; i<project_data[key].items.length; i++){
                        var it = project_data[key].items[i];
                        it.value = res.data ? res.data[it.name]:'';
                        
                        if(isRequired){
                            var isEmpty = it.value == "" ? true : false;
                            requiredFields.push({
                                name: it.name,
                                type: it.type,
                                textType: it.textType
                            });
                        }
                    }
                }else{
                    //非并联控件的field的required的处理
                    if(project_data[key].required){
                        var isEmpty = project_data[key].value == "" ? true : false;
                        requiredFields.push({
                            name: key,
                            type: project_data[key].type,
                            textType: project_data[key].textType
                        });
                    }
                }
            }
            
            var html = template("item", {
                data:project_data,
                followupClass:fv_class, 
                pro_id: pro_id,
                title: decodeURI(title)
            });
            
            $("#question_form .form-info").append(html);
            
            if(pro_id == 7){//控制目标
                $("input[name=CONTROL_CONSTITUTOR]").val(docInfo.name);
            }
            
            $(".q-note-"+pro_id).removeClass("hidden");
            
            initChosen();
            initDatePicker();
            initPopover();
            checkBtnEnable();
        }else{
            showErrorMsg(res.msg);
        }
    });
}

function initChosen(){
    $(".my_select_box").chosen({
        disable_search: true,
        inherit_select_classes: true, //将设定的样式添加到插件的控件中
        disable_search_threshold: 10,
        no_results_text: "",
        width: "100%"
    });
}

function initDatePicker(){
    $(".date").datepicker({
        format: 'yyyy-mm-dd',
        language: 'zh-CN',
        autoclose: true,
        todayHighlight: 1,
        todayBtn: 'linked',
    });
}

function initPopover(){
    var $inputs = $("input"),
        len = $inputs.length;
    for(i=0; i<len; i++){
        var $item = $($inputs[i]),
            name = $item.attr("name");
        
        switch(name){
            case "BP_U": //血压
            case "BP_D": //血压
            case "CONTROL_BP_U": //目标血压
            case "CONTROL_BP_D": //目标血压
                $item.popover({
                    content: '<a onclick="getHistory(\''+name+'\', this)">从居民血压记录中获取</a>',
                    html: true,
                    placement: 'bottom',
                    trigger: 'focus',
                    delay: {hide: 300}
                });
                break;
            case "BS_FPG": //空腹血糖
            case "NO_BS_FPG": //餐后血糖
            case "RANDOM_BLOOD_SUGAR": //随机血糖
            case "CONTROL_BS_FPG":
            case "CONTROL_NO_BS_FPG":
                $item.popover({
                    content: '<a onclick="getHistory(\''+name+'\', this)">从居民血糖记录中获取</a>',
                    html: true,
                    placement: 'bottom',
                    trigger: 'focus',
                    delay: {hide: 300}
                });
                break;
            case "HEIGHT":
            case "WEIGHT":
                $item.popover({
                    content: '<a onclick="getHistory(\''+name+'\', this)">从居民身高体重记录中获取</a>',
                    html: true,
                    placement: 'bottom',
                    trigger: 'focus',
                    delay: {hide: 300}
                });
                break;
            default:
                break;
        }
    }
}

//获得历史记录 type： BP - 血压，
function getHistory(type, el){
    console.log(type);
    var colObj = {},
        reqType = 0,
        tableId = "",
        modalTitle = "";
    switch(type){
        case "BP_U": //血压
        case "BP_D": //血压
        case "CONTROL_BP_U": //目标血压
        case "CONTROL_BP_D":
            reqType = 2;
            tableId = "bp_table";
            modalTitle = "血压记录";
            colObj = {
                colNames: ["记录时间", "血压", "操作"],
                colModel: [
                    {name: 'time', index: 'time', width: '150', align: 'center'},
                    {name: '', index: '', width: '150',  align: 'center',
                    formatter: function(val, op, row){
                        return row.sys + ' / ' + row.dia+ ' mmHg';
                    }},
                    {name: '', index: '', width: '100', align: 'center', 
                    formatter: function(val, op, row){
                        return '<a onclick="fillHistoryData(\''+type+'\', '+ row.sys +', '+ row.dia +')">填入随访记录</a>';
                    }}
                ]
            };
            break;
        case 'HEIGHT':
        case 'WEIGHT':
            reqType = 3;
            tableId = "weight_table";
            modalTitle = "身高体重记录";
            colObj = {
                colNames: ["记录时间", "身高", "体重", "操作"],
                colModel: [
                    {name: 'time', index: 'time', width: '150', align: 'center'},
                    {name: 'height', index: 'height', width: '100',  align: 'center',
                    formatter: function(val, op, row){
                        return val + ' cm';
                    }},
                    {name: 'weight', index: 'weight', width: '100',  align: 'center',
                    formatter: function(val, op, row){
                        return val + ' Kg';
                    }},
                    {name: '', index: '', width: '100', align: 'center', 
                    formatter: function(val, op, row){
                        return '<a onclick="fillHistoryData(\''+type+'\','+row.height+','+row.weight+')">填入随访记录</a>';;
                    }}
                ]
            };
            break;
        case "BS_FPG": //空腹血糖
        case "NO_BS_FPG": //餐后血糖
        case "RANDOM_BLOOD_SUGAR": //随机血糖
        case "CONTROL_BS_FPG":
        case "CONTROL_NO_BS_FPG":
            reqType = 1;
            tableId = "bs_table";
            modalTitle = "血糖记录";
            colObj = {
                colNames: ["记录时间", "血糖", "操作"],
                colModel: [
                    {name: 'time', index: 'time', width: '150', align: 'center'},
                    {name: 'gi', index: 'gi', width: '150',  align: 'center',
                    formatter: function(val, op, row){
                        return row.gi + ' mmol/L';
                    }},
                    {name: '', index: '', width: '100', align: 'center', 
                    formatter: function(val, op, row){
                        return '<a onclick="fillHistoryData(\''+type+'\', '+ row.gi +')">填入随访记录</a>';
                    }}
                ]
            };
            break;
    }
    
    colObj.ajaxGridOptions = {
        data: {
            patient:patiCode, 
            type: reqType, 
            page:0, 
            pagesize: 10
        }
    };
    
    $("#modal-title").text(modalTitle);
    if($("#"+tableId).length == 0){
        var html = '<table id="'+tableId+'"></table>';
        $("#myModal .modal-body").empty().append(html);
        fillHistoryTable(colObj, true, tableId);
    }else{
        fillHistoryTable(colObj, false, tableId);
    }
}

//填充血压历史记录数据
function fillHistoryTable(colObj, isInit, tableId){
    console.log(colObj);
    var option = {
        height: '400px',
        rowNum: 10,
        rowList : [ 10, 20, 30 ],
        jsonReader: {
            root: 'data'
        },
        viewrecords: true,
        hidegrid: false
    };
    $.extend(true, option, followupAPI.getHistoryTableObj);
    $.extend(true, option, colObj);
    if(isInit){
        $("#"+tableId).jqGrid(option);
    }else{
        $("#"+tableId).clearGridData();
        $("#"+tableId).jqGrid('setGridParam', colObj);
        $("#"+tableId).trigger("reloadGrid");
    }
    
    $("#myModal").modal('toggle');
}

//将选中的历史信息填写到随访记录中
function fillHistoryData(type, val1, val2){
    switch(type){
        case 'BP_D':
        case 'BP_U':
            $("input[name=BP_D]").val(val1);
            $("input[name=BP_U]").val(val2);
            break;
        case 'HEIGHT':
        case 'WEIGHT':
            $("#HEIGHT").val(val1);
            $("#WEIGHT").val(val2);
            var w = parseFloat(val2),
                h = parseFloat(val1);
            var BMI = w/(h/100 * h/100);
            if(!isNaN(BMI)){
                $("input[name=BMI]").val(BMI.toFixed(2));
            }
            break;
        case 'CONTROL_BP_D':
        case 'CONTROL_BP_U':
            $("input[name=CONTROL_BP_D]").val(val1);
            $("input[name=CONTROL_BP_U]").val(val2);
            break;
        default:
            $("input[name="+type+"]").val(val1);
            break;
    }
    checkBtnEnable();
    $("#myModal").modal('toggle');
}

//判断按钮是否可执行
function checkBtnEnable(){
    //先判断是否存在必填项目，如果没有必填项目，则至少需要填写一个
    var disabled = true;
    if(requiredFields.length == 0){
        var $inputs = $("input"),
            input_len = $inputs.length,
            $textarea = $("textarea"),
            textarea_len = $textarea.length,
            $select = $("select"),
            select_len = $select.length;
        for(var i=0; i<input_len; i++){
            var $item = $($inputs[i]),
                textType = $item.attr("type"),
                value = $item.val();
            if(textType == "radio"){
                if($item.prop("checked")){
                    disabled = false;
                    break;
                }
            }else if(textType == "checkbox"){
                if($item.prop("checked")){
                    disabled = false;
                    break;
                }
            }else{
                if(value.length > 0){
                    disabled = false;
                    break;
                }
            }
        }
    }else{
        for(var i=0; i<requiredFields.length; i++){
            var item = requiredFields[i],
                value; //目前只有下拉框、输入框、textarea
            if(item.type == 4){
                value = $("textarea[name="+item.name+"]").val();
                if(value.length > 0){
                    disabled = false;
                }else{
                    disabled = true;
                    break;
                }
            }else if(item.type == 2){ //radio
                value = $("input[name="+item.name+"]").val();
                if(value.length > 0){
                    disabled = false;
                }else{
                    disabled = true;
                    break;
                }
            }else if(item.type == 1){
                if(item.textType == 'select'){
                    value = $("select[name="+item.name+"]").val();
                    if(value != "undefined"){
                        disabled = false;
                    }else{
                        disabled = true;
                        break;
                    }
                }else{
                    value = $("input[name="+item.name+"]").val();
                    if(value.length > 0){
                        disabled = false;
                    }else{
                        disabled = true;
                        break;
                    }
                }
            }
            
        }
    }
    if(disabled){
        $("#submitBtn").addClass("disabled");
    }else{
        $("#submitBtn").removeClass("disabled");
    }
}

function submitForm(){
    if($("#submitBtn").hasClass("disabled")){
        return false;
    }
    if(pro_id == 3) { // 实验室检查，空腹血糖、餐后血糖、随机血糖、三项需必填一项
        var bsValue = $('input[name="BS_FPG"]').val() 
                        || $('input[name="NO_BS_FPG"]').val() 
                        || $('input[name="RANDOM_BLOOD_SUGAR"]').val()
        if(!bsValue) {
            showWarningMsg("血糖必填一项");
            return false;
        }
    }
    var data = {};
    $("#question_form").serializeArray().map(function(x){
        data[x.name]=x.value;
    });
    if(pro_id == 7){
        data.CONTROL_CONSTITUTOR_DOCTORCODE = docInfo.code;
    }
    var params = {
        id: fv_id,
        followupProject:pro_id,
        followupProjectData: JSON.stringify(data)
    };
    followupAPI.saveFollowupProjectData(params).then(function(res){
//      var projectName = ['症状', '体征', '实验室检查', '生活方式指导', '评价', '用药情况', '控制目标', '健康教育', '转诊'];
        if(res.status == 200){
//          var title = projectName[pro_id];
//          pro_id ++;
            if(pro_id > 9){
                //保存成功后不做任何操作。
            }else{
                //控制tab页面，跳转选中下一个tab
                parent.goFollowupNextQuestionaire();
            }
        }else{
            showErrorMsg(res.msg);
        }
    });
    return false;
}

function bindEvents(){
    //监听表单数据信息变化
    $("#question_form").on("change", "input", function(){
        //先判断数字键盘不能输入负数
        var textType = $(this).attr("type");
        if(textType == "number"){
            this.value = this.value.replace(/\-/g,"");
        }
        checkBtnEnable();
        
        var name = $(this).attr("name");
        
        //计算BMI值 体质指数（BMI）=体重（kg）÷身高^2（m）
        switch(name){
            case "WEIGHT":
            case "WEIGHT_EXP":
            case "HEIGHT":
                var w = parseFloat($("input[name=WEIGHT]").val()),
                    ex_w = parseFloat($("input[name=WEIGHT_EXP]").val()),
                    h = parseFloat($("input[name=HEIGHT]").val());
                var BMI = w/(h/100 * h/100),
                    EX_BMI = ex_w/(h/100 * h/100);
                if(!isNaN(BMI)){
                    $("input[name=BMI]").val(BMI.toFixed(2));
                }
                if(!isNaN(EX_BMI)){
                    $("input[name=BMI_EXP]").val(EX_BMI.toFixed(2));
                }
                break;
        }
    });
    
    $("#question_form").on("keypress", "input[type=number]", function(event){
        if(event.keyCode == 45){
            event.preventDefault();
        }
    })
    
    //监听下拉框的变化
    $("#question_form").on("change", "select", function(){
        checkBtnEnable();
    });
    
    //监听输入框内容变化
    $("#question_form").on("keyup", "textarea", function(){
        checkBtnEnable();
        var text = $(this).val(),
            len = text.length,
            $p = $(this).siblings();
        $p.find(".other-count").text(len);
    });
}
