function initCheck() {
    $('#ex1').slider();
    $("#ex1").on("slideStop", function(slideEvt) {
        setVideoProcess(slideEvt.value);
    });
    // setProcessValue(600);
    // $("#ex1").on("click", function(slideEvt) {
    //     setVideoProcess(slideEvt.value);
    // });

    // $("#ex1").on("slideStop", function(slideEvt) {
    //     setProcessValue(slideEvt.value);
    // });
    setProcessValue(300);
    // setCurrentProcessValue(50);

    // setCurrentProcessValue(60);

    event = document.createEvent('MessageEvent');
    var origin = window.location.protocol + '//' + window.location.host;
    event.initMessageEvent('setvideoposition', true, true, getVideoPosition(), origin, 1234, window, null);
    document.dispatchEvent(event);


    // 仅选择日期
    $("#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"
    });
    if ($.checkTask) {
        setFeSelect("#fsList", $.checkTask.checked_dept);
        setLaneSelect("#lane", $.checkTask.checked_location);
        get_common_service('user/getUserById/' + $.checkTask.checked_person, null, function (data) {
            changePersonContent(data);
        })
        //查询评分情况
        queryScores();
        //查询录像播放列表
        queryVideoList();
    }
     $("select#video_list").change(function(){
        playVideo($(this).val());
    });
}

function initInfo() {

}
// 使用data参数更新数据：
function queryScores() {
    //$('#score_datatable').score_datatable("");
    console.log("任务id："+$.checkTask.id);
    var data = {
        "task_id": $.checkTask.id
    }
    var cols = [
        { width: 80, text: '序号', type: 'number', flex: true, colClass: 'text-center', field: 'num' },
        { width: 160, text: '评分记录', type: 'string', flex: true, sort: 'down', field: 'content' },
        { width: 80, text: '分数', type: 'string', flex: true, colClass: '', field: 'check_item_score' },
        // {width: 80, text: '图片', type: 'imagedd', flex: true, colClass: '',field: 'pics'},
        {
            width: 160, text: '操作', type: 'string', flex: true, field: 'id',
            oper: [
                { func: 'showEditScore', text: '修改', icon_class: 'icon-edit' },
                { func: 'deleteScore', text: '删除', icon_class: 'icon-remove-circle' }
            ]
        }
    ];

    // var pager = {
    //     page_size:10
    // }
    $('#score_datatable').mytable({
        'cols': cols,
        'url': "/score/getScoreList/",
        'param': data
    }
    );
}
function showEditScore(id) {
    // deleteItem4Common(id,"/score/delete/",queryScores);
    var rowData = getItemByIdFromArr(id, $('#score_datatable').mytable('getTableData'));
    // scoreDetailLayer = showPopup4Common('修改考核项',null,['600px','500px'],'#score-detail-div');
    // var rowData=getItemByIdFromArr(id,$('#score_datatable').mytable('getTableData'));
    showPics(rowData.pics);
    // $("#scoreContent").val(rowData.content);
}

function deleteScore(id) {
    deleteItem4Common(id, "/score/delete/", queryScores, 'r');
}

function setVideoList(videos){
    var videoArr;
    if(videos){
        videoArr = videos.split("|");
        var selectStr="";
        for(var i in videoArr){
            if(i==0)
                selectStr += '<option value="'+videoArr[i]+'" selected="selected">视频'+videoArr[i]+'</option>'
            else
                selectStr += '<option value="'+videoArr[i]+'">视频'+videoArr[i]+'</option>';
        }
    }
    $('#video_list').html(selectStr);
}

function addPic(pic) {
    if (pic) {
        var i=0;
        var imgArr = $("#img_container .pic-class");
        if(imgArr && imgArr.length>0) i = imgArr.length;
        var picStr = '<div id="img_item_' + i + '" class="col-md-4 col-sm-6 col-lg-3">'
            + '<a href="javascript:void(0)" onclick="removeImg(\'#img_item_' + i + '\')" style="float:right;position:absolute;z-index:100;"><span class="label label-danger"><i class="icon icon-remove-circle"></i> 删除</span></a>'
            + '<a class="card lightbox-toggle" href="' + pic + '" style="position:absolute">'
            + '<img class="pic-class img-thumbnail" style="width:100px;height:70px;" src="' + pic + '" alt="">'
            + '</a>'
            + '</div>';
        $('#img_container').append(picStr);
    }
}

