/**
 * Khởi tạo prototype xử lý inject
 * @constructor
 * @author Dung tao
 */
function Inject($, tabId) {
    this.$ = $;
    this.tabId = tabId;

    // @TODO Chèn dữ nút
    this.initDataTrader();
}

Inject.prototype.initDataTrader = function () {
    var _self = this;
    var is_open = false;
    //var myArray = [55000, 53000, 51000, 52000, 53000, 56000, 57000, 58000, 59000, 60000, 61000];

    var myArray = [5000, 6000, 8000, 7000, 9000, 10000, 11000, 12000, 13000];

    var rand_time = myArray[(Math.random() * myArray.length) | 0];

    var tadusoft_html = '<div class="tadusoft-crawldata-form-panel">'
            + '<form id="tadusoft-crawldata-form" class="tadusoft-crawldata-form" onsubmit="return false">'

            + '<div class="form-group m-b-5">'
            + '<select class="form-control" name="tadusoft_category_id" id="tadusoft_category_id">'
            + '<option> -Select Category- </option>'
            + '</select>'
            + '</div>'

            + '<div class="form-group m-b-5">'
            + '<select class="form-control" name="tadusoft_group_id" id="tadusoft_group_id">'
            + '<option> -Select Group- </option>'
            + '</select>'
            + '</div>'

            + '<div class="form-group m-b-5">'
            + '<select class="form-control" name="tadusoft_sub_id" id="tadusoft_sub_id">'
            + '<option> -Select Sub- </option>'
            + '</select>'
            + '</div>'

            + '<div class="form-group m-b-5">'
            + '<input type="number" class="form-control" placeholder="Khoảng cân nặng (kg)" name="tadusoft_estimate_weight" id="tadusoft_estimate_weight" value="1"/>'
            + '</div>'

            + '<div class="form-group m-b-5">'
            + '<div class="tadusoft-crawldata-btn-create" id="tadusoft-btn-crawldata-list" style="float: left">'
            + '<button type="button">'
            + '<span class="tadusoft-heart">'
            + '<i class="material-icons">favorite</i>'
            + '</span> '
            + '<a>Lấy danh sách</a>'
            + '</button>'
            + '<button type="button" id="tadusoft-btn-crawl-start">Tiếp Tục</button>'
            //+ '<button type="button" class="btn btn-sm btn-primary bold tadusoft-bookmark-btn-save" style="padding: 0px 40px;color: #fff !important; ">Lấy dữ liệu</button>'
            + '</div>'
            + '</div>'
            + '</form>'
            + '</div>'

            + '<div class="tadusoft-crawldata-btn-create hide" id="tadusoft-btn-auto" style="float: left">'
            + '<button type="button">'
            + '<span class="tadusoft-heart">'
            + '<i class="material-icons">favorite</i>'
            + '</span> '
            + '<a>SP đang lấy tự động</a>'
            + '</button>'

            + '<button type="button" id="tadusoft-btn-start">Tiếp Tục</button>'
            //+ '<button type="button" id="tadusoft-btn-stop">Dừng tự động</button>'

            + '</div>'
        ;

    if(window.innerWidth > 800){
        this.$("body").after(tadusoft_html);
    }


    //var local_crawl_status = localStorage.getItem('crawl_status');
    // if(local_crawl_status === 'true') {
    //     _self.$("#tadusoft-btn-start").hide();
    //     _self.$("#tadusoft-btn-stop").show();
    // } else {
    //     _self.$("#tadusoft-btn-start").show();
    //     _self.$("#tadusoft-btn-stop").hide();
    // }

    if(location.href.indexOf('detail.tmall.com/item.htm?') > 0){
        var current_url = window.location.href;
        var new_url = current_url.replace("item.htm?", "item_o.htm?de_count=1&");
        window.location.href = new_url;
    }

    if (location.href.indexOf('/category') > 0 || location.href.indexOf('search.htm?') > 0) {
        // Trang danh sách taobao


    } else if (location.href.indexOf('/item/') > 0 || location.href.indexOf('item.htm?') > 0 || location.href.indexOf('item_o.htm?') > 0) {
        _self.checkItemCodeExisted();

    } else {
        _self.$("#tadusoft-btn-start").show();
    }

    if(location.hostname.indexOf('vi.aliexpress') == 0){
        alert("Chuyển sang tiếng anh để tiếp tục");
    }   else {
        //mở đoạn code này để tự động lấy danh sách, chi tiết sản phẩm hoặc feedback

        //_self.handleCrawlAliexpress();
        //_self.handleCrawlAliexpressDetail();
        //_self.handleCrawlAliexpressFeedback();
    }



    _self.getCategory();
    _self.$("#tadusoft_category_id").on("change", function (e) {
        _self.getGroupByCatId(e);
    });

    _self.$("#tadusoft_group_id").on("change", function (e) {
        _self.getSubCategoryByID(e);
    });

    _self.$("#tadusoft-btn-crawl-start").on("click", function (e) {
        alert('start');
        _self.start_crawl(e);
    });

    _self.$("#tadusoft-btn-auto").on("click", function (e) {
        alert('crawl_auto');
        _self.handleCrawlData(e);
    });

    _self.$("#tadusoft-btn-start").on("click", function (e) {
        alert('start');
        _self.start_crawl(e);
    });

    _self.$("#tadusoft-btn-stop").on("click", function (e) {
        alert('stop');
        localStorage.setItem("crawl_status", 'false');
        window.location.reload();
    });


    //auto crawl data : get data from page detail
    /*
     var count = 0;
     window.setTimeout(function () {
     setInterval(function () {

     if (count == 1) {
     _self.$(document).scrollTop(_self.$('.nav_bar').offset().top);
     }

     if (count == 2) {
     // _self.$(document).scrollTop(_self.$('.nav_bar').offset().top);
     }

     if (count == 3) {
     //_self.$(document).scrollTop(_self.$('.nav_bar').offset().top + 500);
     }

     if (count == 6) {
     _self.$(document).scrollTop(_self.$('.nav_bar').offset().top + 500);
     }

     if (count == 7) {
     _self.$(document).scrollTop(_self.$('.nav_bar').offset().top + 1000);
     }

     if (count == 8) {
     _self.$(document).scrollTop(_self.$('.nav_bar').offset().top + 2000);
     }

     if (count == 9) {
     _self.$(document).scrollTop(_self.$('.nav_bar').offset().top + 3500);
     }

     console.log('===>> count: ', count);


     count++;

     if (count == 12) {
     if (!_self.is_open) {
     _self.handleCrawlData();
     } else {
     console.log("===== Link already open ===== ");
     }
     _self.is_open = true;
     }
     if(count == 30){
     _self.handleNextDetailPage();
     }

     }, rand_time);

     }, 300);


     */

    this.$("#tadusoft-btn-crawldata-list").on("click", function (e) {

        if(location.hostname.indexOf('taobao') > 0 || location.hostname.indexOf('tmall') > 0){
            // nếu lấy dữ liệu từ trang taobao
            _self.handleCrawlAlibaba(e);

        } else {
            // nếu lấy dữ liệu từ trang aliexpress
            if (location.href.indexOf('/item/') > 0) {
                _self.handleCrawlData(e);
            } else {
                //get list
                _self.handleCrawlPageManual(e);
            }
        }



        //_self.handleCrawlMenuALL(e);

        //_self.handleCrawlAliexpressFeedback(e);



         // _site = new Aliexpress(_self.$);

        //var feedbackData = _site.getFeedback();
        //console.log('==== feedbackData', feedbackData);

        // console.log("===", _site.getFeedbackPagination());
         //var domData = _site.getPagination();
         //console.log("===>>> crawl list: ", domData);

        //var domData = _site.getDetail();
        //console.log("===>>> crawl detail: ", domData);

        // _self.$("ul.tab-lists li[ae_button_type=tab_feedback]").trigger("click");
        // _self.$("feedback-container .f-filter-list label:first").trigger("click");

    });
};


