//获取团队信息
var request = getRequest(),
    teamCode = request.id,
    isLeader = request.isLeader || true;
//记录页面控件的值
var startDate = '', 
    endDate = '',
    state = '', //状态
    dispensaryType = '', //配送方式
    page = 1,
    size = 10,
    hospital = '', //服务站code
    allocationType, //是否是待分配续方
    nameKey, //搜索的姓名
    selectItemNum = 0, //选中的数量
    selectItem = [], //选中的订单号集合
    isArrange = false, // 判断所选的订单是否是可分配的
    totalOrderCount = 0,
    totalHealthDoctorCount = 0,
    selectDoctor; //选中的医生
$(function(){
    //非团队长隐藏操作按钮
    if(!isLeader){
        $("#arrange").hide();
    }
    //填充下拉框数据
    orderAPI.getFilterInfo().then(function(res){
        fillDropDown(res);
        //获得续方订单列表
        getPrescriptionList();
    });
    //获得服务站数据
    orderAPI.getHospitalList({data: {teamCode: teamCode}}).then(function(res){
        var html = template('address_tmpl', {list: res.data});
        $("#address").empty().append(html);
    });
    bindEvents();
});

//获得续方订单列表
function getPrescriptionList( refresh){
    var params = {
        teamCode: teamCode,
        startDate: startDate,
        endDate: endDate,
        state: state,
        dispensaryType: dispensaryType,
        hospital: hospital,
        allocationType: allocationType,
        nameKey: nameKey
    };
    //先请求获得所有的数量
    orderAPI.getOrderListCount({data:params}).then(function(res){
        if(res.status == 200){
            totalOrderCount = res.data.total;
            if(refresh){
                $("#prescriptTable").bootstrapTable('refresh');
            }
            var options = $.extend(orderAPI.getOrderListTableAjaxObj, {
                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);
                        var address = "";
                        if(o.dispensaryType == 2){
                            address = o.patientHospitalAddress;
                            o.expressageName = o.expressageHospitalName;
                        }else{
                            address = o.expressageHospitalName;
                        }
                        o.address = address;
                        o.action = '<a class="c-12b7f5" href="prescription-main.html?code='+o.code+'&patiCode='+o.patientCode+'&teamCode='+teamCode+'&tab=2">查看</a>';
                        o.checkbox = '<input name="orderItem" type="checkbox" class="icon-checkbox" data-status="'+o.status+'" data-type="'+o.dispensaryType+'" data-expressage="'+o.expressageCode+'" data-code="'+o.code+'">';
                        return o;
                    });
                    
                    return {
                        rows: data,
                        total: totalOrderCount
                    }
                }
            })
            $("#prescriptTable").bootstrapTable(options);
        }
    });
    
}

function queryParams(params) {
    console.log(params);
    //当表格数据变化的时候，则取消全选按钮，然后之前的选中的信息将取消选中
    page = params.offset/params.limit + 1;
    selectItemNum = 0;
    $("#selectAll").prop("checked", false);
    $("#selectedCount").text(0);
    $("#arrange").addClass("disabled");
    
    return {
        teamCode: teamCode,
        page: params.offset/params.limit + 1,
        size: params.limit,
        startDate: startDate,
        endDate: endDate,
        state: state,
        dispensaryType: dispensaryType,
        hospital: hospital,
        allocationType: allocationType,
        nameKey: nameKey
    };
}

//获得健管师列表
function getHealthDoctorList(isRefresh){
    if(isRefresh){
        $("#hDoctor").bootstrapTable('refresh');
    }
    var options = $.extend(orderAPI.getHealthDoctorTableAjaxObj, {
        queryParams: queryParams2,
        queryParamsType: "limit",
        pagination: true,
        paginationLoop: true,
        sidePagination: 'server',
        pageNumber: 1,
        pageSize: 8,
        pageList: [5,8,10],
        responseHandler: function (res) {
            return {
                rows: res.data.doctors,
                total: res.data.total
            }
        },
        columns: [{
            field: 'photo',
            title: '',
            width: '50',
            formatter: function(val, row, index){
                var url = "img/d-male.png";
                if(val.indexOf("http")>-1 || val.indexOf("https")>-1){
                    url = val;
                }
                return '<img src="'+url+'" class="img-circle" width="40">';
            }
        }, {
            field: 'name',
            title: '',
            align: 'left'
        },{
            field: 'jobName',
            title: '职称',
            align: 'right'
        }],
        onClickRow: function(row, $el){
            $("#orderCount").text(selectItemNum);
            $("#docInfo").text(row.name+row.jobName);
            $("#confirmModal").modal('toggle');
            selectDoctor = row.code;
        }
    });
    $("#hDoctor").bootstrapTable(options);
}