function showPics(pics, divId) {
    var picStr = '';
    if (!divId) divId = '#img_container';
    $(divId).html(picStr);
    if (pics) {
        var picArr = pics.split(',');
        for (var i in picArr) {
            var pic = '<div id="img_item_' + i + '" class="col-md-4 col-sm-6 col-lg-3">'
                + '<a href="javascript:void(0)" onclick="removeImg(\'#img_item_' + i + '\')" style="float:right;position:absolute;z-index:100;"><span class="label label-danger"><i class="icon icon-remove-circle"></i> 删除</span></a>'
                + '<a class="card lightbox-toggle" href="' + picArr[i] + '" style="position:absolute">'
                + '<img class="pic-class img-thumbnail" style="width:100px;height:70px;" src="' + picArr[i] + '" alt="">'
                + '</a>'
                + '</div>';
            picStr += pic;
        }
        $(divId).html(picStr);
        $('a.lightbox-toggle').lightbox();
    }
}

function removeImg(img_id) {
    $(img_id).remove();
}

function clearAllImg() {
    $('#img_container').empty();
}
var changePersonLayer;
function showChangeUser() {
    var param = {
        'organid': $.checkTask.checked_dept
    };
   
    post_common_service("/user/getUserList/", param, function (data) {
        changePersonLayer = showPopup4Common('更改人员', null, '800px',null,'r');
        $("#user_container").empty();
        var userStr = "";
        for (var i in data) {
            var name = data[i].truename;
            if (data[i].workno) name = name+" "+data[i].workno;
            var pic = "../../images/body-bg.png";
            if (data[i].pic) pic = data[i].pic;
            str = '<div style="width:100px;float:left;margin:5px;">'
                + '<a class="card" href="javascript:void(0)" onclick="changePerson(\'' + data[i].id + '\')">'
                + '<img src="' + pic + '" alt="" style="height:100px">'
                // +   '<a href="#" onclick="changePerson(\''+name+'\')">'+name+'<a href="'+data[i].pic+'class="lightbox-toggle" data-toggle="lightbox" data-group="image-group-1"><img src="../../images/img4.jpg" class="img-rounded" alt="" width="50px"></a></a>'
                + '<div class="card-heading"><strong>' + name + '</strong></div>'
                + '</a>'
                + '</div>';
            userStr += str;
        }
        $("#user_container").html(userStr);
    })
}

function changePerson(id) {
    // $('#checked_person').html(id);
    var param = {"id": $.checkTask.id,
                 "checked_person": id,
                }
    no_return_common_service("task/update/", param, function(data) {
        get_common_service('user/getUserById/' + id, null, function (data) {
        changePersonContent(data);
    })
    layer.close(changePersonLayer);
    }, function(error) {
        alert(error);
    });  
}

function changePersonContent(data) {
    var name = data.truename;
    if (data.workno) name = data.workno + " " + data.truename;
    $("#checked_person").html(name);
    $("#person_img").attr("href", data.pic);
    $("#person_img > img").attr("src", data.pic);
    $('a.lightbox-toggle').lightbox();
}
var scoreLayer;
function showScore() {
    scoreLayer = showPopup4Common('选择考核项', null, ['400px', '500px'], '#items-div','r');
    buildTree();
}
function buildTree() {
    var zTreeObj;
    var zNodes = [];
    check_item_tree = $.fn.zTree.init($("#items_tree"), {}, zNodes);

    getCheckItems();
}
function getCheckItems() {
    function zTreeOnRename(event, treeId, treeNode, isCancel) {
        alert(treeNode.tId + ", " + treeNode.name);
    }

    function zTreeOnRemove(event, treeId, treeNode) {
        alert(treeNode.tId + ", " + treeNode.name);
    }


    var setting = {
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: null
            }
        },
        view: { //表示tree的显示状态
            selectMulti: false //表示禁止多选
        },
        check: { //表示tree的节点在点击时的相关设置
            enable: false, //是否显示radio/checkbox
            chkStyle: "checkbox", //值为checkbox或者radio表示
            checkboxType: { p: "", s: "" }, //表示父子节点的联动效果
            radioType: "level" //设置tree的分组
        },
        callback: {
            onDblClick: zTreeOnClick
        },
        edit: {
            enable: true,
            drag: {
                autoExpandTrigger: true,
                isMove: true,
                prev: false,
                next: true,
                inner: true,
                autoOpenTime: 0
            },
            showRenameBtn: false,
            showRemoveBtn: false
        }
    };

    get_common_service('checkItem/getAll', null, function (data) {
        zdata = [];
        for (var i = 0; i < data.length; i++) {
            var m = data[i];
            //  var zdataItem = {};
            //  zdataItem["id"] = m.id;
            //  zdataItem["value"] = m.id;
            //  zdataItem["pId"] = null;
            //  zdataItem["score"] = m.score ;
            //  zdataItem["name"] = m.name;
            //  zdataItem["open"] = true;
            //  zdataItem["children"] = addobj(m);
            zdata.push(genNode(m));
        }
        menu_tree = $.fn.zTree.init($("#items_tree"), setting, zdata)
    }, function (error) {

    });
}
function addobj(data) {
    var zdata = [];
    if (typeof (data.subCheckItem) != "undefinde" && data.subCheckItem != null &&
        data.subCheckItem.length > 0) {
        for (var i = 0; i < data.subCheckItem.length; i++) {
            var m = data.subCheckItem[i];
            //  var zdataItem = {};
            //  zdataItem["id"] = m.id;
            //  zdataItem["value"] = m.id;
            //  zdataItem["pId"] = data.id;
            //  zdataItem["score"] = m.score ;
            //  zdataItem["icon"] = "";
            //  zdataItem["name"] = m.name;
            //  if(m.score)
            //     zdataItem["name"] = m.name+'('+m.score+')';
            //  zdataItem["open"] = true;
            //  zdataItem["children"] = addobj(m);
            zdata.push(genNode(m));
        }
        return zdata;
    } else {
        return [];
    }
}
function genNode(m) {
    var zdataItem = {};
    zdataItem["id"] = m.id;
    zdataItem["value"] = m.name;
    zdataItem["pId"] = m.parent_id;
    zdataItem["score"] = m.score;
    zdataItem["icon"] = "";
    zdataItem["name"] = m.name;
    //zdataItem["content"] = m.name;
    if (m.score) zdataItem["name"] = m.name + '(' + m.score + ')';
    zdataItem["open"] = true;
    zdataItem["children"] = addobj(m);
    return zdataItem;
}