Inject.prototype.handleCrawlMenuALL = function (e) {
    var _self = this;

    var _site = null;
    //if (location.hostname.indexOf('aliexpress.com') > 0) {
    _site = new Aliexpress(_self.$);
    //}

    var domData = _site.getMenu();

    console.log("===menu ALL: ", domData);

    chrome.runtime.sendMessage(
        {
            message: {
                method: "POST",
                action: "xhttp",
                url: "https://mmodropship.com/api/crawl_menu",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify(domData)
            }
        },
        function (response) {
            console.log("===== response: ", response);
        }
    );


}


// event on crawl list product (page)
Inject.prototype.handleCrawlAliexpress = function (e) {
    var _self = this;

    var _site = null;

    if (location.hostname.indexOf('aliexpress') > 0 && location.href.indexOf('feedback.aliexpress.com') == -1) {
        _site = new Aliexpress(_self.$);

        //get list
        if (location.href.indexOf('&page=') > 0 || location.href.indexOf('?page=') > 0 || location.href.indexOf('?&page=') > 0 || location.href.indexOf('/category/') > 0 || location.href.indexOf('/wholesale?') > 0) {

            var myArray = [2800, 2500, 3000, 1500, 4000, 3550, 1800, 2300, 1900];

            var rand_time = myArray[(Math.random() * myArray.length) | 0];

            var count = 0;
            var temp_next_page = false;
            var _top = '.nav-breadcrumb';

            window.setTimeout(function () {
                setInterval(function () {

                    try {

                        if (count == 2 && !_self.$("#wrapper").length) {
                            _self.$(document).scrollTop(_self.$(_top).offset().top + 500);
                        }

                        if (count == 3 && !_self.$("#wrapper").length) {
                            _self.$(document).scrollTop(_self.$(_top).offset().top + 800);
                        }

                        if (count == 4 && !_self.$("#wrapper").length) {
                            _self.$(document).scrollTop(_self.$(_top).offset().top + 1000);
                        }

                        if (count == 5 && !_self.$("#wrapper").length) {
                            _self.$(document).scrollTop(_self.$(_top).offset().top + 1500);
                        }

                        if (count == 6 && !_self.$("#wrapper").length) {
                            _self.$(document).scrollTop(_self.$(_top).offset().top + 2000);
                        }

                        if (count == 7 && !_self.$("#wrapper").length) {
                            _self.$(document).scrollTop(_self.$(_top).offset().top + 2500);
                        }

                        if (count == 8 && !_self.$("#wrapper").length) {
                            _self.$(document).scrollTop(_self.$(_top).offset().top + 3000);
                        }

                        if (count == 9 && !_self.$("#wrapper").length) {
                            _self.$(document).scrollTop(_self.$(_top).offset().top + 3500);
                        }

                        if (count == 10 && !_self.$("#wrapper").length) {
                            _self.$(document).scrollTop(_self.$(_top).offset().top + 4000);
                        }
                        if (count == 11 && !_self.$("#wrapper").length) {
                            _self.$(document).scrollTop(_self.$(_top).offset().top + 4500);
                        }
                        if (count == 12 && !_self.$("#wrapper").length) {
                            _self.$(document).scrollTop(_self.$(_top).offset().top + 5000);
                        }
                        if (count == 13 && !_self.$("#wrapper").length) {
                            _self.$(document).scrollTop(_self.$(_top).offset().top + 5500);
                        }
                        console.log('===>> count: ', count);

                        count++;

                        if (count == 15) {
                            var domData = _site.getPagination();
                            console.log("===>>> crawl list: ", domData);


                            chrome.runtime.sendMessage(
                                {
                                    message: {
                                        method: "POST",
                                        action: "xhttp",
                                        url: "https://mmodropship.com/api/store_pagination",
                                        dataType: "json",
                                        contentType: "application/json",
                                        data: JSON.stringify(domData)
                                    }
                                },
                                function (response) {

                                    console.log("===== response: ", response);

                                    if (typeof response.next_link !== 'undefined' && response.next_link.length > 0) {

                                        response.next_link.forEach(function (currentValue, index) {
                                            window.location.href = currentValue;

                                            //window.open(currentValue, '_blank');
                                        });
                                    } else {
                                        alert('Không lấy được trang kế tiếp');
                                        //console.log("==>>> Không lấy được trang kế tiếp")
                                        // window.close();
                                    }


                                }
                            );



                        }

                    } catch(err){
                        if(!temp_next_page){
                            //alert("có lỗi xảy ra");
                            console.log('==>> có lỗi rồi');
                            //_top = '.header-wrap';
                            //temp_next_page = true;
                            _self.crawl_next_pagination();
                        }

                    }

                }, rand_time); //rand_time
            }, 1000);
        }
    }
}


