/*
 @name: custom_follow.js
 @description:
 @require:
 @date: 2015/9/6
 @author: Nero(Nero@Nero-zou.com)
 */
var MATERIAL_SERVER_BASE=window.top.SITE_URL+'/';
var timer;
var comments;
var data_group = [];//todo 这里的数据 在分组变更之后未更新
var vm = new Vue({
    el: '#my-follow',
    data:{
        is_first:false,//是否只显示头条
        date_range:3,//全部公众号时，显示多少天的数据
        loading:false,
        leftKey:'',
        rightTitle:'全部公众号',
        leftActiveId:-1,
        leftData:[],
        search_data:[],
        article_all:[],
        article_one:[],
        article_header_wx:[],
        page_all:[],
        page_one:[],
        article_tab:true,
        puclic_all:[
            {
                num: ''
            }
        ]
    },
    methods: {
        clickAddMaterial: function(obj, e) {
            var offset=$(e.target).offset();
            offset.left=offset.left+190;
            offset.top=offset.top+90;
            window.top.Material.addMaterialToCart(obj.article_url,offset);
        },
        clickAddMaterialElse:function(obj, e){
            window.top.Material.addMaterialToElseCart(obj.article_url);
        },
        headerShow: function () {
            this.is_first = !this.is_first
            getArticleAll();

        },

        menuListShow: function (data_i) {
            vm.$set("leftActiveId", data_i.group_id);
            if (data_i.gzh_num == 0 || data_i.accounts != undefined) {
                return;
            }
            $.get(MATERIAL_SERVER_BASE + 'follow/gaccounts', {
                group_id: data_i.group_id
            }, function (data) {

                data = $.parseJSON(data);

                if (data.data.length > 0) {
                    var temp = [];
                    for (var i = 0, max = data.data.length; i < max; i++) {
                        var lev2 = data.data[i];
                        temp.push({
                            id: lev2.id,
                            name: lev2.name,
                            avatar: lev2.avatar,
                            desc: lev2.desc,
                            group: lev2.group,
                            is_verify: lev2.is_verify,
                            qrcode: lev2.qrcode,
                            update_time: lev2.update_time,
                            weixin_id: lev2.weixin_id
                        });
                    }
                    data_i.$set('accounts', temp);
                }

            })

        },

        artilceOneShow: function (obj) {
            var $id = obj.id;
            this.article_tab = false;
            var $article_header_wx = [];
            var $article_one = [];
            this.rightTitle='单个公众号';
            var $page_one = [];
            vm.$set('loading',true);
            $.getJSON(MATERIAL_SERVER_BASE + 'follow/single', {
                gzh_id: obj.id,
                page: 1
            }, function (data) {
                vm.$set('loading',false);

                for (var i in data.data) {

                    for (var j = 0, max = data.data[i].length; j < max; j++) {

                        var data_name = i;
                        data_name = data_name.split("_");
                        data_name = data_name[0].split("-")[1] + "月" + data_name[0].split("-")[2] + "日";
                        //
                        //var index=(new Date(data.data[i][j].publish_time)).getTime();
                        //index=index-parseInt(data.data[i][j].idx);
                        $article_one.push({
                            article_time: data_name,
                            article_title: data.data[i][j].article_title,
                            article_url: data.data[i][j].article_url,
                            content_type: data.data[i][j].content_type,
                            id: data.data[i][j].id,
                            idx: data.data[i][j].idx,
                            like_num: data.data[i][j].like_num,
                            publish_time: data.data[i][j].publish_time,
                            read_num: data.data[i][j].read_num,
                            update_time: data.data[i][j].update_time,
                            article_text: i

                        });
                    }
                }


                for (var i = 1, max = $article_one.length; i < max; i++) {

                    for (var j = 0; j < i; j++) {

                        if ($article_one[i].article_text == $article_one[j].article_text) {

                            $article_one[i].article_time = 0;
                        }

                    }

                }

                vm.$set('article_one', $article_one);


                $article_header_wx.push({
                    avatar_url: data.gzh_info.avatar_url,
                    wx_account: data.gzh_info.wx_account,
                    wx_desc: data.gzh_info.wx_desc,
                    wx_name: data.gzh_info.wx_name,
                    update_time: data.gzh_info.update_time,
                    id: $id
                });

                vm.$set('article_header_wx', $article_header_wx);

                $page_one.push({
                    firstRecord: data.pager.firstRecord,
                    lastRecord: data.pager.lastRecord,
                    numPages: data.pager.numPages,
                    numRecords: data.pager.numRecords,
                    page: data.pager.page,
                    perPage: data.pager.perPage
                });

                if ($page_one[0].page == $page_one[0].numPages) {
                    $(".js-loadMoresingleOne").hide();
                } else {
                    $(".js-loadMoresingleOne").show();
                }
                vm.$set('page_one', $page_one);
            }).error(function () {
                toastr.error("服务器繁忙","加载数据失败");
                vm.$set('loading',false);
            });


        },
        artShow:function(id)
        {
            vm.$data.article_tab = false;
            var $article_header_wx = [];
            var $article_one = [];
            this.rightTitle='单个公众号';
            var $page_one = [];

            $.get(MATERIAL_SERVER_BASE + 'follow/single', {
                gzh_id: id,
                page: 1
            }, function (data) {
                data = $.parseJSON(data);

                for (var i in data.data) {

                    for (var j = 0, max = data.data[i].length; j < max; j++) {

                        var data_name = i;
                        data_name = data_name.split("_");
                        data_name = data_name[0].split("-")[1] + "月" + data_name[0].split("-")[2] + "日";
                        //
                        //var index=(new Date(data.data[i][j].publish_time)).getTime();
                        //index=index-parseInt(data.data[i][j].idx);
                        $article_one.push({
                            article_time: data_name,
                            article_title: data.data[i][j].article_title,
                            article_url: data.data[i][j].article_url,
                            content_type: data.data[i][j].content_type,
                            id: data.data[i][j].id,
                            idx: data.data[i][j].idx,
                            like_num: data.data[i][j].like_num,
                            publish_time: data.data[i][j].publish_time,
                            read_num: data.data[i][j].read_num,
                            update_time: data.data[i][j].update_time,
                            article_text: i

                        });
                    }
                }


                for (var i = 1, max = $article_one.length; i < max; i++) {

                    for (var j = 0; j < i; j++) {

                        if ($article_one[i].article_text == $article_one[j].article_text) {

                            $article_one[i].article_time = 0;
                        }

                    }

                }

                vm.$set('article_one', $article_one);


                $article_header_wx.push({
                    avatar_url: data.gzh_info.avatar_url,
                    wx_account: data.gzh_info.wx_account,
                    wx_desc: data.gzh_info.wx_desc,
                    wx_name: data.gzh_info.wx_name,
                    update_time: data.gzh_info.update_time,
                    id: id
                });

                vm.$set('article_header_wx', $article_header_wx);

                $page_one.push({
                    firstRecord: data.pager.firstRecord,
                    lastRecord: data.pager.lastRecord,
                    numPages: data.pager.numPages,
                    numRecords: data.pager.numRecords,
                    page: data.pager.page,
                    perPage: data.pager.perPage
                });

                if ($page_one[0].page == $page_one[0].numPages) {
                    $(".js-loadMoresingleOne").hide();
                } else {
                    $(".js-loadMoresingleOne").show();
                }
                vm.$set('page_one', $page_one);
            });
        },
        searchPublicNum: function (key) {
            console.log(key)
        },
        searchPublicNumHide: function () {
            $("#list_search").hide();
            $("#list_menu").show();
            $("#resultNO").hide();
            vm.$data.leftKey = '';
            vm.$data.article_tab = true;
        },
        latelyTime: function (day) {
            this.date_range=day;
            getArticleAll();
        },

        loadMoreall: function () {
            var $last_$article_all = vm.$data.article_all;
            var new_array = [];
            var $article_all = [];
            $article_all = $article_all.concat($last_$article_all, new_array);
            var $page = this.page_all;
            var $num = parseInt($page.numPages);
            var last_num = parseInt($page.page);

            last_num += 1;

            if (last_num <= $num) {

                $.get(MATERIAL_SERVER_BASE + 'client/follow/index', {
                    page: last_num,
                    days: 0
                }, function (data) {
                    data = $.parseJSON(data);
                    for (var i = 0, max = data.data.length; i < max; i++) {
                        $article_all.push({
                            article_title: data.data[i].article_title,
                            article_url: data.data[i].article_url,
                            content_type: data.data[i].content_type,
                            id: data.data[i].id,
                            publish_time: data.data[i].publish_time,
                            update_time: data.data[i].update_time,
                            read_num: data.data[i].read_num,
                            gzh_name:data.data[i].gzh_name
                        })
                    }
                    vm.$set('article_all', $article_all);

                    vm.$set('page_all', data.pager);
                })


            }
        },
        loadMoreOne: function () {
            var oldData = this.article_one;
            var existIds = {};
            for (var i = 0; i < oldData.length; i++) {
                var obj = oldData[i];
                existIds[obj.id] = true;
            }

            var new_array = [];
            var $last_article_one = vm.$data.article_one;
            var $article_one = [];
            var $page_total = vm.$data.page_one[0].numPages;
            var $page_num = vm.$data.page_one[0].page;
            $page_num++;
            var $id = $(".js-my-follow-article-one-header").data("id");

            if ($page_num == $page_total) {
                $(".js-loadMoresingleOne").hide();
            }
            vm.$set('loading',true);
            $.getJSON(MATERIAL_SERVER_BASE + 'follow/single', {
                gzh_id: $id,
                page: $page_num
            }, function (data) {
                vm.$set('loading',false);

                var newData = [];
                for (var i in data.data) {
                    for (var j = 0, max = data.data[i].length; j < max; j++) {

                        var data_name = i;
                        data_name = data_name.split("_");
                        data_name = data_name[0].split("-")[1] + "月" + data_name[0].split("-")[2] + "日";
                        var data_i = data.data[i][j];
                        if (existIds[data_i.id]) {
                            continue;
                        }

                        newData.push({
                            article_time: data_name,
                            article_title: data_i.article_title,
                            article_url: data_i.article_url,
                            content_type: data_i.content_type,
                            id: data_i.id,
                            idx: data_i.idx,
                            like_num: data_i.like_num,
                            publish_time: data_i.publish_time,
                            read_num: data_i.read_num,
                            update_time: data_i.update_time,
                            article_text: i
                        });
                    }
                }
                oldData = oldData.concat(newData);

                vm.$set('article_one', oldData);
                vm.$set('page_one', [data.pager]);
            }).error(function () {
                toastr.error("服务器繁忙","加载数据失败");
                vm.$set('loading',false);
            });

        },

        showAll: function () {
            this.rightTitle='全部公众号';
            $("#list_search").hide();
            $("#list_menu").show();
            $("#resultNO").hide();
            vm.$data.leftKey = '';
            vm.$data.article_tab = true;
        },
        openByOuter:function(href){
            window.top.openUrlToBrowser(href);
        },
        addFollow:function(){
            var $url_pop,
                $id;
            var gzh_ids;
            var $geturl = [];
            var temp=_.template($("#add-my-num").html());
            var w = Win.confirm({
                title: '添加我关注的公众号',
                width: '508px',
                height: '340px',
                keyboard: false,
                backdrop: 'static',
                content: temp(data_group),
                yesFunc: function () {

                    var dest = w.find(".li-checked"),
                        dest_id = dest.data("id"),
                        $name = dest.find(".js-create-group-name").text();

                    if (dest.length > 0) {
                        $.post(MATERIAL_SERVER_BASE + 'follow/add', {
                            url: $url_pop,
                            id: $id,
                            group_id: dest_id
                        }, function (data) {

                            data = $.parseJSON(data);
                            if (data.errcode == 0) {
                                updateAccountGroup();
                                w.modal('hide');
                            } else {
                                toastr.error("", data.message);
                            }

                        });
                    }
                    else {
                        toastr.error("", "请选择要添加的分组");
                    }

                    return false;

                },
                noFunc: function () {
                    return false
                }
            });

            w.find(".js-geturl-btn").click(function () {

                var $that = $(this);
                var $query = $(".js-query-wx-num");
                var $url = $(".js-geturl-input").val();

                if ($url.length > 0 && $url.match(/^http:\/\/mp.weixin.qq.com/)!=null) {
                    var loading=showLoading($that);
                    $.getJSON(MATERIAL_SERVER_BASE + 'follow/query', {
                        url: $url
                    }, function (data) {
                        loading.revert();
                        if (data.errcode === 0) {
                            toastr.success("", data.message);
                            $query.data("id", data.gzh_info.id);
                            console.log("$url:" + $url_pop);
                            $id = data.gzh_info.id;
                            $url_pop = $url;
                            $query.find("img").attr("src", data.gzh_info.avatar);
                            $query.find(".wx-name").text(data.gzh_info.name);
                            $query.find(".wx-num").text(data.gzh_info.weixin_id);

                            $geturl.push({
                                avatar: data.gzh_info.avatar,
                                crawl_url: data.gzh_info.crawl_url,
                                desc: data.gzh_info.desc,
                                id: data.gzh_info.id,
                                name: data.gzh_info.name,
                                weixin_id: data.gzh_info.weixin_id,
                                wx_biz: data.gzh_info.wx_biz
                            });
                            $(".js-pop-getURl-intro").hide();
                            $(".js-pop-getURl-content").show();
                            gzh_ids = data.gzh_info.id;
                        }
                        else {
                            toastr.error("", data.message);
                        }
                    });
                }
                else {
                    toastr.error("", "请填写正确的地址");
                }
            });

            w.find("#pop-list-add-group").click(function () {

                var $val = $(".js-pop-move-input").val();
                if ($val.length > 0) {
                    $.post(MATERIAL_SERVER_BASE + 'group/add', {
                        type: 1,
                        name: $val
                    }, function (data) {

                        data = $.parseJSON(data);
                        if (data.errcode === 0) {
                            w.find(".js-pop-list-ul li").removeClass("li-checked");
                            $('.js-pop-list-ul').prepend(' <li class="li-checked" data-id="' + data.group_id + '"><span class="js-create-group-name">' + $val + '</span> <i class="fa fa-trash js-trash pull-right "></i> <i class="fa fa-edit js-edit pull-right"></i> <div class="create-group-input"><input value="' + $val + '" maxlength="8" placeholder="不超过8个汉字" class="js-create-group-input"/></div> </li>');
                            updateAccountGroup();
                        }
                        else {
                            toastr.error("", "添加失败");
                        }

                    });

                }
                else {
                    toastr.error("", "分组名称不能为空");
                }
            });
        },
        followList:function(){
            var url=MATERIAL_SERVER_BASE+'client/follow/accounts';
            var innerWin=window.top.GUI.Window.open(url, {
                position: 'center',
                height:600,
                width:1120,
                "title": "微小宝客户端",
                "icon": "assest/img/icon.png",
                "toolbar": true,
                "frame": true
            });
        },
        refreshPage:function(){
            window.location.reload();
        }
    }

});

