var selectedData = { cols: [], array: [] };
var checkusersselect = null;
var checkuserlist = null;
var tabledatagride = null;
$(document).ready(function() {
    $.jeDate("#month_date", {
        isinitVal: true,
        format: 'YYYY/MM' // 分隔符可以任意定义，该例子表示只显示年月
    });
    $("#month_date").val(getCurrentTimeFormat());
    var checked_dept = null;
    if (roleContains("FWQ")) {
        checked_dept = getCurrentUser().organid;
    }
    setSASelecttemp("#qzd", checked_dept);

    //默认值 $("#qzd").val()
    var dd = 89;
    if ($("#qzd").val() != "") {
        dd = $("#qzd").val();
    }
    inittAreaable($("#month_date").val(), dd);

    initselecttable();

    laydate.render({
        elem: '#starttime',
        type: 'time'
    });
    laydate.render({
        elem: '#endtime',
        type: 'time'
    });




});

var arealist = null;
var stimemonth = null;

function initselecttable() {
    selectedData = { cols: [], array: [], cache: false };
    selectedData.cols.push({ width: 0.3, name: "time", label: '时间', style: { 'text-align': 'center', 'line-height': '34px' } });
    selectedData.cols.push({ width: 0.2, name: "dept_name", label: '部门', style: { 'text-align': 'center', 'line-height': '34px' } });
    selectedData.cols.push({ width: 0.2, name: "area_name", label: '区域', style: { 'text-align': 'center', 'line-height': '34px' } });
    selectedData.cols.push({ width: 0.3, name: "option", label: '操作', html: true, style: { 'text-align': 'center', 'line-height': '34px' } });
    reloadtable();

}

function reloadtable() {

    $('#selected_table').datagrid({
        dataSource: selectedData,
        states: { fixedTopUntil: 0 },
        rowDefaultHeight: 50,
        height: 200,
    });

}
var layindex = null;
var taskMap = new HashMap();