Inject.prototype.crawl_next_pagination = function (e) {

    chrome.runtime.sendMessage(
        {
            message: {
                method: "GET",
                action: "xhttp",
                url: "https://mmodropship.com/api/crawl_aliexpress_next_pagination",
                dataType: "json",
                contentType: "application/json"
            }
        },
        function (response) {
            if (typeof response.next_link !== 'undefined' && response.next_link.length > 0) {
                response.next_link.forEach(function (currentValue, index) {
                    window.location.href = currentValue;
                });
            } else {
                alert('Đã lấy hết sản phẩm, vui lòng nạp thêm sản phẩm');
            }


        }
    );

};


// event on crawl detail
Inject.prototype.handleCrawlAliexpressDetail = function (e) {
    var _self = this;
    var _site = null;

    if (location.hostname.indexOf('aliexpress') > 0) {
        _site = new Aliexpress(_self.$);
    }

    if (location.href.indexOf('p/error') > 0) {
        _self.handleNextDetailPage();
    }

    //get detail
    if (location.href.indexOf('/item/') > 0) {

        var myArray = [1900, 2000, 3000, 1500, 1700, 1600, 1200, 2300, 1800];

        var rand_time = myArray[(Math.random() * myArray.length) | 0];

        var count = 0;


            window.setTimeout(function () {
                setInterval(function () {

                    try{

                    var _top = '.store-header';

                    if (count == 2) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 500);
                    }

                    if (count == 3) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 800);
                    }

                    if (count == 4) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 1000);
                        _self.$("ul.tab-lists li[ae_button_type=tab_specs]").trigger("click");
                    }

                    if (count == 5) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 1500);
                        _self.$("ul.tab-lists li[ae_button_type=tab_feedback]").trigger("click");
                    }

                    if (count == 6) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 2000);
                        //_self.$("feedback-container .f-filter-list label:first").trigger("click");
                    }

                    if (count == 7) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 2500);
                        _self.$("ul.tab-lists li[ae_button_type=tab_prodetail]").trigger("click");
                    }

                    if (count == 8) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 1200);
                    }

                    if (count == 9) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 3000);
                        _self.$("[data-widget-type=customText]").each(function(){
                            _self.$(this).remove();
                        });
                    }

                    if (count == 10) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 4000);
                    }
                    if (count == 11) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 4500);
                    }
                    if (count == 12) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 5000);
                    }
                    if (count == 13) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 5500);
                    }
                    if (count == 14) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 6500);
                    }
                    if (count == 15) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 8000);
                    }
                    if (count == 16) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 9500);
                    }
                    if (count == 17) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 11000);
                    }
                    if (count == 18) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 1300);
                    }

                    console.log('===>> count: ', count);

                    count++;

                    if (count == 20) {
                        var domData = _site.getDetail();
                        console.log("===>>> crawl detail: ", domData);

                        _self.$.LoadingOverlay("show");

                        chrome.runtime.sendMessage(
                            {
                                message: {
                                    method: "POST",
                                    action: "xhttp",
                                    url: "https://mmodropship.com/api/crawl_aliexpress_detail",
                                    dataType: "json",
                                    contentType: "application/json",
                                    data: JSON.stringify(domData)
                                }
                            },
                            function (response) {
                                console.log("===>>", response);
                                _self.$.LoadingOverlay("hide");
                                if (typeof response.status !== 'undefined' && response.status == 'success') {
                                    //alert('Đã lưu thành công ');

                                    if (typeof response.next_link !== 'undefined' && response.next_link.length > 0) {

                                        response.next_link.forEach(function (currentValue, index) {
                                            window.location.href = currentValue;
                                            //alert(currentValue);
                                        });
                                    } else {
                                        alert('Đã lấy hết sản phẩm tự động');
                                    }
                                }
                            }
                        );
                    }

                    if (count == 40) {
                        // next page
                        _self.handleNextDetailPage();

                    }

                    } catch(err){
                        // next page
                        //alert('có lỗi xảy ra');
                        _self.handleNextDetailPage();

                    }

                }, rand_time); //rand_time

            }, 1000);
        
    }


};