vm.$watch('leftKey', function (newVal) {

    var $search_data = [];
    var $key = newVal;

    if ($key.length > 0) {

        clearTimeout(timer);

        $("#list_search").show();
        $("#list_menu").hide();
        $(".del").show();
        //$("#resultNO").hide();
        timer = setTimeout(function () {
            $.get(MATERIAL_SERVER_BASE + 'follow/accounts', {
                kw: $key
            }, function (data) {

                data = $.parseJSON(data);

                if (data.length < 1) {

                    $("#list_search").hide();
                    $("#resultNO").show();
                }
                else {
                    for (var i = 0, max = data.length; i < max; i++) {
                        $search_data.push({
                            avatar: data[i].avatar,
                            id: data[i].id,
                            name: data[i].name
                        });
                    }

                    vm.$set("search_data", $search_data);

                    $("#list_search").show();
                    $("#resultNO").hide();

                }
            })

        }, 300);

    }
    else {
        $("#list_search").hide();
        $("#list_menu").show();
        $(".del").hide();
        $("#resultNO").hide();
        vm.$data.article_tab = true;
    }
});


function init() {
    page_layout();
    var $scope = vm.$data.leftData;
    var $scpe_li = vm.$data.leftDataLi;
    var $cope_time = vm.$data.lastet_time;
    $.getJSON(MATERIAL_SERVER_BASE + 'follow/accounts', {}, function (data) {
        var $puclic_all = vm.$data.puclic_all;
        $puclic_all[0].num = 0;
        for (var i = 0, max = data.length; i < max; i++) {
            $scope.push({
                group_id: data[i].group_id,
                group_name: data[i].group_name,
                gzh_num: data[i].gzh_num,
                open: false,
                arrow: false
            });
            $puclic_all[0].num = $puclic_all[0].num + parseInt($scope[i].gzh_num);
            if (i === 0) {
                $scope[0].open = false;
            }
            if (data[i].accounts) {

                $scope[i].accounts = [];

                for (var j = 0, inmax = data[i].accounts.length; j < inmax; j++) {
                    $scope[i].accounts.push({
                        avatar: data[i].accounts[j].avatar,
                        desc: data[i].accounts[j].desc,
                        group: data[i].accounts[j].group,
                        id: data[i].accounts[j].id,
                        is_verify: data[i].accounts[j].is_verify,
                        name: data[i].accounts[j].name,
                        qrcode: data[i].accounts[j].qrcode,
                        update_time: data[i].accounts[j].update_time,
                        weixin_id: data[i].accounts[j].weixin_id
                    });
                }

            }

        }
        vm.$set("puclic_all", $puclic_all);
        vm.$set("leftData", $scope);
        $(".js-menu-list-all").show();


    });

    getArticleAll();

    $.post(MATERIAL_SERVER_BASE + 'follow/groups', {}, function (response) {
        if(response.errcode==0){
            data_group = response.data;
        }else{
            toastr.error("","加载分组信息失败");
        }
    },'json');
    modalEvents();
}


