getUserId();

const DEFAULT = 2;
const ONDEMAND = 4;
const AUTO = 8;
const FAST = 16;
const PASSIVE = 32;

var RANK_TBL_ROW_COUNT = 4;

var lastTimeRank0 = "";
var lastTimeRank1 = "";
var lastTimeRank2 = "";
var lastTimeRank3 = "";
var lastTimeRank4 = "";


/***
 * DataObject DO
 * @param cname
 * @param serverJsonObj
 * @constructor
 */
var DataObject = function(cname, serverJsonObj){
    this.ctlName = cname;
    this.jsonObj = serverJsonObj;
    this.getVal = function (key) {
        return jsonObj[key];
    };
    this.serVal = function (key, val) {
        jsonObj[key] = val;
    };

};

/***
 * DataObjectList
 * @param name
 * @constructor
 */
var DataObjectList = function(name){
    this.ctlName = name;
    this.list = null;
    this.isSorted = false;
    this.preSort = [];
    /***
     * sorting
     * @param comparator (a,b)  =====>  a - b
     */
    this.sortBy = function(comparator){
        this.preSort = new Array();
        for (let i = 0; i < this.list.length; i++) this.preSort.push(list[i]);
        quickSort(this.preSort, 0, this.preSort.length - 1, function(l, r){});
    };

    this.clearData = function () {
        this.isSorted = false;
        this.preSort = null;
        this.list = null;
    }

    this.len = function() {
        if(this.list == null) return 0;
        return this.list.length;
    };

    this.mergeJsonData = function (data, extdata) {
        this.list = new Array();
        for (let i = 0; i < data.length; i++) this.addObject(data[i]);
    };

    this.addObject = function (jsonObj) {
        this.list.push(new DataObject(this.ctlName, jsonObj));
    };

    this.assignJsonData = function (data) {
        this.clearData();
        this.mergeJsonData(data);
    };
    this.getRaw = function (index) {
        if(this.list == null) return null;
        return this.list[index];
    };
    this.getSorted = function (index) {
        if(this.list == null) return null;
        if(!this.isSorted) return this.getRaw(index);
        return this.preSort[index];
    };
    this.quickSort = function (a,left,right,comp){
        if(left>right){ //一定要有这个判断，因为有递归left和i-1，若没有这个判断条件，该函数会进入无限死错位递归
            return;
        }

        var i=left,
            j=right,
            pivot=a[left]; //基准总是取序列开头的元素

        while(i!=j){
            while((comp(a[j],pivot) > 0)&&i<j){j--}
            while((comp(a[j],pivot) <= 0)&&i<j){i++}
            if(i<j){  //如果i==j跳出外层while
                var t=a[i];
                a[i]=a[j];
                a[j]=t;
            }
        }

        a[left]=a[i];//交换基准数和k位置上的数
        a[i]=pivot;

        quicksort(a,left,i-1,comp);
        quicksort(a,i+1,right,comp);
    };
};

/***
 * DOService
 * @param controlName
 * @constructor
 */
var DataObjectService = function(controlName, syncType, extparm){
    this.ctlName    = controlName;
    // 2=default 4=on-demand, 8=auto, 16:fast, 32=passive
    this.syncType   = syncType;
    this.extParm    = extparm;
    this.isDefault  =  ((syncType & DEFAULT)  !== 0);
    this.isOnDemand = ((syncType & ONDEMAND)  !== 0);
    this.isAuto =     ((syncType & AUTO)  !== 0);
    this.isFast =     ((syncType & FAST) !== 0);
    this.isPassive  = ((syncType & PASSIVE) !== 0);
    this.failedCount= 0;
    this.list       = new DataObjectList(controlName);
    this.autoUpdateTimer = 0;
    this.autoInterval = 1000;
    this.callerThis = this;

    this.setUpInterval = function() {
        //URL + exparm
        if(this.autoUpdateTimer != 0) clearInterval(this.autoUpdateTimer);
        this.autoUpdateTimer = setInterval(this.selfUpdateTick, this.autoInterval, this);
        setTimeout(this.selfUpdateTick, 1000, this);
    }

    this.init = function(){
        this.appUrl = controlName + "/list" + extparm;
        if(!this.isFast || this.isOnDemand){
            this.autoInterval = 300;
        }

        if(this.isFast) {
            this.appUrl = controlName + "/get" + extparm;
        }

        if(this.isAuto){
            // timer
            this.setUpInterval();
        }
    };

    this.stopTimers = function () {
        clearInterval(this.autoUpdateTimer);
        this.autoUpdateTimer = 0;
    };

    /***
     * Automatica Update Tick, where obj is a replacement for "this" where "this" might be incorrect
     * @param obj : DataObjectService
     */
    this.selfUpdateTick = function(obj){
        get_data(obj.appUrl, obj.onDataReceived, obj);
    };

    this.onDemandUpdate = function(obj){
        get_data(obj.appUrl, obj.onDataReceived, obj);
    };

    this.onDataReceived = function(data, sta){
        let obj = this.callerThis;
        if(obj == undefined){console.error("Cannot get callerThis in onDataReceived, please check"); console.error(this)}
        let output = first_parse(this, data);
        if (output.list == undefined || output.list.length == 0) {
            obj.failedCount++;
            if(obj.failedCount > 100){
                obj.failedCount = 0;
                obj.stopTimers();
                console.log("[排行榜返回为空git clone https://github.com/pentaho/mondrian-tck.git次数过多]，暂停刷新");
            }
            if(obj.failedCount == 2) {
                send_alert("排行榜多次返回没有数据，请尝试重新加载！ [" + obj.appUrl +"]");
            }
        }else{
            obj.list.assignJsonData(output.list);
        }
    };

    this.getList = function () {
        return this.list;
    };

    this.passiveUpdate = function(data){
        this.failedCount = 0;
        this.list.assignJsonData(data);
    };

    this.init();
};

