window.onload = function() {
    (function($export, messageBox) {

        'use strict';

        // Vue.config.debug = true
        // Fnatic.request.debugModel.all = true;
        // Fnatic.request.debugModel.event = true;

        Vue.filter('date', function(value) {
            return Fnatic.utils.dataformat(value, $o.const.FORMATTER);
        })

        Vue.filter('filesize', function(value) {
            return Fnatic.NumberSuffix(value);
        })

        var $o = {
            prevMessage: undefined,
            postion: 0,
            uuid: Fnatic.utils.guid().create().ToString()
        };

        //记录数据为第一次加载，后续的数据都是通过pullload加载
        $o.isFirst = true;

        $o.MessageType = [
            'DEVMSG_TYPE_UNKNOW', // 0
            'DEVMSG_TYPE_TEXT', // 1
            'DEVMSG_TYPE_PIC', // 2
            'DEVMSG_TYPE_ECLOUD_FILE', // 3
            'DEVMSG_TYPE_LOCAL_FILE' // 4
        ]

        $o.MessageFrom = [
            'DEVMSG_FROM_UNKNOW', // 0
            'DEVMSG_FROM_PC', // 1
            'DEVMSG_FROM_MOBILE' // 2
        ]

        $o.FielStatus = [
            'FILESTATUS_READY', // 0
            'FILESTATUS_TRANSFER', // 1 传输中，根据FROM来判断是上传还是下载
            'FILESTATUS_FINISHED' // 2 已完成，根据FROM来判断是上传完成还是下载完成
        ]

        $o.ActionType = {
            DOWNLOAD: 0,
            UPLOAD: 1,
            OPEN: 2,
            PREVIEW: 3
        }

        $o.const = {

            UPLOAD_FAILURE: '发送失败，点击重试',
            DOWNLOAD_FAILURE: '下载失败，点击重试',

            COUNT: 20,
            QRCODE: '//jdy.tmall.com',
            FORMATTER: 'yyyy-MM-dd hh:mm:ss',

            BENCH_MYDEVICE_ADD_MESSAGE: 'bench.mydevice.add.message',
            BENCH_MYDEVICE_SYNC_STATUE: 'bench.mydevice.sync.process',
            BENCH_MYDEVICE_MASK_CHANGED: 'bench.mydevice.mask.changed',
            BENCH_MYDEVICE_FILES_ACTION: 'click_msgitem',
            // BENCH_MYDEVICE_MESSAGE_LIST: 'getMyDeviceMessageList',
            BENCH_MYDEVICE_CHOOSE_ELCOUD_FILE: 'choose_ecloudfile',
            BENCH_MYDEVICE_DOWNLOAD: 'download_msgfile',

            BENCH_MYDEVICE_OPENIMAGE: 'open_image',

            BENCH_MYDEVICE_PULLLOAD: 'load_morehismsg',

            BENCH_MYDEVICE_RETRY: 'resend_message', //失败之后的重试

            OPEN_ECLOUD: 'chooseCloudFile'
        }

        $export.config = {
            frompc: 1,
            time: 3e2
        }

        // $o.widget = new qnPromotionQRCode.Widget({
            // uri: $o.const.QRCODE,
            // renderTo: document.getElementsByClassName('qrcode-container')[0]
        // });

        // $o.widget.init();

        $o.filter = function(data) {
            return {
                seqid: data.seqid,
                content: data.content,
                from: data.from,
                datetime: data.datetime,
                type: data.type,
                status: data.status
            };
        }

        $export.messages = new Vue({
            el: '.app',
            data: {
                list: [],
                ready: true,
                mask_status: 0
            },
            methods: {
                //定位文件地址
                preview: function(evt) {
                    var vm = evt.targetVM;
                    console.log(vm)
                    evt.stopPropagation();
                    evt.preventDefault();
                    Fnatic.request.app('previewCloudFile', {
                        uuid: $o.uuid,
                        file_id: vm.$data.content.file_id,
                        space_id: vm.$data.content.space_id
                    })
                },
                previewpic: function(evt) {
                    var vm = evt.targetVM;
                    evt.stopPropagation();
                    evt.preventDefault();
                    workbench.mydevice[$o.const.BENCH_MYDEVICE_OPENIMAGE](JSON.stringify($o.filter(vm.$data)));
                },
                download: function(evt) {
                    var vm = evt.targetVM;
                    console.log('download');
                    workbench.mydevice[$o.const.BENCH_MYDEVICE_DOWNLOAD](JSON.stringify($o.filter(vm.$data)));
                },
                retry: function(evt) {
                    var vm = evt.targetVM;
                    if (vm.$data.status !== 1 && !vm.$data.showError) {
                        return;
                    }
                    console.log('retry', vm.$data.status, vm.$data.process);
                    vm.$data.status = 0;
                    workbench.mydevice[$o.const.BENCH_MYDEVICE_RETRY](JSON.stringify($o.filter(vm.$data)));
                }
            }
        })

        $o.queue = new Fnatic.Queue();

        $o.default = {
            process: 0,
            showOperator: true,
            showError: false
        }

        //绑定pullload
        // Fnatic.ui.pullload.init(messages.$el, function() {
        //     var defer = $.Deferred();
        //     var lastId = messages.list[0].seqid;
        //     workbench.mydevice[$o.const.BENCH_MYDEVICE_PULLLOAD](lastId);
        //     defer.resolve();
        //     return defer.promise();
        // });

        $o.loader = Fnatic.ui.dynload({
            el: messages.$el,
            callback: function() {
                if (messages.list && messages.list[0]) {
                    var lastId = messages.list[0].seqid;
                    workbench.mydevice[$o.const.BENCH_MYDEVICE_PULLLOAD](lastId);
                }
            }
        })

        $o.scroll = function() {
            var task = new Fnatic.Task({
                handler: Fnatic.ui.autoscroll,
                param: [messages.$el]
            });

            $o.queue.clear();
            $o.queue.add(task);
        }

        //预留给客户端更新缩略图的方法
        $export.syncPicture = function(res) {
            console.log('[syncPicture]', res);
            var data = JSON.parse(res);
            data.forEach(function(item) {
                var messageTmp = _.findWhere(messages.list, {
                    seqid: item.seqid
                });
                if (!messageTmp) {
                    return;
                }
                messageTmp.content.proto_url = item.proto_url + '?' + new Date().getTime();
            })
        }

        //预留给客户端打开云盘的方法
        $export.openEcloudComponent = function() {
            Fnatic.request.app($o.const.OPEN_ECLOUD, {
                uuid: $o.uuid
            }).then(function(res) {
                console.log(res);
                workbench.mydevice[$o.const.BENCH_MYDEVICE_CHOOSE_ELCOUD_FILE](JSON.stringify(res));
            })
        }

        //预留给客户端清空聊天窗的方法
        $export.clearAllMessage = function() {
            messages.list = [];
            $o.loader.reset();
            console.log('清除客户端聊天信息');
        }

        $export.showTipPrompt = function(opts) {
            opts = JSON.parse(opts);
            $o.loader.msg = opts.msg;
            $o.loader.remind(opts.msg);
            setTimeout(function(){
                $o.loader.end();
            }, 800);
        }

        //监听消息推送
        $export.appendMessage = function(data) {
            // console.log(data)
            if (typeof data === 'string') {
                data = JSON.parse(data);
            }
            console.log('[消息推送]', data);
            //是否是历史记录
            var ishismsg = false;
            $o.pos += data.length;
            data.forEach(function(item) {
                    if (!item.content) {
                        return;
                    }
                    _.extend(item, $o.default);
                    Fnatic.record.info(item);
                    if (!$o.prevMessage || item.datetime - $o.prevMessage >= $export.config.time) {
                        item.showtime = true;
                        $o.prevMessage = item.datetime;
                    }
                    if (item.content.extension) {
                        item.content.ext = item.content.extension.replace('.', '');
                    }
                    item.fileType = $o.MessageType[item.type];
                    item.fileFrom = $o.MessageFrom[item.from];
                    item.pc = item.from === $export.config.frompc;
                    // item.msgTitle = item.pc ? $o.const.UPLOAD_FAILURE : $o.const.DOWNLOAD_FAILURE;
                    item.msgTitle = item.errmsg ? item.errmsg : item.pc ? $o.const.UPLOAD_FAILURE : $o.const.DOWNLOAD_FAILURE;
                    if (item.hismsg === 1) {
                        ishismsg = true;
                        // console.log('[历史消息]', item);
                    }
                })
                //判断历史消息，第一次加载需要滚动到底部，加载完毕后isFirst标志设置为false
            if (ishismsg) {
                messages.list.unshift.apply(messages.list, data);
                setTimeout(function() {
                    $o.isFirst = false
                });
            } else {
                messages.list = messages.list.concat(data);
            }

            if (!ishismsg || $o.isFirst) {
                $o.scroll();
            } else {
                setTimeout(function() {
                    $o.loader.run();
                }, 800);
            }

            // root.Fnatic.ui.autoscroll(messages.$el);
        }

        //监听文件进度推送
        $export.syncProcess = function(res) {
            var data = JSON.parse(res);
            data.forEach(function(item) {
                var messageTmp = _.findWhere(messages.list, {
                    seqid: item.seqid
                });
                // item.process = -1;
                if (!messageTmp) {
                    return;
                }
                // console.log('[发我下看看]', item)
                //如果有带下来的出错信息则直接用
                messageTmp.msgTitle = item.data && item.data.msg ? item.data.msg : messageTmp.msgTitle;
                messageTmp.showError = item.process === -1 ? true : false;
                //云盘
                if (messageTmp.fileType === 'DEVMSG_TYPE_ECLOUD_FILE' && messageTmp.fileFrom === 'DEVMSG_FROM_PC') {
                    messageTmp.showOperator = true;
                } else {
                    messageTmp.showOperator = item.process === 100 ? true : false;
                    if (!messageTmp.showError) {
                        messageTmp.process = item.process;
                    } else {
                        // $o.scroll();
                    }
                    if (messageTmp.showOperator && item.data.content) {
                        console.log('[文件信息更新]', item.data.content);
                        _.extend(messageTmp.content, item.data.content);
                    }
                }
                if (item.msg) {
                    console.log('[失败原因] ', item.msg);
                }
                console.log('[syncProcess] -> seqid: [', item.seqid, '] process: [', item.process, '][', item, ']');
                // console.log(messages.list[messages.list.length -1].process)
            })
        }

        //监听mask信息
        $export.setMask = function(res) {
            console.log('mask', res);
            res = JSON.parse(res);
            messages.mask_status = res.mask;
            messages.mask_addr = res.addr;
        };

    })(this, function() {

        var MessageBox = function() {
            this.uuid = Fnatic.utils.Guid.create();
            this.process = 0;
            this.status = 0;
        }

        _.extend(MessageBox.prototype, {
            update: function(proc) {
                this.process = proc;
            }
        })

        return new MessageBox;
    })
};