(function () {

    var h5SyncActions = parent.window.h5SyncActions;

    if (h5SyncActions && h5SyncActions.isSync) {

        var sdk = {

            /**
             * 获取配置信息
             */
            getClassConf: function () {
                return h5SyncActions.classConf;
            },

            getUserType: function () {
                return this.getClassConf().user.type;
            },

            /**
             * 构建发送数据
             */
            buildSvcMsgData: function (obj, type) {

                console.log('buildSvcMsgData-------------------------');
                console.log(obj);

                var classConf = this.getClassConf();
                var classStatus = classConf.h5Course.classStatus;
                var message = {};
                switch (type) {
                    case 'recordAudio':
                        var syncAction = {
                            otherInfor: obj.otherInfor
                        };
                        var receiveUser = '';
                        var sendUser = '';
                        if (obj.sendUser != obj.receiveUser) {
                            sendUser = obj.sendUser;
                            receiveUser = obj.receiveUser;
                        } else {
                            sendUser = classConf.user.id;
                            receiveUser = classConf.user.id;
                        }
                        message = {
                            syncAction: syncAction,
                            sendUser: sendUser,
                            receiveUser: receiveUser,
                            classStatus: classStatus,
                            type: 'recordAudio',
                            questionType: obj.questionType ? obj.questionType : '',
                            recoveryMode: obj.recoveryMode == undefined ? '' : obj.recoveryMode,
                            tplate: obj.tplate
                        };
                        break;
                    case 'sync':
                        var syncAction = {
                            index: obj.index,
                            syncName: obj.syncName,
                            funcType: obj.funcType,
                            otherInfor: obj.otherInfor == undefined ? '' : obj.otherInfor
                        };
                        var receiveUser = '';
                        var sendUser = '';
                        var sendUserInfo = '';
                        var starSend = '';

                        if (obj.method == 'drag') {
                            syncAction = {
                                index: obj.index,
                                syncName: obj.syncName,
                                left: obj.left,
                                top: obj.top,
                                pageX: obj.pageX,
                                pageY: obj.pageY,
                                otherInfor: obj.otherInfor == undefined ? '' : obj.otherInfor
                            };
                        }

                        if (obj.sendUser != obj.receiveUser) {
                            sendUser = obj.sendUser;
                            receiveUser = obj.receiveUser;
                            sendUserInfo = obj.sendUserInfo;
                            starSend = obj.starSend;
                        } else {
                            sendUser = classConf.user.id;
                            receiveUser = classConf.user.id;
                            sendUserInfo = classConf.user;
                            starSend = '0';
                        }

                        message = {
                            method: obj.method ? obj.method : '',
                            syncAction: syncAction,
                            user: classConf.user,
                            sendUser: sendUser,
                            receiveUser: receiveUser,
                            sendUserInfo: sendUserInfo,
                            classStatus: classStatus,
                            starSend: starSend,
                            type: 'sync',
                            questionType: obj.questionType ? obj.questionType : '',
                            recoveryMode: obj.recoveryMode == undefined ? '' : obj.recoveryMode,
                            tplate: obj.tplate
                        };
                        break;
                    case 'resultSync':

                        var receiveUser = obj.receiveUser;
                        var sendUser = obj.sendUser;
                        var sendUserInfo = obj.sendUserInfo;
                        var starSend = obj.starSend;

                        // if(obj.sendUser != obj.receiveUser) {
                        //     receiveUser = obj.receiveUser;
                        // } else {
                        //     receiveUser = classConf.user.id;
                        // }

                        message = {
                            syncAction: {
                                index: obj.index,
                                resultData: obj.resultData,
                                syncName: obj.syncName
                            },
                            user: classConf.user,
                            sendUser: sendUser,
                            receiveUser: receiveUser,
                            sendUserInfo: sendUserInfo,
                            classStatus: classStatus,
                            starSend: starSend,
                            type: 'resultSync',
                            questionType: obj.questionType ? obj.questionType : '',
                            tplate: obj.tplate,
                            operate: obj.operate
                        };
                        break;
                    default:
                        message = {};
                }
                return h5SyncActions.buildSvcMsgData(message, type);
            },

            //消息队列执行
            execMessages: {
                messages: [],
                intv: null,
                eventLock: false,
                exec: function (message) {
                    if (this.messages.length === 0 && !this.eventLock) {
                        //如果没有消息积压并且事件锁未锁定
                        this.eventLock = true;
                        this.triggerEvent(message);
                    } else {
                        this.messages.push(message);
                        if (!this.intv) {
                            this.intv = setInterval(function () {
                                var that = SDK.execMessages;
                                if (!that.eventLock) {
                                    if (that.messages.length > 0) {
                                        that.eventLock = true;
                                        var msg = that.messages.shift();
                                        that.triggerEvent(msg);
                                    } else {
                                        clearInterval(that.intv);
                                        that.intv = null;
                                    }
                                }
                            }, 1);
                        }
                    }
                },
                triggerEvent: function (message) {
                    var method = message.data[0].value.method;
                    var syncAction = message.data[0].value.syncAction;
                    var index = syncAction.index;
                    var syncName = syncAction.syncName;
                    if (syncAction.otherInfor) {
                        SDK.syncData = syncAction.otherInfor;
                    }
                    //事件触发目标元素target
                    var targetEle = $("[data-syncactions=" + index + "]");
                    if (method == 'event') {
                        targetEle.trigger(syncName, message);
                    }

                    if (method == 'drag') {
                        var pos = {
                            left: syncAction.left,
                            top: syncAction.top,
                            pageX: syncAction.pageX,
                            pageY: syncAction.pageY,
                            otherInfor: syncAction.otherInfor,
                            operate: message.operate
                        };
                        targetEle.trigger(syncName, pos);
                    }
                }
            },

            setEventLock: function () {
                this.execMessages.eventLock = false;
                h5SyncActions.setEventUnlocked();
            },

            actEvent: function (message) {
                var syncAction = message.data[0].value.syncAction;

                //现在这个状态做断线恢复用
                if (message.operate == '5') {
                    if (syncAction.otherInfor) {
                        this.syncData = syncAction.otherInfor;
                    }
                    if (this.recover) {
                        this.execMessages.eventLock = true;
                        this.recover(this.syncData);
                        return false;
                    } else {
                        console.warn("断线重连方法缺失，请实现断线重连方法");
                    }
                }

                //队列执行同步的消息
                this.execMessages.exec(message);
                return false;
            },

            bindSyncRecord: function (obj) {
                var message = this.buildSvcMsgData(obj, 'recordAudio');

                var classStatus = message.data[0].value.classStatus;
                if (classStatus == '1' || classStatus == '2') {
                    h5SyncActions.addSendMessage(message);
                    // h5SyncActions.addEventQueue(message); // trigger event click ---> bindSyncResultEvt
                } else {
                    h5SyncActions.addEventQueue(message);
                }

            },

            //新添加结果时间触发
            actResultEvent: function (message) {
                // console.log('sdk-----actResultEvent------------>%s', JSON.stringify(message));
                var syncAction = message.data[0].value.syncAction;
                var index = syncAction.index;
                var syncName = syncAction.syncName;
                var syncResultData = syncAction.resultData;

                //事件触发目标元素target
                var targetEle = $("[data-syncresult=" + index + "]");
                //syncResultClick
                targetEle.trigger(syncName, message);
            },

            //各端同步数据存储
            syncData: {},

            //恢复页面状态的方法
            recover: null,

            bindSyncEvt: function (obj) {
                if (!obj.otherInfor && this.syncData && Object.keys(this.syncData).length > 0) {
                    obj.recoveryMode = 1;
                    obj.otherInfor = this.syncData;
                }

                var message = this.buildSvcMsgData(obj, 'sync');

                var classStatus = message.data[0].value.classStatus;
                console.log('classStatus66666--------', classStatus)
                if (classStatus == '1' || classStatus == '2' || classStatus == '11' || classStatus == '12' || classStatus == '13' || classStatus == '14') {
                    h5SyncActions.addSendMessage(message);
                    h5SyncActions.addEventQueue(message); // trigger event click ---> bindSyncResultEvt

                } else {
                    h5SyncActions.addEventQueue(message);
                }
            },

            //新添加结果同步数据封装
            bindSyncResultEvt: function (obj) {

                // console.log('sdk bindSyncResultEvt------------->%s', JSON.stringify(obj));
                //debugger;
                var message = this.buildSvcMsgData(obj, 'resultSync');

                var classStatus = message.data[0].value.classStatus;
                if (classStatus == '2') {
                    // h5SyncActions.addSendMessage(message);
                    h5SyncActions.addEventQueue(message);

                }
            },
            //新添加发星星
            bindSyncStart: function(obj) {
              var message = obj;
              h5SyncActions.addSendStart(message);
            },

            //传递控制器本地事件  如取消start模式  取消demo模式等
            bindSyncCtrl: function(obj) {
                var type = obj.type;
                if (type) {
                    h5SyncActions.addEventQueue(obj);
                }
            },
            // 调用控制器播放功能
            playRudio: function (data) {
                var dom = data.index;
                var syncName = data.syncName;
                var newData = {
                    URL: dom.src,
                    otherInfor: {
                        index: dom,
                        syncName: syncName
                    }
                }
                // console.dir(data.index instanceof HTMLElement)
                // console.dir(data.index instanceof jQuery)
                if (dom.hasAttribute('loop')) { //循环播放的音频 dom结构里有
                    newData.loop = true
                } else {
                    newData.loop = false;
                }
                if (h5SyncActions.playRudio) {
                    console.log("模板准备调用playRudio，参数是", newData);
                    h5SyncActions.playRudio(newData);
                } else {
                    console.log("控制器无音频播放方法，本地播放");
                    data.index.play();
                }
            },

            // 调用控制器暂停功能
            pauseRudio: function (data) {
                var newData = {};
                var dom = data.index;
                var syncName = data.syncName;
                if (data && data.index) {
                    newData = {
                        URL: dom.src,
                        otherInfor: {
                            index: dom,
                            syncName: syncName
                        }
                    }
                }
                if (h5SyncActions.pauseRudio) {
                    console.log("模板准备调用pauseRudio，参数是", newData);
                    h5SyncActions.pauseRudio(newData);
                } else {
                    console.log("控制器无音频停止方法，本地停止播放");
                    data.index.pause();
                }
            },

            //接收结束播放(通过设置currentTime去触发 onended 无效）
            audioEnd: function (message) {
                console.log('结束');
                var syncName = message.otherInfor.syncName;
                $('audio[data-syncaudio=' + syncName + ']').trigger("ended");
            }

        };
        window.SDK = sdk;
    } else {
        window.SDK = {
            getUserType: function () {
                return "tea";
            },
            //页面当前状态数据
            syncData: {},
            setEventLock: function () { },
            log: function () {
                console.log('---------sdk log------------');
            },
            // 本地播放功能
            playRudio: function (data) {
                data.index.play();
            },
            // 本地暂停功能
            pauseRudio: function (data) {
                data.index.pause();
            }
        };
    }
})();