var SinglePage = function () {
    this.modules = [];
};

var Module = function(chartContainerSelector, dataCtlName){
    this.selector = chartContainerSelector;
    this.dataCtl = dataCtlName;
    this.activeData = null;
    this.lastActive = 0;
    this.tickInterval = 1000;
    /***
     * bindData to UI
     * @param data DataObjectList
     */
    this.setData = function (data) {
        if(data.ctlName == this.dataCtl){
            console.log(`-------- Module ${this.selector} got data ----------- `);
            this.activeData = data;
            this.drawData(this.activeData);
        }else{
            console.log(`-------- Module ${this.selector} cannot use data of ${data.ctlName} ----------- `);
        }
    };
    this.init = function () {
        // do init
        this.setupInterval();
    };
    this.tick = function () {
        // do tick
    };
    this.setupInterval = function () {
        // do tick
        if(this.tickInterval != 0) clearInterval(this.tickInterval);
        this.tickInterval = setInterval(this.tick, this.tickInterval);
    };
    this.drawData = function () {
        // do drawData
    };
};

var RedRankTable = new Module("#table-rank", "fcBiWorkerDaily");

RedRankTable.slideLen = 16;
RedRankTable.slides   = 0;
RedRankTable.parts    = 4;
RedRankTable.partLen  = 4;
RedRankTable.curSlide = 0;

RedRankTable.drawData = function (data) {
    // showSlide
    this.showSlide(this.curSlide, data);
};

RedRankTable.showSlide = function (slide, data) {
    for(var part = 0; part < this.parts; part++){
        this.showPart(slide, part, data);
    }
};

RedRankTable.showPart = function(slide, part, data){
    var lpos = slide * this.slideLen + (part * this.partLen);
    var rpos = slide * this.slideLen + ((part+1) * this.partLen);
    var partList = [];
    for (var i = lpos; i < rpos; i++) {
        var one = data.getSorted(i);
        if(one == null || one == undefined) {
            partList[partList.length] = {passNum : 0, failNum: 0, failRate: 0, workerId: 0, fcDay: new Date().toLocaleDateString()};
        } else {
            partList[partList.length] = one.jsonObj;
        }
        partList[partList.length - 1].color = true;
    }
    redrankvue.part[part] = partList;
};

RedRankTable.tickInterval = 1000;
RedRankTable.tick = function(){
    var totalDataLen = this.activeData != null ? this.activeData.len() : 0;
    if(this.slides != Math.ceil(totalDataLen / this.slideLen)){
        this.slides = Math.ceil(totalDataLen / this.slideLen);
        this.curSlide = 0;
    } else {
        this.curSlide = (this.curSlide + 1) % this.slides;
    }
};

RedRankTable.init();