function zTreeOnClick(event, treeId, treeNode) {
    //alert(treeNode.name);
    var imgArr = $("#img_container .pic-class");
    var picsStr = "";
    if (imgArr && imgArr.length > 0) {
        for (var i = 0; i < imgArr.length; i++) {
            picsStr += imgArr[i].src + ","
        }
        picsStr = picsStr.substr(0, picsStr.length - 1);
    }
    var param = {
        'task_id': $.checkTask.id,
        'pics': picsStr,
        'name': treeNode.value,
        'content': treeNode.value,
        'check_item_id': treeNode.id,
        'checkman': treeNode.id,
        'checked_person': $.checkTask.checked_person,
        'checked_dept': $.checkTask.checked_dept
    };
    no_return_common_service("/score/add", param, function (data) {
        if (scoreLayer) layer.close(scoreLayer);
        //查询评分情况
        queryScores();
        layer.msg(data, {
            time: 2000//20s后自动关闭
        });
    });
}

function submitCheck() {
    var param = {
        "id": $.checkTask.id,
        "check_status": 4
    }
    no_return_common_service("/task/taskEnd/", param, function (data) {
        layer.msg(data, {
            time: 2000//20s后自动关闭
        });
        changePage("/view/mytask/unchecked.html");
    });

}
function showPre(id) {
    // $('#myModal').modal({name:"dd"});
    changePage("/view/mytask/taskDetail.html");
}
function showInvalid() {
    invalidLayer = showPopup4Common('申请无效', function () {
        saveValidReason();
    }, ['400px', '500px'], '#invalid_div','r');

}
function saveValidReason() {
    var param = {
        "task_id": $.checkTask.id,
        "apply_reason": $("#apply_reason").val()
    }
    no_return_common_service("/checkApply/add/", param, function (data) {
        layer.msg("申请提交成功", {
            time: 2000//20s后自动关闭
        });
        changePage("/view/mytask/unchecked.html");
    });
}


function score(score) {
    alert("扣分：" + score);
    $('#scoreWin').modal('toggle');
}

function refuseApply() {
    alert("拒绝申请");
    $('#refuseApplyWin').modal('toggle');
}

function agreeApply() {
    alert("同意申请");
}


function getVideoPosition() {
    var X = $('#tabcontent').offset().top;
    var Y = $('#tabcontent').offset().left;
    var width = $('#tabcontent').width();
    var height = $('#tabcontent').height();
    return parseInt(Y) + "|" + parseInt(X) + "|" + parseInt(width) + "|" + parseInt(height);
}
function initUpLoad(){

    var uploader = WebUploader.create({

        // swf文件路径
        swf: 'lib/webuploader/js/Uploader.swf',

        // 文件接收服务端。
        server: base_image_server_url+'/filesSrver/'+FILE_UPLOAD,

        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: '#picker',

        // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
        resize: false
    });
}