function updateAccountGroup(){
    var temp = [];

    $.getJSON(MATERIAL_SERVER_BASE + 'follow/accounts', {}, function (data) {
        data_group=data;
        var $puclic_all = vm.$get('puclic_all');
        $puclic_all[0].num = 0;

        for (var i = 0, max = data.length; i < max; i++) {
            temp.push({
                group_id: data[i].group_id,
                group_name: data[i].group_name,
                gzh_num: data[i].gzh_num,
                open: false,
                arrow: false
            });
            $puclic_all[0].num = $puclic_all[0].num + parseInt(temp[i].gzh_num);

            if (i === 0) {
                temp[0].open = false;
            }
            if (data[i].accounts) {

                temp[i].accounts = [];

                for (var j = 0, inmax = data[i].accounts.length; j < inmax; j++) {
                    temp[i].accounts.push({
                        avatar: data[i].accounts[j].avatar,
                        desc: data[i].accounts[j].desc,
                        group: data[i].accounts[j].group,
                        id: data[i].accounts[j].id,
                        is_verify: data[i].accounts[j].is_verify,
                        name: data[i].accounts[j].name,
                        qrcode: data[i].accounts[j].qrcode,
                        update_time: data[i].accounts[j].update_time,
                        weixin_id: data[i].accounts[j].weixin_id
                    });
                }

            }
        }
        vm.$set("leftData", temp);
        vm.$set("puclic_all", $puclic_all);

    }).error(function(){
        toastr.error("","更新分组信息失败");
    });
}
/**
 * 添加关注 事件
 */