function inittAreaable(time, dept) {

    layindex = layer.load(0, { shade: false });
    var t = time.replace("/", "-") + "";
    var endtime = moment(t + "-25T23:00:00", "YYYY-MM-DD HH:mm:ss");
    var starttime = moment(moment(t + "-25T23:00:00", "YYYY-MM-DD HH:mm:ss").subtract(1, 'month'));


    var param1 = { "start_time": starttime.format("YYYY-MM-DD HH:mm:ss"), "end_time": endtime.format("YYYY-MM-DD HH:mm:ss"), "checked_dept": dept }
    post_common_service("/f/task/getall/0/0", param1, function(taskdata) {

        taskMap = new HashMap();
        taskdata.forEach(t => {
            var key = t.area_id + "_" + moment(t.start_time).format("YYYY-MM-DD");
            if (taskMap.get(key) != null) {
                var list = taskMap.get(key);
                list.push(t);
                taskMap.set(key, list);
            } else {
                var list = [];
                list.push(t);
                taskMap.set(key, list);
            }

        });


        var param = { "dept_id": dept };
        post_common_service('/f/area/getall', param, function(redata) {

            layer.close(layer.index);
            var data = redata.areas;
            checkuserlist = redata.checkusers;

            var datac = { cols: [], array: [] };

            var days = endtime.diff(starttime, 'days');

            datac.cols.push({ width: 120, name: 'type', label: "", });

            for (var i = 1; i <= days; i++) {
                var temp = moment(moment(t + "-25T23:00:00", "YYYY-MM-DD HH:mm:ss").subtract(1, 'month'));
                var currentday = temp.add(i, "day");
                var day = currentday.date();
                datac.cols.push({ width: 80, name: "day_" + i, label: currentday.format("MM-DD"), html: true, className: "table_content" });
            }
            arealist = data;
            stimemonth = time;

            for (var index in data) {
                var area = data[index];
                var data_table = {};
                data_table.type = area.name;
                for (var i = 1; i <= days; i++) {
                    //内容
                    var temp = moment(moment(t + "-25T23:00:00", "YYYY-MM-DD HH:mm:ss").subtract(1, 'month'));
                    var currentday = temp.add(i, "day");
                    var key = area.id + "_" + currentday.format("YYYY-MM-DD");

                    var temphtml = "";

                    if (taskMap.get(key) != null) {
                        //存在稽查记录
                        var list = taskMap.get(key);
                        var hasc = 0;
                        var invc = 0;
                        list.forEach(t => {
                            if (t.check_status == 4 || t.check_status == 16 || t.check_status == 6) {
                                //完成稽查
                                hasc++;
                            }
                            if (t.check_status == 22) {
                                //存在无效任务
                                invc++;
                            }
                        });
                        //无效
                        if (invc == list.length) {
                            temphtml = '<div class="btn-group btn_c" data-toggle="buttons" id="div_' + area.id + '_' + i + '" >' +
                                '<label class="btn btn-info6" >' +
                                '<input type="checkbox" name="options" onchange="selectedTask(this)" id="' + area.id + '_' + i + '"> 无效' +
                                '</label>';
                        } else
                        //已完成
                        if (hasc + invc == list.length) {
                            temphtml = '<div class="btn-group btn_c" data-toggle="buttons"  id="div_' + area.id + '_' + i + '">' +
                                '<label class="btn btn-info5 " >' +
                                '<input type="checkbox" name="options" onchange="selectedTask(this)" id="' + area.id + '_' + i + '"> 已稽查' +
                                '</label>';
                        } else {
                            //进行中
                            temphtml = '<div class="btn-group btn_c" data-toggle="buttons" id="div_' + area.id + '_' + i + '" >' +
                                '<label class="btn btn-info3" >' +
                                '<input type="checkbox" name="options" onchange="selectedTask(this)" id="' + area.id + '_' + i + '"> 稽查中' +
                                '</label>';
                        }


                    } else {
                        //不存在稽查
                        temphtml = '<div class="btn-group btn_c" data-toggle="buttons" id="div_' + area.id + '_' + i + '" >' +
                            '<label class="btn btn-info2" >' +
                            '<input type="checkbox" name="options" onchange="selectedTask(this)" id="' + area.id + '_' + i + '"> 待稽查' +
                            '</label>';
                    }

                    data_table["day_" + i] = temphtml;
                }
                datac.array.push(data_table);
            }

            if (tabledatagride != null) {
                tabledatagride.dataSource.data = null;
                tabledatagride.setDataSource(datac);
                tabledatagride.setPager(1, datac.array.length, datac.array.length);
                tabledatagride.render();
            } else {
                $('#table_s').datagrid({
                    dataSource: datac,
                    states: { fixedLeftUntil: 1, fixedTopUntil: 0 },
                    showRowIndex: false,

                    onRender: function() {



                        $(".btn_c").mouseover(function() {
                            var tempids = this.id.split("_");
                            var t = stimemonth.replace("/", "-") + "";
                            var starttime = moment(moment(t + "-25T23:00:00", "YYYY-MM-DD HH:mm:ss").subtract(1, 'month'));
                            var ctime = starttime.add(tempids[2], "day");
                            var key = tempids[1] + "_" + ctime.format("YYYY-MM-DD");
                            if (taskMap.get(key) != null) {
                                var temphtml = "";
                                var list = taskMap.get(key);

                                list.forEach(t => {
                                    var startus = "";
                                    if (t.check_status == 4 || t.check_status == 16 || t.check_status == 6) {
                                        startus = "已完成";
                                    } else
                                    if (t.check_status == 22) {
                                        startus = "无效";
                                    } else {
                                        startus = "进行中";
                                    }
                                    temphtml += '<tr><td>' + moment(t.start_time).format("HH:mm:ss") + '</td><td>' + moment(t.end_time).format("HH:mm:ss") + '</td><td>' + startus + '</td></tr>';
                                });

                                var thtml = '<table border=1 style="border:solid 1px;width:180px;"><tr><th>开始时间</th><th>结束时间</th><th>状态</th></tr>' + temphtml + '</table>';
                                layer.tips(thtml, "#" + this.id, {
                                    tips: [1, '#8e8e8e'],
                                    time: 0,
                                    width: '240px'
                                });
                            }
                        });
                        $(".btn_c").mouseout(function() {
                            layer.close(layer.index);
                        });


                    },
                    configs: {
                        C1: { className: "datagrid-cell-index", style: { 'text-align': 'center', } },
                        R0: { style: { 'text-align': 'center', 'line-height': '36px' } }
                    }
                });
                tabledatagride = $('#table_s').data('zui.datagrid');
            }




            for (var index in checkuserlist) {
                var p = checkuserlist[index];
                p.title = p.truename;
            }


            if (checkusersselect != null) {
                reset();
            } else {
                checkusersselect = $('#check_users').comboTree({
                    source: checkuserlist,
                    isMultiple: true
                });
            }

        });

    });
}