// event on crawl detail manual aliexpress
Inject.prototype.handleCrawlData = function (e) {
    var _self = this;

    var _site = null;

    if (location.hostname.indexOf('aliexpress') > 0) {
        _site = new Aliexpress(_self.$);


        //get aliexpress detail
        if (location.href.indexOf('/item/') > 0) {
            var domData = _site.getDetail();
            console.log("===>>> crawl detail: ", domData);

            var cat_id = _self.$("#tadusoft_category_id").val();
            var group_id = _self.$("#tadusoft_group_id").val();
            var sub_id = _self.$("#tadusoft_sub_id").val();
            var est_weight = _self.$("#tadusoft_estimate_weight").val();

            domData.category_id = cat_id;
            domData.group_id = group_id;
            domData.sub_id = sub_id;
            domData.est_weight = est_weight;


            _self.$.LoadingOverlay("show");


            chrome.runtime.sendMessage(
                {
                    message: {
                        method: "POST",
                        action: "xhttp",
                        url: "https://mmodropship.com/api/crawl_aliexpress_detail_manual",
                        dataType: "json",
                        contentType: "application/json",
                        data: JSON.stringify(domData)
                    }
                },
                function (response) {
                    console.log("===>>", response);
                    _self.$.LoadingOverlay("hide");
                    if (typeof response.status !== 'undefined' && response.status == 'success') {
                        alert('Đã thêm thành công sản phẩm mới');
                    }
                }
            );
            

        } else {
            var domData = _site.getList();

            console.log("===>>> dom: ", domData);

            if (typeof domData.item_list !== 'undefined' && domData.item_list.length > 0) {

                var cat_id = _self.$("#tadusoft_category_id").val();
                var group_id = _self.$("#tadusoft_group_id").val();
                var sub_id = _self.$("#tadusoft_sub_id").val();
                var est_weight = _self.$("#tadusoft_estimate_weight").val();

                if (cat_id > 0) {

                } else {
                    alert('Vui lòng chọn LOẠI SẢN PHẨM');
                    return null;
                }

                domData.category_id = cat_id;
                domData.group_id = group_id;
                domData.sub_id = sub_id;
                domData.est_weight = est_weight;

                chrome.runtime.sendMessage(
                    {
                        message: {
                            method: "POST",
                            action: "xhttp",
                            url: "https://mmodropship.com/api/crawl_product_list",
                            dataType: "json",
                            contentType: "application/json",
                            data: JSON.stringify(domData)
                        }
                    },
                    function (response) {

                        console.log("===>>>", response);

                        if (typeof response.status !== 'undefined' && typeof response.count_success !== 'undefined' && response.status == 'success') {
                            alert('Đã lưu: ' + response.count_success);
                        } else {
                            alert('Có lỗi xảy ra');
                        }
                    }
                );

            } else {
                //Chưa lấy được dữ liệu từ DOM, lấy trang tiếp theo để đọc
                alert('không lấy được dữ liệu');
            }
        }

    }

    if(location.hostname.indexOf('taobao') > 0){
        _site = new Taobao(_self.$);
    }
    if(location.hostname.indexOf('tmall') > 0) {
        _site = new Tmall(_self.$);
    }

    //get detail
    if(location.href.indexOf('item.htm?') > 0 || location.href.indexOf('item_o.htm?') > 0 ){

        _self.$.LoadingOverlay("show");

        var domData = _site.getData();
        console.log('==== domData', domData);

        var cat_id = _self.$("#tadusoft_category_id").val();
        var group_id = _self.$("#tadusoft_group_id").val();
        var sub_id = _self.$("#tadusoft_sub_id").val();
        var est_weight = _self.$("#tadusoft_estimate_weight").val();

        domData.category_id = cat_id;
        domData.group_id = group_id;
        domData.sub_id = sub_id;
        domData.est_weight = est_weight;

        /*
        chrome.runtime.sendMessage(
            {
                message: {
                    method: "POST",
                    action: "xhttp",
                    url: "https://mmodropship.com/api/crawl_alibaba_detail",
                    dataType: "json",
                    contentType: "application/json",
                    data: JSON.stringify(domData)
                }
            },
            function(response) {

                _self.$.LoadingOverlay("hide");

                console.log("===>>", response);
                if(typeof response.status !== 'undefined' && typeof response.message_code !== 'undefined' && response.status == 'success'){

                    if(typeof response.save_type !== 'undefined' && response.save_type == 'new'){
                        alert('Đã thêm thành công sản phẩm mới');
                    }

                } else {

                    if( typeof response.message_code !== 'undefined' && response.message_code == 'empty_category'){
                        alert('Bạn phải chọn Loại sản phẩm');
                    } else {
                        alert('Có lỗi xảy ra');
                    }


                }
            }
        );
        */


    }



};