function funcGenerater(num) {
    var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
    var str = num + '';
    var func = '';
    for (var i = 0; i < str.length; i++) {
        func += arr[str[i] - 0];
    }
    return func;
}

;
(function ($) {
    var funcNum = 0;
    $.fn.syncbind = function (evt, pre, func) {
        var defaults = {
            //各种默认参数
        }
        // var options = $.extend(defaults, options); //传入的参数覆盖默认参数
        this.each(function () {
            funcNum++;
            var tempFunc = "temp_syncfunc_" + funcGenerater(funcNum);
            var _this = $(this); //缓存一下插件传进来的节点对象。
            var index = _this.data('syncactions'); //同步事件对象需要data-syncactions预置属性
            if (!index) {
                index = tempFunc + "_dom";
                _this.attr("data-syncactions", index);
            }
            //当flag为false时则不同步事件
            //当flag为不填或者true时，事件同步
            var syncNext = function (flag) {
                if (flag === undefined || flag) {
                    SDK.bindSyncEvt({
                        index: index,
                        eventType: evt,
                        method: 'event',
                        syncName: tempFunc
                    });
                } else {
                    _this.trigger(tempFunc);
                }
            };
            //执行内容
            _this.on(evt, function (e) {
                if (e.type == "touchstart") {
                    e.preventDefault()
                }
                pre(_this, syncNext);
            })
            _this.on(tempFunc, func);
        })
        return $(this); //把节点对象返回去，为了支持链式调用。
    }
})(jQuery);