function modalEvents(){
    //删除
    $(document).on("click", ".js-trash", function (e) {

        e.stopPropagation();
        var $this = $(this);
        var $id = $this.closest("li").data("id");

        $.post(MATERIAL_SERVER_BASE + 'group/delete', {
            id: $id
        }, function (data) {

            data = $.parseJSON(data);
            if (data.errcode == 0) {

                $this.closest("li").remove();
               updateAccountGroup();
            }
        });
    });


    $(document).on("click", ".js-edit", function (e) {

        e.stopPropagation();

        var $this = $(this);
        var $id = $this.closest("li").data("id");

        $(this).closest("li").find(".create-group-input").show();

    });


    $(document).on("click", ".js-pop-list-ul li", function () {

        $(this).addClass("li-checked").siblings().removeClass("li-checked");

    });

    $(document).on("click", ".js-create-group-input", function (e) {
        e.stopPropagation();
    })

    $(document).on("click", ".modal-scrollable", function () {
        var $leftData = vm.$data.leftData;
        $(".create-group-input").each(function (i) {
            var $this = $(this);
            var $name = $this.find(".js-create-group-input").val();
            var $id = $this.closest("li").data("id");

            if (!$this.is(":hidden") && $name.length > 0) {

                $(".js-create-group-name").eq(i).text($name);

                $.post(MATERIAL_SERVER_BASE + 'group/modify', {
                    id: $id,
                    name: $name
                }, function (data) {

                });

                for (var i = 0, max = $leftData.length; i < max; i++) {
                    if ($leftData[i].group_id == $id) {

                        $leftData[i].group_name = $name;
                    }

                }
                vm.$set("leftData", $leftData);
            }

        });

        $(".create-group-input").hide();

    });
}


