var cur_status;
var cur_page;
function initTaskPage() {
    initQueryParams();
    initTableRowBtn();
    queryTask();
}
function initQueryParams() {
    // 仅选择日期
    $("#start_time").datetimepicker(
    {
        language:  "zh-CN",
        weekStart: 1,
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0,
        format: "yyyy-mm-dd"
    });
    // 仅选择日期
    $("#end_time").datetimepicker(
    {
        language:  "zh-CN",
        weekStart: 1,
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0,
        format: "yyyy-mm-dd"
    });
    //去上次查询保留的参数
    var store_params = $.zui.store.get('store_param_'+current_url);
    var checked_dept = null;
    var position_id = null;
    var checked_person = null;
    if(store_params) {
        checked_dept = store_params.checked_dept;
        position_id = store_params.position_id;
        checked_person = store_params.checked_person;
        $("#start_time").val(store_params.start_time.substr(0,11));
        $("#end_time").val(store_params.end_time.substr(0,11));
        $("#hasScoreList").val(store_params.hasScore);
        cur_page = store_params.currentpage;
    }
    if(roleContains("STATION")){
        checked_dept = getCurrentUser().organid;     
    }
    setFeSelect("#fsList",checked_dept);
    if(roleContains("STATION")){
        $("#fsList").attr('disabled','disabled');
    }
    setJobSelect("#jobSelect",position_id);

    setFeePersonSelect("#feePersonList",checked_person,checked_dept);

    $('#fsList').change(function(){ 
        setFeePersonSelect("#feePersonList",null,$("#fsList").val());
    }) 
    //获取页面参数
    var page_params = $.zui.store.get("page_params");
    if(page_params && page_params.status) {
        cur_status = page_params.status;
    }
    if(hasRole(ROLE_JICHA_ADMIN) && cur_status==4){
        $("#dispatchPatchBtn").show();
        $("#dispatchAllNoScoreBtn").show();            
    }
    if(roleContains("STATION") && cur_status==5){
        $("#confirmPatchBtn").show(); 
    }
    $("#checkPersonDiv").show();

    if(cur_status==4 || cur_status==5 || cur_status==6){
        $("#hasScoreDiv").show();     
    }

}
//初始化表行按钮
function initTableRowBtn() {
    $.zui.store.set("task_table_btn_2",[{func:'showCheck',text:'开始稽查',icon_class:'icon-eye-open'}]);
    $.zui.store.set("task_table_btn_3",[{func:'showCheck',text:'开始稽查',icon_class:'icon-eye-open'}]);
    $.zui.store.set("task_table_btn_7",[{func:'showContinueCheck',text:'继续稽查',icon_class:'icon-eye-open'}]);
    $.zui.store.set("task_table_btn_4",[{func:'showTaskDetail',text:'详情',icon_class:'icon-tasks'},
                                        {func:'dispatchTaskById',text:'下发',icon_class:'icon-signin'}]);
    $.zui.store.set("task_table_btn_5",[{func:'showTaskDetail',text:'详情',icon_class:'icon-tasks'}]);
    $.zui.store.set("task_table_btn_6",[{func:'showTaskDetail',text:'详情',icon_class:'icon-tasks'}]);
    $.zui.store.set("task_table_btn_21",[{func:'showApplyDetail',text:'处理',icon_class:'icon-hand-up'}]);
}
//查询任务
function queryTask(){
    var start_time = "";
    if($("#start_time").val()) start_time = $("#start_time").val()+" 00:00:00";
    var end_time = "";
    if($("#end_time").val()) end_time = $("#end_time").val()+" 23:59:59"; 
    var data = {
        "start_time": start_time,
        "end_time": end_time,
        "checked_dept": $("#fsList").val(),
        "check_status":cur_status,
        "hasScore":$("#hasScoreList").val(),
        "position_id":$("#jobSelect").val(),
        "checked_person": $("#feePersonList").val()
    }
    // console.log(data);
    var hide = false;
    if(hasRole(ROLE_STATION_ADMIN) || hasRole(ROLE_STATION) ||  hasRole(ROLE_JICHA)|| roleContains('STATION')) {
        hide = true;
    }
    var cols = [
                {width: 80, text: '序号', type: 'number', flex: true, colClass: 'text-center',field: 'num'},
                {width: 160, text: '任务名称', type: 'string', flex: true, sort: 'down',field: 'name'},
                {width: 80, text: '考核人员', type: 'string', flex: true, colClass: '',field: 'checked_person_name'},
                {width: 160, text: '考核部门', type: 'string', flex: true, sort: 'down',field: 'checked_dept_name'},
                {width: 80, text: '稽查人员', type: 'string', flex: true, hide:hide,colClass: '',field: 'checkman_name'},
                {width: 160, text: '稽查时间段', type: 'string', flex: true, sort: 'down',field: 'check_period'},
                // {width: 120, text: '状态', type: 'string', flex: true, colClass: '',field: 'check_status_name'}
            ];
    var colFunc = {width: 120, text: '操作', type: 'string', flex: true, field: 'id'};   
    colFunc.oper = $.zui.store.get("task_table_btn_"+cur_status);
    cols.push(colFunc);
    //只有下发才显示复选框
    var checkable = false;
    if((hasRole(ROLE_JICHA_ADMIN) && cur_status==4)||(roleContains("STATION") && cur_status==5)){
        checkable = true;
    }
    console.log("checkable:"+checkable);
    if(cur_status==2 || cur_status==3){
        data.check_status_arr = [2,3];
    }
    taskTableObj = $('#task_list_table').mytable({'cols':cols,
                            'checkable':checkable,
                            'url':"/task/getTaskList/",
                            'param':data,
                            'pager': {
                                    'p_cur': cur_page
                                }
                            });
    $.zui.store.set('store_param_'+current_url,data);
}
//进入稽查页面
function showCheck(id){
    // $('#myModal').modal({name:"dd"});
    $.checkTask =getItemByIdFromArr(id,$('#task_list_table').mytable('getTableData'));
    $.checkTask.appeal = null;
    //开始稽查
    no_return_common_service('/task/update', {"id":$.checkTask.id,"check_status":3});
    
    changePage("/view/mytask/check.html",taskTableObj);
}
//进入继续稽查页面
function showContinueCheck(id){
    // $('#myModal').modal({name:"dd"});
    $.checkTask =getItemByIdFromArr(id,$('#task_list_table').mytable('getTableData'));
    $.checkTask.appeal = null;
    changePage("/view/mytask/check.html",taskTableObj);
}
//处置无效任务申请
function showApplyDetail(id){
    layer.open({
        type: 1,
        area: ['400px','500px'],
        title: '申请处理',
        closeBtn: 1,
        shadeClose: true,
        skin: 'layui-layer-lan',
        content: $('#apply_detail_div'),
        btn: ['同意', '拒绝'],
        btnAlign: 'c', //按钮居中
        shade: 0 ,//不显示遮罩
        yes: function(index){
            aggreeApply(id);
            layer.close(index);
        },
        btn2: function(index){
            refuseApply(id)
            layer.close(index);
        }
    });
    var param = {
        'id':id
    };
    post_common_service('/checkApply/getByTaskId', param, function(data) {
        $('#apply_man').val(data.apply_man);
        $('#apply_time').val(data.apply_time);
        $('#apply_reason').val(data.apply_reason);
        $('#apply_id').val(data.id);        
    });
}
//同意申请
function aggreeApply(taskId){
    var param = {
        'id':$('#apply_id').val(),
        'task_id':taskId
    };
    addOrUpdateItem4Common(param,'/checkApply/agree',queryTask);
}
//拒绝申请
function refuseApply(taskId){
     var param = {
        'id':$('#apply_id').val(),
        'task_id':taskId
    };
    addOrUpdateItem4Common(param,'/checkApply/refuse',queryTask);
}
//任务详情页面
function showTaskDetail(id){
    var rowData=getItemByIdFromArr(id,$('#task_list_table').mytable('getTableData'));
    $.checkTask = rowData;
    if(typeof($.checkTask)!="undefined" && typeof($.checkTask.appeal) != "undefined"){
        $.checkTask.appeal = null;
    }
      
    changePage("/view/mytask/taskDetail.html",taskTableObj);
}
//下发所有任务
function dispatchTaskPatch(){
    var param = {
        "check_status":4,
        "dispatch_ids":$('#task_list_table').mytable('getTableCheckedIds')
    }
    // console.log("放假啦:"+param.dispatch_ids);
    if(!param.dispatch_ids || param.dispatch_ids.length==0){
        layer.msg('请选择下发任务！', {
            time: 2000//20s后自动关闭
        });
        return;
    }
    layer.confirm('确定下发选中任务？', {
        btn: ['确定','取消'] //按钮
    }, function(){
        no_return_common_service('/task/dispatch', param, function(data){
            queryTask();
            layer.msg(data, {
                time: 2000//20s后自动关闭
            });
        });
    }, function(index){
        layer.close(index);
    });
   var datas = $('#task_list_table').mytable('getTableData');
//    console.log(datas);
}
//下发单条任务
function dispatchTaskById(id){
    layer.confirm('确定下发任务？', {
        btn: ['确定','取消'] //按钮
    }, function(){
       var param = {
            "id": id,
            "check_status":5
        }
       no_return_common_service('/task/dispatchById', param, function(data){
            queryTask();
            layer.msg(data, {
                time: 2000//20s后自动关闭
            });
        });
    }, function(index){
        layer.close(index);
    });
    
}
function dispatchAllNoScoreTask(){
    layer.confirm('确定下发选择时间内所有无扣分任务？', {
        btn: ['确定','取消'] //按钮
    }, function(){
        var start_time = "";
        if($("#start_time").val()) start_time = $("#start_time").val()+" 00:00:00";
        var end_time = "";
        if($("#end_time").val()) end_time = $("#end_time").val()+" 23:59:59"; 
        var param = {
            "start_time": start_time,
            "end_time": end_time
        }
        no_return_common_service('/task/dispatchAllNoScoreTask', param, function(data){
            queryTask();
            layer.msg(data, {
                time: 2000//20s后自动关闭
            });
        });
    }, function(index){
        layer.close(index);
    });
}

function confirmTaskPatch(){
    var param = {
        "check_status":5,
        "dispatch_ids":$('#task_list_table').mytable('getTableCheckedIds')
    }
    if(!param.dispatch_ids) {
        layer.msg("请选择需确认任务！", {time: 2000//20s后自动关闭
                                        });
        return;
    }
    layer.confirm('确定确认选中任务？', {
        btn: ['确定','取消'] //按钮
    }, function(){
        no_return_common_service('/task/confirm', param, function(data){
            queryTask();
            layer.msg(data, {
                time: 2000//20s后自动关闭
            });
        });
    }, function(index){
        layer.close(index);
    });
//    var datas = $('#task_list_table').mytable('getTableData');
//    console.log(datas);
}