{{include "com/inc.html"}}
<!-- Main Header -->
{{include "com/header.html"}}
<!-- Left side column. 权限菜单 -->
{{include "com/menu.html"}}
<div class="content-wrapper">
    <section class="content-header">
        <h1>
            <small></small>
        </h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i> 任务列表</a></li>
        </ol>
    </section>
    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-xs-12">
                <div class="box">
                    <div class="box-body">

                        <div class="form-horizontal">
                            <div class="box-body margin">
                                <h3><i class="glyphicon glyphicon-exclamation-sign" style="margin-right: 6px"></i>数据情况
                                </h3>
                                <div class="form-group" style="margin-left: 10px;margin-top: 20px">
                                    <div class="col-xs-6" style="width: auto">
                                        <label class="form-inline">数据总量：
                                            <input type="text" class="form-control" style="width: 80px" readonly value="{{.T.allNum}}"></label>
                                        <label class="form-inline" style="margin-left: 20px">已分发：
                                            <input type="text" class="form-control" style="width: 80px" readonly value="{{.T.isGiveNum}}"></label>
                                        <label class="form-inline" style="margin-left: 20px">待分发：
                                            <input type="text" class="form-control" style="width: 80px" readonly value="{{.T.isNotGiveNum}}"></label>
                                        <label class="form-inline" style="margin-left: 20px">已标注：
                                            <input type="text" class="form-control" style="width: 80px" readonly value="{{.T.isTagNum}}"></label>
                                        <label class="form-inline" style="margin-left: 20px">未标注：
                                            <input type="text" class="form-control" style="width: 80px" readonly value="{{.T.isNotTagNum}}"></label>
                                    </div>
                                    <div class="col-xs-4 form-group">
                                        <label class="form-inline">操作：
                                            <input type="button" class="btn btn-info" onclick="dispatchTask('0')" value="分发">
                                            <input type="button" class="btn btn-primary" value="质检">
                                            <input type="button" class="btn btn-success" value="质检结果">
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <hr>
                        <div class="form-horizontal">
                            <div class="box-body margin">
                                <h3><i class="glyphicon glyphicon-tasks" style="margin-right: 6px"></i>数据清洗任务列表
                                </h3>

                                <table id="dataTable" class="table table-bordered table-hover">
                                    <thead>
                                    <tr>
                                        <th></th>
                                        <th>用户账号</th>
                                        <th>项目名称</th>
                                        <th>数据量</th>
                                        <th>任务状态</th>
                                        <th>完成进度</th>
                                        <th>开始时间</th>
                                        <th>完成时间</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                </table>
                            </div>
                        </div>
                    </div>
                    <!-- /.box-body -->
                </div>
                <!-- /.box -->
            </div>
        </div>
    </section>
</div>


<div class="modal fade" id="modal-create-task" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" style="width: 60%">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <div class="edit-info">
                        <span class="glyphicon glyphicon-tasks" aria-hidden="true"></span>
                        <span class="h3">新建任务</span>
                    </div>
                    <div class="edit-form">
                        <form id="modal-form-task" class="form-horizontal">
                            <div class="modal-body modal-task">
                                <div class="form-group margin-bottom" style="margin-left: 15px">
                                    <label class="control-label form-inline h4">待分发数据总量(条)：
                                        <span id="modal-num">{{.T.isNotGiveNum}}</span>
                                    </label>
                                </div>
                                <hr>
                                <div class="form-group" style="margin-left: 15px">
                                    <label class="radio-inline">
                                        <input type="radio" name="stype" value="man" checked>手动分发
                                    </label>
                                    <label class="radio-inline">
                                        <input type="radio" name="stype" value="auto">自动分发
                                    </label>
                                </div>
                                <div id="task-man">
                                    <div id="TaskDiv">
                                        <div id="itemDiv" class="form-group" style="margin-left: 10px;display: none">
                                            <select id="group-select-clone"></select>
                                            <label class="control-label form-inline" style="margin-left: 20px">数据量(条)：
                                                <input type="number" class="form-control"></label>
                                        </div>
                                        <div class="form-group group-item" style="margin-left: 10px;">
                                            <select class="selectpicker" id="group-select"></select>
                                            <label class="control-label form-inline" style="margin-left: 20px">数据量(条)：
                                                <input type="number" class="form-control"></label>
                                            <input type="button" class="btn btn-info btn-sm" onclick="addTaskSelect()" value="新增">
                                        </div>
                                    </div>
                                </div>
                                <div id="task-auto" style="display: none">
                                    <label class="control-label form-inline" style="margin-left: 20px">用户数量：
                                        <input type="number" class="form-control" id="modal-user-num"></label>
                                    <label class="control-label form-inline" style="margin-left: 20px">分配总量(条)：
                                        <input type="number" class="form-control" id="modal-data-num"></label>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <input type="button" onclick="saveTask()" class="btn btn-primary" value="保存">
                <input type="button" onclick="cancelModel()" class="btn btn-default" value="取消">
            </div>
        </div>
    </div><!-- /.modal -->