function queryParams2(params) {
    console.log(params);
    //当表格数据变化的时候，则取消全选按钮，然后之前的选中的信息将取消选中
    return {
        page: params.offset/params.limit + 1,
        size: params.limit,
        name: $.trim($("#doctorName").val())
    };
}

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

        var expressHtml = template('express_tmpl', {list: res.data.dispensaryTypes});
        $("#express").append(expressHtml);
    }else{

    }
}

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

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

    $("#express").on('change', function(){
        dispensaryType = $(this).val();
        if(dispensaryType == 3){ //健管师配送时，显示复选框
            $("#checkboxBox").removeClass("hidden");
        }else{
            $("#checkboxBox").addClass("hidden");
            $("#allocationType").prop("checked", false);
            allocationType = 0;
        }
        getPrescriptionList(true);
    });
    
    $("#address").on('change', function(){
        hospital = $(this).val();
        getPrescriptionList(true);
    });

    $("#allocationType").on('change', function(){
        var $this = $(this);
        if($this.prop('checked')){
            allocationType = 1;
        }else{
            allocationType = 0;
        }
        getPrescriptionList(true);
    });

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

    $("#selectAll").on('click', function(){
        var $this = $(this),
            $checkbox = $("input[name=orderItem]"),
            length = $checkbox.length;
        if($this.prop("checked")){
            $checkbox.prop("checked", true);
            selectItemNum = length;
            $("#selectedCount").text(selectItemNum);
        }else{
            $checkbox.prop("checked", false);
            selectItemNum = 0;
            $("#selectedCount").text(0);
        }
        checkArrangeDisable('all');
    });

    $("body").on('click', "input[name=orderItem]", function(){
        var $this = $(this),
            status = $this.data('status'),
            type = $this.data('type'),
            expressage = $this.data('expressage'),
            code = $this.data('code');
        if($this.prop("checked")){
            selectItemNum ++;
            if((type == 3) && (status >= 50) && (expressage=='' || !expressage)){
                selectItem.push(code);
            }
        }else{
            selectItemNum --;
            if(selectItem.indexOf(code) > -1){
                var index = selectItem.indexOf(code);
                selectItem.splice(index,1);
            }
        }
        $("#selectedCount").text(selectItemNum);
        checkArrangeDisable();
    });

    $("#arrange").on('click', function(){
        if($(this).hasClass("disabled")){
            return false;
        }
        $('#myModal').modal('toggle');
        getHealthDoctorList();
    });

    $("#doctorName").on('keyup', function(e){
        if (e.which === 13) {
            getHealthDoctorList(true);
        }
    });

    $("#confirmBtn").on('click', function(){
        //发送请求确认的请求
        var params = {
            codes: selectItem.join(","),
            healthDoctor: selectDoctor
        }
        orderAPI.distributeHealthDoctor({data: params}).then(function(res){
            if(res.status == 200){
                $('#myModal').modal('toggle');
                $('#confirmModal').modal('toggle');
                $("#prescriptTable").bootstrapTable('refresh');
            }else{

            }
        })
    });
}


//判断选中的订单是否是可分配的的订单
function checkArrangeDisable(clickType){ //type=all 为点击全选时处理
    //可以分配的条件，1是健管师配送订单，2状态为待分配
    var $checkbox = $("input[name=orderItem]:checked"),
        len = $checkbox.length;
    isArrange = false;
    if(clickType == 'all'){
        selectItem = [];
    }
    for(var i=0; i<len; i++){
        var $item = $($checkbox[i]),
            status = $item.data('status'),
            type = $item.data('type'),
            expressage = $item.data('expressage'),
            code = $item.data('code');
        if(type != 3){
            isArrange = false;
            break;
        }else{
            if((status >= 50) && (expressage=='' || !expressage)){ //支付成功后状态+配送员的名字为空为待分配状态
                isArrange = true;
                if(clickType == 'all'){
                    selectItem.push(code);
                }
            }else{
                isArrange = false;
                break;
            }
        }
    }
    if(!isArrange){
        $("#arrange").addClass("disabled");
    }else{
        $("#arrange").removeClass("disabled");
    }
}