/**
 * Created with JetBrains WebStorm.
 * User: dfwang
 * Date: 14-7-18
 * Time: 下午1:48
 * To change this template use File | Settings | File Templates.
 */
define(function (require, exports) {
    var IOUtil;
    if (RunningPlatform === "NodeWebkit") {
        IOUtil = require("../../../../share/assert/js/ioutil_desktop.js").IOUtil;
    }
    else if (RunningPlatform === "Android") {
        IOUtil = require("../../../../share/assert/js/ioutil_android.js").IOUtil;
    }
    else if (RunningPlatform === "CEF") {
        IOUtil = require("../../../../share/assert/js/ioutil_cef.js").IOUtil;
    }
    else{
        IOUtil = require("../../../../share/assert/js/ioutil_web.js").IOUtil;
    }

    var AppContext = require("../../../../share/assert/js/appcontext").AppContext;

    fabric.Spot.prototype.getRenderDOM = function (relatedResPath) {
        var def = $.Deferred();
        var _json = null;
        var _random = Math.floor(Math.random()*1000)
        var _evtId = 'hots_play'+this.id+"_"+_random;
        var _ctrId = 'hots_ctrl'+this.id+"_"+_random;
        relatedResPath = relatedResPath.replace('/meta.json','');
        var _folder =  relatedResPath//.substr(0,relatedResPath.lastIndexOf('/'));
        var _that = this;
        var _medias = [];
        var _mainCanvas = this.canvas.upperCanvasEl.parentNode.parentNode;
        IOUtil.readFile(AppContext.joinPath(relatedResPath,'meta.json')).done(function(data,err){
            if(data){
                data = data.replace(/\n/g, '\\n');
                _json = JSON.parse(data);
                init();
            }
        });
        function init(){
            $(_evtId).remove();
            var _dom = $('<div><img style="width: 100%;height: 100%" id="'+_evtId+'" src="'+AppContext.joinPath(_folder,_json.spotImg)+'"></div>');

            function createCtrl(target){
                function getDoms(opt)
                {
                    var _str = '';
                    var _res = AppContext.joinPath(_folder,opt.src);
                     switch (opt.type)
                     {
                         case "video":

                             _str = '<a href="javascript:;" type="video" res="'+_res+'">'+
                                 '<img src="player/assert/images/hot_area_btn2.png" >'+
                                 '</a>';
                             break
                         case "text":
                             _str = '<a href="javascript:;" type="text">'+
                                 '<img src="player/assert/images/hot_area_btn3.png" >'+
                                 '</a>';
                             break
                         case "audio":
                             _str = '<a href="javascript:;" type="audio" res="'+_res+'" name="'+randomString(8)+'">'+
                                 '<img src="player/assert/images/hot_area_btn4.png" >'+
                                 '</a>';
                             break
                         default :
                             _str = '<a href="javascript:;" type="image" res="'+_res+'">'+
                                 '<img src="player/assert/images/hot_area_btn1.png" >'+
                                 '</a>';
                             break
                     }
                    return _str;
                }
                var _offset = target.offset();
                $('.hot_area').remove();
                var _l = (((target.width()) || target.width())- 168)*0.5;
                var _ctrl = '<div id="'+_ctrId+'" class="hot_area" style="left:'+Math.abs(_offset.left-$('#wrapperLeft').width()+_l)+'px;top: '+Math.abs(_offset.top-$('#wrapperTop').height()-75)+'px">'+
                    '<p class="hot_area_cont hot_area_btn" id="spot_play_list_c">';
                    for(var i=0;i<_json.items.length;i++)
                    {
                        _ctrl+=getDoms(_json.items[i]);
                    }
                    if(_json.des)   _ctrl+=getDoms({src:'',type:'text'});
                    _ctrl+='</p>'+
                    '<a href="javascript:;" title="关闭" class="hot_area_close" id="hots_ctrl_close"></a>'+
                    '<span class="triangle"></span>'+
                    '</div>';
                $(_mainCanvas).append(_ctrl);
                $('#hots_ctrl_close').bind('vclick',function(e){
                    $(this.parentNode).remove();
                    $('#spot_example_audio').remove();
                })

                $('#spot_play_list_c a').bind('click',function(e){
                    e.preventDefault();
                   var _that = $(this);

                    switch (_that.attr('type'))
                    {
                        case 'image':
                            imagePlay(_that.attr('res'));
                            break
                        case 'video':
                            videoPlay(_that.attr('res'));
                            break
                        case  'audio':
                            audioPlay(_that.attr('res'),e);
                            break
                        case 'text':
                            $('#'+_ctrId).hide();
                            textPlay(_json.des);
                            break
                    }
                });

                if(_json.des&& _json.items.length<1)
                {
                    $('#'+_ctrId).hide();
                    textPlay(_json.des,true);
                }else if(!_json.des && _json.items.length==1)
                {
                    if(_json.items[0].type !='audio') $('#'+_ctrId).hide();
                    $('#spot_play_list_c a').click();
                }
            }
            def.resolve(_dom);
            $('#'+_evtId).bind('vclick',function(e){
                var _list = $('.audiojs');
                for(var i=0;i<_list.length;i++)
                {
                    _list[i].remove();
                }
                var _dom = $('#'+_ctrId);
                if(!_dom[0])
                {
                    _dom.remove();
                    if(!_json.des && _json.items.length<1) return;
                    createCtrl($(this.parentNode));

                }else
                {
                    _dom.remove();
                    $('#spot_example_audio').remove();
                }

            });
        }

        function createPlayBox(_domstr){
            var _dom = $('<div id="spot_play_box" style="position: absolute;width: 100%;height: 100%;top: 0;left: 0;z-index: 9999">' +
                '<div id="spot_playbox_ctrl" style="position: absolute;background-color: #000000;opacity: 0.5;width: 100%;height: 100%"></div>' +
                '<a href="javascript:void(0)" class="spot-close-btn" id="spot_close_btn"></a>'+
                '<div id="spot_playbox_container" style="line-height: 50em;text-align:center;position: absolute;width: 90%;height: 90%;left: 5%;top: 5%;">' +_domstr+'</div>' +
                '</div>');
            return  _dom;
        }
        function videoPlay(url){
            for(var i=0;i<_medias.length;i++)
            {
                $('#'+_medias[i].a).remove();
                var _sel = '#'+_ctrId+' a[name='+_medias[i].p+']';
            }

            var _dom = '';
            if (getExtName(url) === 'swf') {
                if(RunningPlatform === "Android")
                {
                    if(_json.items.length<=1 && !_json.des)
                    {
                        $('#'+_ctrId).remove();
                    };
                    window.commInterface.openSwfFile(url,0);
                    return;
                }else
                {
                    _dom = createPlayBox( '<embed id="example_video_1" wmode="opaque" class="video-js vjs-default-skin"  width="100%" height="100%" src="' + url + '">')
                }

            }else
            {
                _dom = createPlayBox( '<video id="example_video_1" poster="share/assert/images/movie.png" class="video-js vjs-default-skin" preload="none" controls width="100%" height="100%">'
                    + '<source src="' + decodeURI(url) + '" type="video/mp4" />'
                    + '</video>' )
            }

            $(_mainCanvas).append(_dom);

            setTimeout(function(){
                if (getExtName(url) != 'swf'){
                    _dom.find('#example_video_1')[0].play()
                }
            },800)

            $('#spot_close_btn').bind('vclick',function(e){
                e.preventDefault();
                $(this.parentNode).remove();
                $('#'+_ctrId).show();
                if(_json.items.length<=1 && !_json.des)
                {
                    $('#'+_ctrId).remove();
                };
            });
        }



        function textPlay(str,only)
        {
            var _par =  $('#'+_ctrId);
            var _img =  $('#'+_evtId).parent();
            var _css = 'text-align:left';
            if(str.length<=7)_css = 'text-align:center;';
            var _ctrl = '<div id="spot_content_text" class="hot_area" style="left:'+0+';top: '+0+'">'+
                '<div id="hot_text_cont" class="hot_area_cont" style="word-break:break-word;display: block;font-size: 20px;margin: 0 8px;'+_css+';color:#ffffff">'+str+'</div>'+
                '<a href="javascript:;" title="关闭" class="hot_area_close" id="hots_text_close"></a>'+
//                '<span class="triangle"></span>'+
                '</div>';
            $(_mainCanvas).append(_ctrl);
            //修正位置
            var _css = {};
            var _text = $('#spot_content_text');

            if(_text.width()>368) {
                _text.css('width', 368);
                _css = {width:368};
            }
                var _llcoa = calcLoction();
                //,left:Math.floor(_par.css('left').replace('px',''))-100,top:Math.floor(_par.css('top').replace('px',''))-_par.height()
                if(calcDira("1001",_llcoa))
                {
                    _css.left = _img[0].offsetLeft+_img.width()
                    _css.top = _img[0].offsetTop-_text.height();
                }else if(calcDira("1010",_llcoa))
                {
                    _css.left = _img[0].offsetLeft-_text.width();
                    _css.top =_img[0].offsetTop-_text.height();
                }else if(calcDira("0101",_llcoa))
                {
                    _css.left = _img[0].offsetLeft+_img.width()
                    _css.top =_img[0].offsetTop+_img.height();
                }else if(calcDira("0110",_llcoa))
                {
                    _css.left =_img[0].offsetLeft-_text.width();
                    _css.top = _img[0].offsetTop+_img.height();
                }
                _text.css(_css);
            /*}else
            {
                var _ta = resetDirce(_par,_text)
                _css = {left:_img.offset().left - (_text.width()-_img.width())/2,top:_img.offset().top-_text.height()-10};
                $('#spot_content_text').css(_css);
            }*/

            $('#hots_text_close').bind('vclick',function(e){
                e.preventDefault();
                 $('#spot_content_text').remove();
                $('#'+_ctrId).show();
                if(_json.items.length<1)
                {
                    $('#'+_ctrId).remove();
                };
            })
            /**
             * 计算框休位置
             */
            function calcLoction()
            {
                //上，下，左，右
                var _loction=[0,0,0,0];
                var _width = _text.width(),_height=_text.height(),_left=_img[0].offsetLeft,_top=_img[0].offsetTop;
                var _winw=document.body.offsetWidth,_winh=window.outerHeight;
                if(_top-_height>10) _loction[0]=1;
                if(_top+_height+_img.height()<_winh) _loction[1]=1;
                if(_left-_width>10) _loction[2]=1;
                if(_left+_width+_img.width()<_winw-10) _loction[3]=1;
                return _loction;
            }
            //方向 string 1111
            function calcDira(_dic,_lco)
            {
                var _is = true;
                var _s = _dic.split('');
                for(var i=0;i<_dic.length;i++)
                {
                    if(_dic[i]=="1"){
                        if(_dic[i]!=_lco[i])
                        {
                            _is = false;
                            break;
                        }
                    }
                }
                return _is;
            }

        }

        function audioPlay(url,target)
        {
            for(var i=0;i<_medias.length;i++)
            {
                $('#'+_medias[i].a).remove();
                var _sel = '#'+_ctrId+' a[name='+_medias[i].p+']'
            }
            var _par =  $('#'+_ctrId).offset();
            var _name = $(target.target.parentNode).attr('name');
            var _dom =$('#spot_audio_'+_name);
            $('#'+_ctrId).hide();
            var _that= this;
            //seajs.use('player/assert/js/3rdparty/audio/audio.js', function () {
            var str="";
            if(RunningPlatform==='CEF'){//在cef 标签里有type标签就不行了
                     str = $('<div class="audiojs" style="width:180px;overflow:hidden;position:absolute;left: '+_par.left+'px; top:'+_par.top+'px">' +
                    '<audio controls="controls" id="spot_audio_'+_name+'" preload="auto" autoplay>'
                    + '<source src="' + decodeURI(url) + '"/>'
                    + '</audio><a href="javascript:;" title="关闭" style="position: absolute" class="hot_area_close" id="hots_audio_close"></a></div>');
            }else{
                    str = $('<div class="audiojs" style="width:180px;overflow:hidden;position:absolute;left: '+_par.left+'px; top:'+_par.top+'px">' +
                    '<audio controls="controls" id="spot_audio_'+_name+'" preload="auto" autoplay>'
                    + '<source src="' + decodeURI(url) + '" type="audio/mpeg" />'
                    + '</audio><a href="javascript:;" title="关闭" style="position: absolute" class="hot_area_close" id="hots_audio_close"></a></div>');
            }

                $(_mainCanvas).append(str);
                //audiojs.events.ready(function() {
                    //audiojs.createAll();
                    //$('.audiojs').css({left:_par.left,top:_par.top});
                    _medias.push({a:'spot_audio_'+_name,p:_name});
                    $('#hots_audio_close').bind('vclick',function(e)
                    {
                        e.preventDefault();
                        var _list = $('.audiojs');
                        //console.log(_list)
						for(var i=0;i<_list.length;i++)
                        {
                            $(_list[i]).remove();
                        }
                        $('#'+_ctrId).show()
                        if(_json.items.length<=1 && !_json.des)
                        {
                            $('#'+_ctrId).remove();
                        };
                    })
                //});
            //})
        }

        function imagePlay(url)
        {
            for(var i=0;i<_medias.length;i++)
            {
                $('#'+_medias[i].a).remove();
                var _sel = '#'+_ctrId+' a[name='+_medias[i].p+']';
                $(_sel).find('img').attr('src','player/assert/images/hot_area_btn4.png');
            }
            var _dom = createPlayBox( '<img style="position: relative;max-width:98%;max-height:95%" id="spot_content_image" src="'+url+'">' );
            $(_mainCanvas).append(_dom);



            $('#spot_close_btn').bind('vclick',function(e){
                e.preventDefault();
                $(this.parentNode).remove();
                $('#'+_ctrId).show();
                if(_json.items.length<=1 && !_json.des)
                {
                    $('#'+_ctrId).remove();
                };
                //$('#'+_ctrId).remove();
            });
        }
        //获取扩展名

        function getExtName(url) {
//        var result =/\.[^\.]+/.exec(url);
            var _name = null;
            _name = url.split(".");
            _name = _name[_name.length - 1];
            return _name.toLowerCase();
        };
        function randomString(a) {
            var b = "";
            a = 0 < parseInt(a) ? parseInt(a) : 10;
            for (var c = 0; c < a; c++)
                 var d =Math.floor(61 * Math.random()), b = b + "ABCDEFGHIJKLMNOPQRSTUVWXTZ0123456789abcdefghiklmnopqrstuvwxyz".substring(d, d + 1);
            return b
        }
        //定位两个元素的中心
        function resetDirce(_a,_b)
        {
            var _l = _a.offset().left - (_a.width() - _b.width())*0.5;
            var _t = _b.offset().top - _b.height();
            return {x:_l,y:_t};
        }
        return def.promise();
    };
});