var FlowRealTime = new (function () {

    this.pgName = "flowDashBoard";
    this.page = new SinglePage(this.pgName);
    this.scheduleId = utils_get_param("scheduleId");
    this.flowId = utils_get_param("flowId");
    if(scheduleId  == null || flowId == null)
    {
        send_alert(`清重新进入本页面！<a href='denglu.html'> 返回主页 </a>`);
        return;
    }
    this.flowPlace = " % flowPlace %";
    this.flowName = " % flowPlace %";

    this.scheduleLoadDataService = new DataObjectService("fcWorkScheduleLoad", ONDEMAND /*AUTO & FAST*/, "?scheduleId=" + scheduleId);
    this.oaStaffService = new DataObjectService("fcWorkScheduleLoad", ONDEMAND, "");
    this.sectorService = new DataObjectService("fcWorkScheduleLoad", ONDEMAND, "");
    this.flowService = new DataObjectService("fcFlow", ONDEMAND, "");
    this.workerDailyService = new DataObjectService("fcBiWorkerDaily", ONDEMAND | AUTO | FAST, "?type=1");

    this.MeduimData = new (function () {
        this.initializeUsers = function(list){
            list.forEach(function (val, it, arr) {
                var isExist = false;
                userIDs.forEach(function (vals) {
                    if (vals == val.userId) {
                        isExist = true;
                    }
                });
                if (!isExist) userIDs.push(val.userId);
            });
        };
    })();

    this.initPage = function() {
        setInterval(this.tick, 1000);
    };

    this.tick = function(){
        RedRankTable.setData(FlowRealTime.workerDailyService.getList());
    };

    this.Action = new (function (parent) {
        this.parent = parent;
        this.doStopSchedule = function () {
            get_data("fcWorkSchedule/stopSchedule?userId=" + userId + "&scheduleId=" + scheduleId, this.parent.UI.showStopSuccess, this.parent);
        };
        this.confirmStopSchedule = function () {
            var out = confirm("真的要下班吗？");
            if (out == true) {
                this.doStopSchedule();
            } else {
            }
        };
    })(this);

    this.UI = new (function (parent) {
        this.p = parent;
        this.showClearPanel = function () {
            $("#clearModal").modal('show');
        };
        this.showStopSuccess = function (obj, sta, scope) {
            send_alert("下班操作成功！ <a href='denglu.html'> 点击这里返回控制主页 </a>");
        };
        this.bind = function () {
            $(".confirm-clear-data").click(function(){
                FlowRealTime.ClearDataControl.clearDataOfDeviceId($('#handInput').val());
            });
            $(".open-clear-panel").click(function () {
                FlowRealTime.UI.showClearPanel();
            })
            $(".close-schedule").click(function () {
                FlowRealTime.Action.confirmStopSchedule();
            })
        }
    })(this);

    var ClearDataControl = new (function (parent) {
        this.p = parent;
        this.finished = true;
        this.executed = false;
        this.directCount = -1;

        this.clearDataOfDeviceId = function (handId) {
            this.executed = false;
            this.directCount = -1;
            this.finished = true;
            var hand = handId;
            var hd = 0;
            if (hand.length > 0) {
                hd = parseInt(hand);
            }
            get_data("endpoint/clearBoard?flowId=" + flowId + "&handheldId=" + hd, this.clearSuccess);
        };

        this.clearSuccess = function (obj, sta) {
            console.warn("-------  手持设备清空  ----------");
            console.warn(obj);
            send_alert("发送清空请求成功, 正在等待采集端进行处理...");
            this.finished = false;
            setTimeout(this.resultVerifyTimeout, 8000, this);
            setTimeout(this.getVerify, 300, this);
        }

        this.getVerify = function (obj) {
            if (obj.finished) return;
            get_data("endpoint/heartbeat?flowId=" + flowId, obj.onVerifyResult);
            setTimeout(obj.getVerify, 100, obj);
        };

        this.onVerifyResult = function (obj, sta) {
            var parsed = {};
            if (typeof(obj) === "string") {
                parsed = JSON.parse(obj);
            } else {
                parsed = obj;
            }

            if (typeof(parsed) === "object") {
                if (parsed.ret === "10000") {
                    //ok
                    if (parsed.model == null || parsed.model === undefined) {
                        executed = true;
                        finished = true;
                    } else if (typeof(obj.model) === "object") {
                        // 没有拿到，继续
                        if (obj.model.list != null && obj.model.list.length > 0) {
                            var direct = obj.model.list[0];
                            if (direct.eventType + "" !== "500") {
                                // OK
                                executed = true;
                                finished = true;
                            } else if (direct.arg2 + "" !== "" + $("#handInput").val()) {
                                // OK
                                executed = true;
                                finished = true;
                            } else {
                                directCount = direct.counter;
                            }
                        }
                    }
                }
            }
        }

        this.resultVerifyTimeout = function (obj) {
            finished = true;
            if (executed) {
                // 执行成功
            } else {
                if (directCount >= 0) {
                    get_data("endpoint/ack?counter=" + directCount, function () {
                        console.log("撤销操作成功");
                        console.log(this);
                    });
                    directCount = -1;
                    send_alert("请求已经超时！请注意，采集端可能没有执行成功。即将撤销您的请求。");
                } else {
                    send_alert("请求已经超时！请注意，采集端可能没有执行成功。");
                }
            }
        }
    })(this);

})();

var redrankvue = new Vue({
    el: '#redrank',
    data: {
        part:[
            { message: 'Foo', color:true },],
        title: '本厂今日生产能手榜'
    },
    methods: {
        clicktitle: function () {
            alert("Hello! This is Title");
        }
    }
});

$(document).ready(function(){
    FlowRealTime.initPage();
    FlowRealTime.UI.bind();
});