// event on crawl detail Alibala manual
Inject.prototype.handleCrawlAlibaba = function (e) {
    var _self = this;
    var _site = null;

    if(location.hostname.indexOf('taobao') > 0){
        _site = new Taobao(_self.$);
    }
    if(location.hostname.indexOf('tmall') > 0) {
        _site = new Tmall(_self.$);
    }

    //get detail
    if(location.href.indexOf('item.htm?') > 0 || location.href.indexOf('item_o.htm?') > 0 ){

        _self.$.LoadingOverlay("show");

        var domData = _site.getData();
        console.log('==== domData', domData);

        var cat_id = _self.$("#tadusoft_category_id").val();
        var group_id = _self.$("#tadusoft_group_id").val();
        var sub_id = _self.$("#tadusoft_sub_id").val();
        var est_weight = _self.$("#tadusoft_estimate_weight").val();

        domData.category_id = cat_id;
        domData.group_id = group_id;
        domData.sub_id = sub_id;
        domData.est_weight = est_weight;


         chrome.runtime.sendMessage(
         {
         message: {
         method: "POST",
         action: "xhttp",
         url: "https://mmodropship.com/api/crawl_alibaba_detail",
         dataType: "json",
         contentType: "application/json",
         data: JSON.stringify(domData)
         }
         },
         function(response) {

         _self.$.LoadingOverlay("hide");

         console.log("===>>", response);
         if(typeof response.status !== 'undefined' && typeof response.message_code !== 'undefined' && response.status == 'success'){

         // if(typeof response.save_type !== 'undefined' && response.save_type == 'new'){
             alert('Đã thêm thành công sản phẩm mới');
         // }

         } else {

         if( typeof response.message_code !== 'undefined' && response.message_code == 'empty_category'){
         alert('Bạn phải chọn Loại sản phẩm');
         } else {
         alert('Có lỗi xảy ra');
         }


         }
         }
         );
         


    }



};