</div>

{{include "com/footer.html"}}
<script>
    menuActive("task/list");

    let grouptaskid = {{ .T.grouptaskid }}
    let userList = []
    let stype = "man"

    $(function () {
        ttable = $('#dataTable').dataTable({
            "paging": true,
            "lengthChange": false,
            "searching": true,
            "ordering": false,
            "info": true,
            "autoWidth": false,
            "language": {
                "url": "/dist/js/dataTables.chinese.lang"
            },
            "fnDrawCallback": function () {
                $("ul.pagination").prepend("&nbsp;&nbsp;&nbsp;转到第 <input type='text' id='changePage'   style='width:20px;'> 页    <a type='text' href='javascript:void(0);' id='dataTable-btn' style='text-align:center'>GO</a>");
                $('#dataTable-btn').click(function (e) {
                    var redirectpage = 0
                    if ($("#changePage").val() && $("#changePage").val() > 0) {
                        var redirectpage = $("#changePage").val() - 1;
                    }
                    ttable.page(redirectpage).draw(false);
                });
                this.api().column(0).nodes().each(function (cell, i) {
                    cell.innerHTML = i + 1;
                });
            },
            "columns": [
                {"data": null, width: "1%"},
                {"data": "s_login", width: "5%"},
                {"data": "s_projectname", width: "4%"},
                {"data": "i_givenum", width: "4%"},
                {"data": "s_status", width: "4%"},
                {"data": "s_progress", width: "4%"},
                {"data": "i_starttime", width: "4%", render: function (val) {
                        if (val === undefined) {
                            return "未开始"
                        }else {
                            var dt = new Date()
                            dt.setTime(parseInt(val) * 1000);
                            return dt.format("yyyy-MM-dd")
                        }
                    }},
                {"data": "i_completetime", width: "4%", render: function (val) {
                        if (val === undefined) {
                            return "未完成"
                        }else {
                            var dt = new Date()
                            dt.setTime(parseInt(val) * 1000);
                            return dt.format("yyyy-MM-dd")
                        }
                    }},
                {
                    "data": "_id", width: "11%", render: function (val, a, row, pos) {
                        tmp = '<div>' +
                            '<a class="btn btn-sm btn-primary" onclick="retrieveTask(' + row + ')">收回</a>&nbsp;&nbsp;' +
                            '<a class="btn btn-sm btn-warning" href="/front/project/clear?pid=' + val + '">质检</a>&nbsp;&nbsp;' +
                            '<a class="btn btn-sm btn-info" onclick="">关闭</a>&nbsp;&nbsp;' +
                            '</div>';
                        return tmp
                    }
                }
            ]
        });

        $.ajax({
            url: "/front/user/task/list",
            type: "POST",
            data: {"grouptaskid": grouptaskid, "s_status": "-1", "s_login": "-1"},
            success: function (r) {
                if (r.data.length > 0) {
                    console.log(r.data)
                    ttable.fnClearTable();
                    ttable.fnAddData(r.data);
                }
            }
        })
        $.ajax({
            url: "/front/group/user/list",
            type: "POST",
            data: {},
            success: function (r) {
                if (r.rep) {
                    userList = r.data
                    console.log(userList)
                }
            }
        })
        $('input[type=radio][name=stype]').change(function () {
            if (this.value === 'man') {
                stype = "man"
                $("#task-man").attr("style", "display:block;")
                $("#task-auto").attr("style", "display:none;")
            } else if (this.value === 'auto') {
                stype = "auto"
                $("#task-man").attr("style", "display:none;")
                $("#task-auto").attr("style", "display:block;")
            }
        });
    });

    function cancelModel() {
        $('#TaskDiv .group-item.clone-template').remove()
        $("#modal-create-task").modal('hide')
        document.getElementById("modal-form-task").reset();
    }

    function dispatchTask(val) {
        $('#modal-create-task').modal('show')
        let text = document.getElementById("modal-user-num");
        text.setAttribute("max", userList.length.toString())
        text.onkeyup = function(){
            this.value=this.value.replace(/\D/g,'');
            if(text.value > userList.length){
                text.value = userList.length;
            }
        }
        for (var i in userList) {
            var opt = document.createElement('option');
            opt.innerText = userList[i]["s_login"];
            opt.value = userList[i]["_id"];
            $('#group-select')[0].appendChild(opt)
        }
        $("#group-select").selectpicker("refresh");
    }

    function addTaskSelect() {
        let tNode = $('#itemDiv').clone().addClass('group-item').addClass('clone-template').show()
        let st = $(tNode).find('select')
        $(st).addClass('selectpicker')
        for (var i in userList) {
            var opt = document.createElement('option');
            opt.innerText = userList[i]["s_login"];
            opt.value = userList[i]["_id"];
            $(st)[0].appendChild(opt)
        }
        $(st).selectpicker("refresh");
        $('#TaskDiv').append($(tNode))
    }

    function saveTask() {
        let arr = []
        if (stype === "man") {
            $('.group-item').each(function () {
                var selectId = $(this).find("select option:checked").val()
                var inputVal = $(this).find("input").val()
                console.log(selectId, inputVal)
                let tmp = {}
                for (let v in userList) {
                    if (userList[v]["_id"] === selectId) {
                        tmp["s_userid"] = selectId
                        tmp["s_login"] = userList[v]["s_login"]
                        tmp["s_name"] = userList[v]["s_name"]
                        tmp["i_givenum"] = inputVal
                        break
                    }
                }
                arr.push(tmp)
            })
        }else if (stype === "auto") {
            let userNum = parseInt($('#modal-user-num').val())
            let dataNum = parseInt($('#modal-data-num').val())
            console.log(userNum, dataNum, dataNum > userNum)
            if (userNum > 0 && dataNum > 0 && dataNum >= userNum) {
                if (dataNum%userNum === 0) {
                    // 整除
                    let avg = dataNum/userNum
                    for (let i = 0; i < userNum; i++) {
                        let tmp = {}
                        tmp["s_userid"] = userList[i]["_id"]
                        tmp["s_login"] = userList[i]["s_login"]
                        tmp["s_name"] = userList[i]["s_name"]
                        tmp["i_givenum"] = avg
                        arr.push(tmp)
                    }
                }else {
                    // 没有整除
                    let quo =  Math.floor(dataNum/userNum)      // 商数
                    let rem = dataNum%userNum                   // 余数
                    console.log("quo---", quo, "rem---", rem)
                    for (let i = 0; i < userNum; i++) {
                        let tmp = {}
                        tmp["s_userid"] = userList[i]["_id"]
                        tmp["s_login"] = userList[i]["s_login"]
                        tmp["s_name"] = userList[i]["s_name"]
                        if (i === (userNum-1)) {
                            tmp["i_givenum"] = quo + rem
                        }else {
                            tmp["i_givenum"] = quo
                        }
                        arr.push(tmp)
                    }
                }
            }else {
                showTip("请设置有效数字")
                return;
            }
        }
        console.log(arr)
        $.ajax({
            url: "/front/user/task/save",
            type: "POST",
            data: {"grouptaskid": grouptaskid, "usernums": JSON.stringify(arr)},
            success: function (r) {
                if (r.success) {
                    console.log(r.data)
                    location.reload()
                }else {
                    showTip(r.msg)
                }
            }
        })
    }

    // 收回
    function retrieveTask(row) {
        if (row.s_status === "未开始" || row.status === "进行中") {
            $.ajax({
                url: "/front/user/task/retrieve",
                type: 'POST',
                data: {"s_sourceinfo": row.s_sourceinfo, "taskid": row._id},
                success: function (r) {
                    if (r.success) {
                        ttable.api().ajax.reload()
                    } else {
                        showTip(r.msg);
                    }
                }
            })
        }else {
            showTip("操作不允许")
        }
    }
</script>
