//获取团队信息
var request = getRequest(),
    teamCode = request.id || '',
    type = request.type;
//记录页面控件的值
var startDate = '', 
    endDate = '',
    state = '', //状态
    dispensaryType = '', //配送方式
    page = 1,
    size = 10,
    hospital, //服务站code
    allocationType, //是否是待分配续方
    nameKey, //搜索的姓名
    totalOrderCount = 0,
    selectDoctor; //选中的医生
$(function(){
    //填充下拉框数据
    orderAPI.getHFilterInfo().then(function(res){
        fillDropDown(res);
        //获得续方订单列表
        getPrescriptionList();
    });
    bindEvents();
});

//获得续方订单列表
function getPrescriptionList( refresh){
    var params = {
        type: type,
        teamCode: teamCode,
        startDate: startDate,
        endDate: endDate,
        state: state,
        dispensaryType: 3,
        hospital: hospital,
        nameKey: nameKey
    };
    //先请求获得所有的数量
    orderAPI.getHOrderListCount({data:params}).then(function(res){
        if(res.status == 200){
            totalOrderCount = res.data.total;
            if(refresh){
                $("#prescriptTable").bootstrapTable('refresh');
            }
            var options = $.extend(orderAPI.getHOrderListTableAjaxObj, {
                queryParams: queryParams,
                queryParamsType: "limit",
                pagination: true,
                paginationLoop: true,
                sidePagination: 'server',
                pageNumber: 1,
                pageSize: 10,
                responseHandler: function (res) {
                    var data = _.map(res.data, function(o){
                        var result = "";
                        for(var i=0; i<o.prescriptionDt.length; i++){
                            if(i>0){
                                result += ','+o.prescriptionDt[i].name;
                            }else{
                                result += o.prescriptionDt[i].name;
                            }
                        }
                        o.result = result;
                        o.statusName = getStatusName(o.status);
                        o.express = getExpressName(o.dispensaryType);
                        o.address = address;
                        o.action = '<a class="c-12b7f5" href="">操作</a>';
                        return o;
                    });
                    
                    return {
                        rows: data,
                        total: totalOrderCount
                    }
                }
            })
            $("#prescriptTable").bootstrapTable(options);
        }
    });
    
}

function queryParams(params) {
    return {
        type: type,
        page: params.offset/params.limit + 1,
        size: params.limit,
        startDate: startDate,
        endDate: endDate,
        state: state,
        hospital: hospital,
        dispensaryType: 3,
        teamCode: teamCode,
        nameKey: nameKey
    };
}

function fillDropDown(res){
    if(res.status == 200){
        var stateHtml = template('state_tmpl', {list: res.data.states});
        $("#orderStatus").append(stateHtml);

        var expressHtml = template('address_tmpl', {list: res.data.hospitals});
        $("#address").append(expressHtml);
    }else{

    }
}

//绑定事件
function bindEvents(){
    $(".n-tab").on('click', function(){
        if($(this).hasClass("active")){
            return false;
        }else{
            $(this).addClass("active");
            $(this).siblings().removeClass("active");
            getStartEndDate($(this).attr("data-val"));
            getPrescriptionList(true);
        }
    });

    $("#orderStatus").on('change', function(){
        var $this = $(this);
        state = $this.val();
        getPrescriptionList(true);
    });
    
    $("#address").on('change', function(){
        hospital = $(this).val();
        getPrescriptionList(true);
    });

    $("#searchBtn").on('click', function(){
        var $input = $("#searchName"),
            text = $.trim($input.val());
        nameKey = text;
        getPrescriptionList(true);
    });

}

//根据选择的tab获得开始和结束时间
function getStartEndDate(index){
    var now = new Date(),
        sDate = new Date();
    endDate = now.format('yyyy-MM-dd');
    switch (index){
        case '0':
            startDate = '';
            endDate = '';
            break;
        case '1': //近一周
            sDate.setDate(now.getDate() - 7);
            startDate = sDate.format('yyyy-MM-dd');
            break;
        case '2': //近一个月
            sDate.setMonth(now.getMonth() -1);
            startDate = sDate.format('yyyy-MM-dd');
            break;
        case '3': //近半年
            sDate.setMonth(now.getMonth() - 6);
            startDate = sDate.format('yyyy-MM-dd');
            break;
        case '4': //近一年
            sDate.setFullYear(now.getFullYear() - 1);
            startDate = sDate.format('yyyy-MM-dd');
            break;
    }
    
}

//获得状态值
//续方各状态返回值
//（-3 支付过期 -2 患者自己取消 ）续方取消，
//-1 审核不通过 ,
//（0 待审核, 2调整中，3调整成功, 4调整失败 ,10 医生审核(CA)通过）审核中，
//20药师审核中,
//21.药师审核失败,
//30 开方中/药师审核成功,
//31.开方失败,
//（40开方完成/待支付 ，41 支付失败 ）待支付， 
// 50 支付成功/待配药，
//（60配药成功/待配送）等待领药，
//（61配送失败62分配健管师 65配送中，69配送到服务站）配送中，
//（100配送到患者手中/已完成）已完成
//根据状态获得相关信息
function getStatusName(status){
    var name = "",
        img = "";
    status = status + '';
    switch (status){
        case '-3':
            name = '支付过期';
            break;
        case '-2':
            name = '患者自己取消';
            break;
        case '-1':
            name = '审核不通过';
            break;
        case '0':
        case '2':
        case '3':
        case '4':
        case '10':
            name = '审核中';
            break;
        case '20':
            name = '药师审核中';
            break;
        case '21':
            name = '药师审核失败';
            break;
        case '30':
            name = '开方中';
            break;
        case '31':
            name = '开方失败';
            break;
        case '40':
            name = '待支付';
            break;
        case '41':
            name = '支付失败';
            break;
        case '50':
            name = '配药中';
            break;
        case '60':
            name = '等待领药';
            break;
        case '61':
        case '62':
        case '65':
        case '69':
            name = '配送中';
            break;
        case '100':
            name = '已完成';
            break;
        default:
            break;
    }
    return name;
}

function getExpressName(type){
    switch(type){
        case 1: 
            return '自取';
            break;
        case 2:
            return '快递配送';
            break;
        case 3:
            return '健管师配送';
            break;
    }
}