Inject.prototype.handleCrawlPageManual = function (e) {
    var _self = this;

    var _site = null;

    if (location.hostname.indexOf('aliexpress') > 0 && location.href.indexOf('feedback.aliexpress.com') == -1) {
        _site = new Aliexpress(_self.$);

        var domData = _site.getPagination();
        console.log("===>>> crawl list: ", domData);

        var cat_id = _self.$("#tadusoft_category_id").val();
        var group_id = _self.$("#tadusoft_group_id").val();
        var sub_id = _self.$("#tadusoft_sub_id").val();
        var est_weight = _self.$("#tadusoft_estimate_weight").val();

        domData.category_id = cat_id;
        domData.category_group_id = group_id;
        domData.category_sub_id = sub_id;
        domData.est_weight = est_weight;


        chrome.runtime.sendMessage(
            {
                message: {
                    method: "POST",
                    action: "xhttp",
                    url: "https://mmodropship.com/api/store_pagination_manual",
                    dataType: "json",
                    contentType: "application/json",
                    data: JSON.stringify(domData)
                }
            },
            function (response) {

                console.log("===== response: ", response);

                if (typeof response.status !== 'undefined' && typeof response.count_success !== 'undefined' && response.status == 'success') {
                    alert('Đã lưu: ' + response.count_success);
                } else {
                    alert('Có lỗi xảy ra');
                }


            }
        );

    }
}





// event on save
Inject.prototype.handleNextDetailPage = function (e) {

    //Chưa lấy được dữ liệu từ DOM, lấy trang tiếp theo để đọc
    chrome.runtime.sendMessage(
        {
            message: {
                method: "GET",
                action: "xhttp",
                url: "https://mmodropship.com/api/next_product",
                dataType: "json",
                contentType: "application/json"
            }
        },
        function (response) {
            console.log("===== response: ", response);
            if (typeof response.next_link !== 'undefined' && response.next_link.length > 0) {
                response.next_link.forEach(function (currentValue, index) {
                    //alert(currentValue);
                    window.location.href = currentValue;
                });
            } else {
                alert('Không lấy được trang kế tiếp');
                //console.log("==>>> Không lấy được trang kế tiếp")
                // window.close();
            }


        }
    );

};


Inject.prototype.getCategory = function (e) {
    var _self = this;

    //Chưa lấy được dữ liệu từ DOM, lấy trang tiếp theo để đọc
    chrome.runtime.sendMessage(
        {
            message: {
                method: "GET",
                action: "xhttp",
                url: "https://mmodropship.com/api/category_list",
                dataType: "json",
                contentType: "application/json"
            }
        },
        function (response) {

            console.log("===== category: ", response);

            if (typeof response.category_list !== 'undefined' && response.category_list.length > 0) {

                response.category_list.forEach(function (currentValue, index) {

                    _self.$("#tadusoft_category_id").append('<option value="' + currentValue.id + '" >' + currentValue.name + '</option>');

                });
            } else {
                alert('Không lấy được Category');
            }


        }
    );

};