function reset() {
    initselecttable();
    var myDataGrid = $('#selected_table').data('zui.datagrid');
    myDataGrid.dataSource.data = null;
    myDataGrid.setDataSource(selectedData);
    myDataGrid.setPager(1, selectedData.array.length, selectedData.array.length);
    myDataGrid.render();

    if (checkusersselect != null) {
        $("#check_users").val("");
        checkusersselect.unbind();
        checkusersselect.closeDropDownMenu();
        checkusersselect.bindings();
        $(".ComboTreeItemChlid").find("input").prop('checked', false);


    }
    $("#starttime").val("");
    $("#endtime").val("");



}


function selectedTask(obj) {
    changeListItem(obj.id);

}

function removeListItem(obj) {
    var ids = obj.id.split("delete_");

    $("#" + ids[1]).parent().removeClass("active");
    $("#" + ids[1]).prop("checked", false);
    changeListItem(ids[1]);

}

function changeListItem(id) {
    var tempids = id.split("_");
    var t = stimemonth.replace("/", "-") + "";
    var starttime = moment(moment(t + "-25T23:00:00", "YYYY-MM-DD HH:mm:ss").subtract(1, 'month'));
    var ctime = starttime.add(tempids[1], "day");
    var carea = null;
    for (var i in arealist) {
        var a = arealist[i];
        if (a.id == tempids[0]) {
            carea = a;
        }
    }


    if ($("#" + id).prop('checked')) {
        addlisttable(carea, ctime, id);
    } else {
        removelisttable(carea, ctime);
    }
}


function addlisttable(area, time, id) {
    var feeList = $.zui.store.get("cache_sa_station_list");
    var dept_info = null;
    for (var index in feeList) {
        var dept = feeList[index];
        if (area.dept_id == dept.deptid) {
            dept_info = dept;
        }
    }
    id = trim(id);
    var btn = '<button class="btn btn-primary" type="button" onclick="removeListItem(this)" id="delete_' + id + '">删除</button>';
    selectedData.array.push({ "time": time.format("YYYY-MM-DD"), "dept_name": dept_info.name, "area_name": area.name, "option": btn, areaInfo: area, deptInfo: dept_info });

    var myDataGrid = $('#selected_table').data('zui.datagrid');
    myDataGrid.dataSource.data = null;
    myDataGrid.setDataSource(selectedData);
    myDataGrid.setPager(1, selectedData.array.length, selectedData.array.length);
    myDataGrid.render();

    // $('#selected_table').data('zui.datagrid').setDataSource(selectedData);
    // $('#selected_table').data('zui.datagrid').renderData();
}

function removelisttable(area, time) {
    for (var index in selectedData.array) {
        var o = selectedData.array[index];
        if (o != null && o.areaInfo.id == area.id && time.format("YYYY-MM-DD") == o.time) {
            selectedData.array.splice(index, 1);
        }
    }
    var myDataGrid = $('#selected_table').data('zui.datagrid');
    myDataGrid.dataSource.data = null;
    myDataGrid.setDataSource(selectedData);
    myDataGrid.setPager(1, selectedData.array.length, selectedData.array.length);

    myDataGrid.render();
    //reloadtable();
}



function search() {
    inittAreaable($("#month_date").val(), $("#qzd").val());

}


function addTask() {
    //获取列表
    var tasklist = selectedData.array;
    var start_time = $("#starttime").val();
    var end_time = $("#endtime").val();

    if (start_time == "" || end_time == "") {
        layer.msg('须选择稽查时间段！', {
            time: 2000, //20s后自动关闭
        });
        return;
    }
    if (moment("2018-01-01 " + end_time).valueOf() - moment("2018-01-01 " + start_time).valueOf() < 15 * 60 * 1000) {
        layer.msg('稽查时间段需满足15分钟以上！', {
            time: 2000, //20s后自动关闭
        });
        return;
    }
    if (tasklist.length < 1) {
        layer.msg('未选择任务区域！', {
            time: 2000, //20s后自动关闭
        });
        return;
    }


    var check_user_list = checkusersselect.getSelectedItemsId();
    tasklist.forEach(t => {
        t.start_time = t.time + " " + start_time;
        t.end_time = t.time + " " + end_time;
    });

    var param = { "userids": check_user_list, "checkAreaData": tasklist };
    post_common_service('/f/task/add', param, function(redata) {
        // layer.msg('已添加', { icon: 1 });
        inittAreaable($("#month_date").val(), $("#qzd").val());
    });


}