function getArticleAll(config) {

    var $article_all = [];
    var defaultConfig = {
        page: 1,
        is_first: vm.$get('is_first')?1:0,
        days: vm.$get('date_range')
    }
    vm.$set('loading',true);
    config = $.extend(true, {}, defaultConfig, config);
    $.getJSON(MATERIAL_SERVER_BASE + 'client/follow/index', {
        page: config.page,
        is_first: config.is_first,
        days: config.days

    }, function (data) {
        vm.$set('loading',false);
        for (var i = 0, max = data.data.length; i < max; i++) {
            $article_all.push({
                article_title: data.data[i].article_title,
                article_url: data.data[i].article_url,
                content_type: data.data[i].content_type,
                id: data.data[i].id,
                publish_time: data.data[i].publish_time,
                update_time: data.data[i].update_time,
                read_num: data.data[i].read_num,
                gzh_name:data.data[i].gzh_name
            })
        }
        vm.$set('article_all', $article_all);

        vm.$set('page_all', data.pager);

    }).error(function () {
        toastr.error("服务器繁忙","加载数据失败");
        vm.$set('loading',false);
    });
}

$(window).resize(function(){
    page_layout();
});
function page_layout(){
    var winHeight=$(window).height();
    $('#list_menu').height(winHeight-140);
}

function showLoading(target) {
    var oldHtml = target.html();
    target.addClass('js-loading disabled');
    var fa= target.find('i.fa');
    if(fa.length==0){
        try{
            target.prepend('<i class="fa fa-spinner fa-loading"></i> ');
        }catch (e){

        }
    }else{
        fa.attr('class','fa fa-spinner fa-loading');
    }
    return {
        revert: function () {
            target.html(oldHtml);
            target.removeClass('js-loading disabled');
        }
    };
}