Inject.prototype.getGroupByCatId = function (e) {
    var _self = this;

    var catId = _self.$("#tadusoft_category_id").val();
    //Chưa lấy được dữ liệu từ DOM, lấy trang tiếp theo để đọc
    chrome.runtime.sendMessage(
        {
            message: {
                method: "GET",
                action: "xhttp",
                url: "https://mmodropship.com/api/group_category/" + catId,
                dataType: "json",
                contentType: "application/json"
            }
        },
        function (response) {

            console.log("===== Group: ", response);
            _self.$("#tadusoft_group_id").show();
            _self.$("#tadusoft_group_id option").remove();
            _self.$("#tadusoft_group_id").append('<option> - Select Group - </option>');

            if (typeof response.group_list !== 'undefined' && response.group_list.length > 0) {

                response.group_list.forEach(function (currentValue, index) {
                    _self.$("#tadusoft_group_id").append('<option value="' + currentValue.id + '" >' + currentValue.name + '</option>');

                });
            } else {
                _self.$("#tadusoft_group_id").hide();
                _self.$("#tadusoft_sub_id").hide();
                //alert('Không lấy được Group');
                console.log("===>>> Không lấy được Group");
            }


        }
    );

};

Inject.prototype.getSubCategoryByID = function (e) {
    var _self = this;

    var groupId = _self.$("#tadusoft_group_id").val();
    //Chưa lấy được dữ liệu từ DOM, lấy trang tiếp theo để đọc
    chrome.runtime.sendMessage(
        {
            message: {
                method: "GET",
                action: "xhttp",
                url: "https://mmodropship.com/api/sub_category/" + groupId,
                dataType: "json",
                contentType: "application/json"
            }
        },
        function (response) {

            console.log("===== Sub: ", response);
            _self.$("#tadusoft_sub_id").show();
            _self.$("#tadusoft_sub_id option").remove();
            _self.$("#tadusoft_sub_id").append('<option value=""> - Select Sub - </option>');

            if (typeof response.sub_list !== 'undefined' && response.sub_list.length > 0) {
                response.sub_list.forEach(function (currentValue, index) {
                    _self.$("#tadusoft_sub_id").append('<option value="' + currentValue.id + '" >' + currentValue.name + '</option>');

                });
            } else {
                _self.$("#tadusoft_sub_id").hide();
                //alert('Không lấy được SUB Category');
                console.log("===>>> Không lấy được SUB Category");
            }


        }
    );

};


Inject.prototype.checkItemCodeExisted = function (e) {
    var _self = this;
    var _site = null;

    if (location.hostname.indexOf('aliexpress') > 0) {
        _site = new Aliexpress(_self.$);
    }
    if(location.hostname.indexOf('taobao') > 0){
        _site = new Taobao(_self.$);
    }
    if(location.hostname.indexOf('tmall') > 0) {
        _site = new Tmall(_self.$);
    }
    
    var item_code = _site.get_item_code();
    console.log("=== item_code: ", item_code);

    chrome.runtime.sendMessage(
        {
            message: {
                method: "GET",
                action: "xhttp",
                url: "https://mmodropship.com/api/check_item_code_existed/" + item_code,
                dataType: "json",
                contentType: "application/json"
            }
        },
        function (response) {

            var myArray = [5000, 6000, 8000, 7000, 9000, 10000, 11000, 12000, 13000];

            var rand_time = myArray[(Math.random() * myArray.length) | 0];

            console.log("===== check item code: ", response);
            if (typeof response.status !== 'undefined') {

                if (response.status == true) {

                    var crawl_status = localStorage.getItem('crawl_status');
                    console.log("===>>> crawl_status: ", crawl_status);

                    if (typeof response.crawl_status !== 'undefined' && response.crawl_status == '1') {
                        console.log("===>>> Sản phẩm hoàn tất");
                        _self.$(".tadusoft-crawldata-form-panel").hide();
                        _self.$("#tadusoft-btn-auto").removeClass('hide');
                        _self.$("#tadusoft-btn-auto a").text("SP Hoàn tất");

                        //_self.handleNextDetailPage();

                        if (crawl_status === 'true') {
                            //_self.start_crawl(e);
                        } else {
                            // _self.$("#tadusoft-btn-start").show();
                            // _self.$("#tadusoft-btn-stop").hide();
                        }


                    } else {
                        console.log("===>>> Sản phẩm này đã tồn tại");
                        _self.$(".tadusoft-crawldata-form-panel").hide();
                        _self.$("#tadusoft-btn-auto").removeClass('hide');
                        _self.$("#tadusoft-btn-auto a").text("SP đã hoàn tất");



                    }


                } else {
                    console.log("===>>> Đây là sản phẩm mới");
                    _self.$(".tadusoft-crawldata-form-panel").show();
                    _self.$("#tadusoft-btn-crawldata-list a").text("Lấy sản phẩm này");
                }
            } else {
                alert("Vui lòng reload lại trang web, hoặc liên hệ người quản trị");
            }


        }
    );

};


Inject.prototype.start_crawl = function (e) {

    localStorage.setItem("crawl_status", 'true');

    chrome.runtime.sendMessage(
        {
            message: {
                method: "GET",
                action: "xhttp",
                url: "https://mmodropship.com/api/next_product",
                dataType: "json",
                contentType: "application/json"
            }
        },
        function (response) {
            if (typeof response.next_link !== 'undefined' && response.next_link.length > 0) {
                response.next_link.forEach(function (currentValue, index) {
                    window.location.href = currentValue;
                });
            } else {
                alert('Đã lấy hết sản phẩm, vui lòng nạp thêm sản phẩm');
            }


        }
    );

};

// event on save
Inject.prototype.handleCrawlAliexpressFeedback = function (e) {
    var _self = this;
    var _site = null;

    if (location.hostname.indexOf('aliexpress') > 0) {
        _site = new Aliexpress(_self.$);
    }
    //get feedback
    if (location.href.indexOf('feedback.aliexpress.com') > 0) {
        var myArray = [1900, 2000, 3000, 1500, 1700, 1600, 1200, 2300, 1800];

        var rand_time = myArray[(Math.random() * myArray.length) | 0];

        var count = 0;
        
        window.setTimeout(function () {
            setInterval(function () {

                try{

                    var _top = '.customer-reviews';

                    if (count == 1) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 500);
                    }

                    if (count == 2) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 800);
                    }

                    if (count == 3) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 1500);
                    }

                    if (count == 4) {
                        _self.$(document).scrollTop(_self.$(_top).offset().top + 3000);
                    }



                    console.log('===>> count: ', count);

                    count++;

                    if (count == 5) {
                        var feedbackData = _site.getFeedback();
                        console.log('==== feedbackData', feedbackData);
                        
                        if(feedbackData.feedback_arr.length == 0){
                            _self.handleNextFeedback();
                        } else {
                            _self.$.LoadingOverlay("show");

                            chrome.runtime.sendMessage(
                                {
                                    message: {
                                        method: "POST",
                                        action: "xhttp",
                                        url: "https://mmodropship.com/api/crawl_aliexpress_feedback",
                                        dataType: "json",
                                        contentType: "application/json",
                                        data: JSON.stringify(feedbackData)
                                    }
                                },
                                function (response) {
                                    console.log("===>>", response);
                                    _self.$.LoadingOverlay("hide");

                                    var next_page = _site.getFeedbackPagination();
                                    if(next_page == null){
                                        _self.handleNextFeedback();
                                    }else {
                                        window.location.href = next_page;
                                    }

                                }
                            );
                        }


                    }

                } catch(err){
                    // next page
                    alert('có lỗi xảy ra');
                    _self.handleNextFeedback();

                }

            }, rand_time); //rand_time

        }, 1000);
        
    }
};

// event on save
Inject.prototype.handleNextFeedback = function (e) {

    //Chưa lấy được dữ liệu từ DOM, lấy trang tiếp theo để đọc
    chrome.runtime.sendMessage(
        {
            message: {
                method: "GET",
                action: "xhttp",
                url: "https://mmodropship.com/api/next_feedback",
                dataType: "json",
                contentType: "application/json"
            }
        },
        function (response) {
            console.log("===== response: ", response);
            if (typeof response.next_link !== 'undefined' && response.next_link.length > 0) {
                response.next_link.forEach(function (currentValue, index) {
                    window.location.href = currentValue;
                });
            } else {
                alert('Không lấy được trang kế tiếp');
                //console.log("==>>> Không lấy được trang kế tiếp")
                // window.close();
            }


        }
    );

};