/**
 * Created by manhdung on 6/10/18.
 */
function Aliexpress($) {
    this.$ = $;

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

Aliexpress.prototype.initDataTrader = function() {
    this.DOM = {
        items_list: ".product-container .product-list ul.list-items li.list-item"
    };
};

// get list pagination
Aliexpress.prototype.getData = function(e) {
    var _self = this;

    //items
    var items_arr = [];
    _self.$(_self.DOM.items_list).each(function(){

        var href = _self.$(this).find('a').attr('href');
        var img_source = _self.$(this).find('img.goods_list_img').data('original');
        var item_name = _self.$(this).find('o.transcon').text();
        var item_price = _self.$(this).find('span.sg_color').text();

        var item_detail = {
            href : href,
            image: img_source,
            short_desc: item_name,
            unit_price: item_price
        }

        items_arr.push(item_detail);

    });
    if(items_arr.length > 0){
        return items_arr;    
    } else {
        return [];
    }
    

};


// get detail
Aliexpress.prototype.getDetail = function(e) {
    var _self = this;

    var itemName = _self.$("h1.product-title-text").text();
    if((itemName.trim() === '' || typeof itemName === 'undefined' || itemName === null)){
        itemName = _self.$("div.title--wrap--Ms9Zv4A h1").text();
    }

    var unit_price_original = _self.$(".product-price-original span.product-price-value").text();
    if((unit_price_original.trim() === '' || typeof unit_price_original === 'undefined' || unit_price_original === null)){
        unit_price_original = _self.$(".pdp-info .product-price .price--original--qDQaH8V .price--originalText--Zsc6sMv").text();
    }

    // chưa lấy được
    var product_sold = _self.$(".product-info span.product-reviewer-sold").text();
    var product_review_rating = _self.$(".product-info span.overview-rating-average").text();

    var unit_price = _self.$(".product-price-current span.product-price-value").text();
    if((unit_price.trim() === '' || typeof unit_price === 'undefined' || unit_price === null)){
        unit_price = _self.$(".product-price-current").text();
    }

    var uniform_unit_price = _self.$(".uniform-banner span.uniform-banner-box-price").text();
    if((unit_price.trim() === '' || typeof unit_price === 'undefined' || unit_price === null) && uniform_unit_price != ''){
        unit_price = uniform_unit_price;
    }

    var item_video_src = _self.$(".product-main .video-container .video-wrap video").attr('src');
    if(typeof item_video_src === 'undefined' || item_video_src === null){
        item_video_src = _self.$(".pdp-info .video--wrap--NfR8r9l video source").attr('src');
    }

    // chưa lấy được
    var item_video_image = _self.$(".product-main .video-container img").attr('src');
    if(item_video_image === 'undefined' || typeof item_video_image === null){
        item_video_image = _self.$(".pdp-info .video--wrap--NfR8r9l video").attr('poster');
    }


    var item_code = _self.$("input[name=productId]").val();
    var item_url = location.href;
    var item_url_array = item_url.split('/');
    if(item_url_array.length > 4){
        var  item_url_code1 = item_url_array[4];
        var item_url_code1_arr = item_url_code1.split('.');
        item_code = item_url_code1_arr[0];
    }


    var shop_name = _self.$("div.shop-name a").text();
    var shop_link = _self.$("div.shop-name a").attr('href');
    if((shop_name.trim() === '' || typeof shop_name === 'undefined' || shop_name === null)){
        shop_name = _self.$("a.store-header--storeName--vINzvPw").text();
        shop_link = _self.$("a.store-header--storeName--vINzvPw").attr('href');
    }

    var avatar = _self.$(".img-view-wrap .image-viewer .image-view-magnifier-wrap img.magnifier-image").attr('src');
    if( typeof avatar === 'undefined' || avatar === null){
        avatar = _self.$(".pdp-info .image-viewer .image-view-magnifier-wrap img.magnifier-image").attr('src');
    }


    //attach images
    var tab_images_arr = [];

    _self.$(".img-view-wrap .image-viewer ul.images-view-list li img").each(function(){
        var data_image = _self.$(this).attr('src').replace('_50x50.jpg_.webp', '');
        tab_images_arr.push(data_image);
    });

    if(tab_images_arr.length == 0){
        _self.$(".pdp-info .slider--wrap--PM2ajTZ .slider--box--TJYmEtw .slider--img--D7MJNPZ img").each(function(){
            var data_image = _self.$(this).attr('src');
            tab_images_arr.push(data_image);
        });
    }


    var description_img_arr = [];
    _self.$("#product-description .detail-desc-decorate-richtext img").each(function(){
        var data_image = _self.$(this).attr('src');
        description_img_arr.push(data_image);
    });


    _self.$("#product-description p img").each(function(){
        var data_image = _self.$(this).attr('src');
        description_img_arr.push(data_image);
    });
    
    if(description_img_arr.length == 0){
        _self.$("#product-description img").each(function(){
            var data_image = _self.$(this).attr('src');
            description_img_arr.push(data_image);
        });
    }


    var description_span_arr = [];
    _self.$("#product-description span").each(function(){
        var data_text = _self.$(this).html();
        if(_self.$(this).find('span').length == 0 && data_text.length > 0){
            description_span_arr.push(data_text);
        }
    });


    /*======Start sku data=======*/
    var attr_option_arr = [];
    if(_self.$(".product-sku .sku-property").length){
        _self.$(".product-sku .sku-property").each(function(){
            var attr_name = _self.$(this).find(".sku-title").text();
            var option_arr = [];

            _self.$(this).find("ul.sku-property-list li.sku-property-item .sku-property-image").each(function(){
                var option_obj = {
                    option_name: _self.$(this).find('img').attr('title'),
                    option_src: _self.$(this).find('img').attr('src').replace('_50x50.jpg_.webp', ''),
                    option_type: 'image'
                };
                option_arr.push(option_obj);
            });

            _self.$(this).find("ul.sku-property-list li.sku-property-item .sku-property-text").each(function(){
                var option_obj = {
                    option_name: _self.$(this).find('span').text(),
                    option_src: _self.$(this).find('span').text(),
                    option_type: 'text'
                };
                option_arr.push(option_obj);
            });

            if(option_arr.length > 0){
                var attr_obj = {
                    name: attr_name,
                    option_data: option_arr
                };
                attr_option_arr.push(attr_obj);
            }
        });
    }


    if(attr_option_arr.length == 0){
        _self.$(".sku--wrap--o7E5T0f .sku-item--property--Wk6aoYj").each(function(){
            var attr_name = _self.$(this).find(".sku-item--title--gcxMSdg").text();
            var option_arr = [];

            _self.$(this).find(".sku-item--box--6Mh3HRv .sku-item--image--mXsHo3h").each(function(){
                var option_obj = {
                    option_name: _self.$(this).find('img').attr('alt'),
                    option_src: _self.$(this).find('img').attr('src'),
                    option_type: 'image'
                };
                option_arr.push(option_obj);
            });

            _self.$(this).find(".sku-item--box--6Mh3HRv .sku-item--text--s0fbnzX").each(function(){
                var option_obj = {
                    option_name: _self.$(this).find('span').text(),
                    option_src: _self.$(this).find('span').text(),
                    option_type: 'text'
                };
                option_arr.push(option_obj);
            });

            if(option_arr.length > 0){
                var attr_obj = {
                    name: attr_name,
                    option_data: option_arr
                };
                attr_option_arr.push(attr_obj);
            }
        });
    }


    /*======End sku data=======*/
    // cần phải có đoạn này để giả lập click nhảy qua tab chi tiết
    //_self.$("ul.tab-lists li[ae_button_type=tab_specs]").trigger( "click" );

    var goodsDetailArr = [];
    _self.$(".product-specs ul.product-specs-list li.product-prop").each(function(){
        var detail_obj = {
            title: _self.$(this).find('span.property-title').text(),
            text: _self.$(this).find('span.property-desc').text()
        }

        goodsDetailArr.push(detail_obj);
    });

    if(goodsDetailArr.length == 0){
        _self.$(".specification--list--fiWsSyv li.specification--line--iUJOqof").each(function(){
            var detail_obj = {
                title: _self.$(this).find('div.specification--title--UbVeyic span').text(),
                text: _self.$(this).find('div.specification--desc--Mz148Bl span').text()
            }

            goodsDetailArr.push(detail_obj);
        });
    }

    var iframe_review_src = _self.$(".product-reviews iframe.product-evaluation").attr('src');

    var shipping_data = 0;
    _self.$(".product-dynamic-shipping .dynamic-shipping .dynamic-shipping-line strong").each(function(){
        var shipping_text = _self.$(this).text();
        if(shipping_text == 'Free Shipping'){
            shipping_data = 0;
        }
        if(shipping_text.length > 0){
            if (shipping_text.indexOf('$') > 0) {
                var shipping_arr = shipping_text.split('$');
                shipping_data = shipping_arr[1];
            }
        }
    });




    //https://stackoverflow.com/questions/38602543/is-there-a-way-to-access-json-ld-via-javascript-if-it-doesnt-have-an-id

    var jsonld_arr = JSON.parse(document.querySelector('script[type="application/ld+json"]').innerText);
    console.log("json ld array: ",jsonld_arr);
    for  (var i = 0; i < jsonld_arr.length; i++) {
        var jsonld_obj = jsonld_arr[i];

        if(typeof itemName === 'undefined' && typeof jsonld_obj.name !== 'undefined'){
            itemName = jsonld_obj.name;
        }

        if( typeof avatar === 'undefined' && typeof jsonld_obj.image !== 'undefined'){
            var json_image = jsonld_obj.image;
            if(typeof json_image[0] !== 'undefined' ){
                avatar = json_image[0];

                if(typeof item_video_image === 'undefined'){
                    item_video_image = avatar;
                }
            }
        }

        if(typeof jsonld_obj.aggregateRating !== 'undefined' && product_review_rating === ''){
            if(typeof jsonld_obj.aggregateRating.ratingValue !== 'undefined'){
                product_review_rating = jsonld_obj.aggregateRating.ratingValue;
            }
        }

        if(typeof unit_price === 'undefined' && typeof jsonld_obj.offers !== 'undefined'){
            unit_price = jsonld_obj.offers.price;
        }
    }

    var feedback_arr = [];
    _self.$(".ae-evaluateList-box .ae-evaluateList-card").each(function(){

        var username = _self.$(this).find(".ae-evaluateList-card-name").text();
        if(username.length == 0){
            username = 'Shopper';
        }
        //var user_country = _self.$(this).find(".ae-evaluateList-card-name").text();
        var review_title = _self.$(this).find(".ae-evaluateList-card-title").text();
        var review_text = _self.$(this).find(".ae-evaluateList-card-content").text();
        var review_time = _self.$(this).find(".ae-evaluateList-card-date").text();
        var review_image_arr = [];
        _self.$(this).find(".ae-evaluateList-card-img-box img.ae-evaluateList-card-img").each(function(){
            var img = _self.$(this).attr('src');
            review_image_arr.push(img);
        });

        //var ali_feedback_id = _self.$(this).find(".f-content .feedback-id").val();

        var feedback_obj = {
            username: username,
            //ali_feedback_id: ali_feedback_id,
            //user_country: user_country,
            review_title: review_title,
            review_text: review_text,
            review_time: review_time,
            //review_rate: review_rate,
            review_image_arr: review_image_arr
        }
        feedback_arr.push(feedback_obj);

    });



    return {
        name: itemName,
        unit_price: unit_price,
        unit_price_original: unit_price_original,
        item_code: item_code,
        shop_name: shop_name,
        shop_link: shop_link,
        avatar: avatar,
        tab_images_arr: tab_images_arr,
        attr_option_arr: attr_option_arr,
        description_img_arr: description_img_arr,
        description_text_arr: description_span_arr,
        goodsDetailArr: goodsDetailArr,
        original_link: location.href,
        item_video_src: item_video_src,
        item_video_image: item_video_image,
        product_sold: product_sold,
        shipping_price: shipping_data,
        product_review_rating: product_review_rating,
        iframe_review_src : iframe_review_src,
        feedback_arr: feedback_arr
    };


};

//vào trang home để lấy: https://www.aliexpress.com/
Aliexpress.prototype.getMenu = function(e) {
    var _self = this;

    //items
    var menu_arr = [];

    _self.$(".categories-list-box .cl-item").each(function(){

        var child_group_ul = _self.$(_self.$(this).find('.sub-cate .sub-cate-main .sub-cate-content .sub-cate-row .sub-cate-items'));

        var menu_href = _self.$(this).find('dt.cate-name a').attr('href');
        var menu_label = _self.$(this).find('dt.cate-name a').text();

        console.log('====>>> category: ',menu_label+"===="+ menu_href);

        var menu_child_arr = [];

        child_group_ul.each(function(){

            var menu_child_group_href = _self.$(this).find('dt a').attr('href');

            if(menu_child_group_href.length > 1){

                var menu_child_group_label = _self.$(this).find("dt a").text();

                console.log('====>>> group: ',menu_child_group_label+"===="+ menu_child_group_href);

                var menu_child_sub_arr = [];
                _self.$(this).find('dd a').each(function(){

                    var menu_child_sub_obj = {
                        sub_href : _self.$(this).attr("href"),
                        sub_label: _self.$(this).text()
                    }
                    console.log('====>>> Sub: ',menu_child_sub_obj);
                    menu_child_sub_arr.push(menu_child_sub_obj);
                });

                var menu_child_obj = {
                    group_href : menu_child_group_href,
                    group_label: menu_child_group_label,
                    sub_arr: menu_child_sub_arr
                };
                menu_child_arr.push(menu_child_obj);

            }

        });

        var menu_obj = {
            href : menu_href,
            label: menu_label,
            sub_menu: menu_child_arr
        };

        menu_arr.push(menu_obj);

    });

    if(menu_arr.length > 0){
        return menu_arr;
    } else {
        return [];
    }
};



// get list pagination
Aliexpress.prototype.getPagination = function(e) {
    var _self = this;

    //items
    var items_arr = [];

    var category_href = location.href;
    var category_code =  findParam(category_href, 'CatId');
    var search_text = '';

    var category_id =  findParam(category_href, 'mmo-category');
    var group_id =  findParam(category_href, 'mmo-group');
    var sub_id =  findParam(category_href, 'mmo-sub');

    if((category_code == '' || typeof category_code === 'undefined') && location.href.indexOf('/wholesale?') > 0){
        category_code =  findParam(category_href, 'catId');
        search_text =  findParam(category_href, 'SearchText');
    }

    if(category_code == '' || typeof category_code === 'undefined'){
        var category_array = category_href.split('/');
        if(category_array.length > 4){
            var  category_code1 = category_array[4];
            var category_code1_arr = category_code1.split('?');
            category_code = category_code1_arr[0];
        }
    }
    
    _self.$(".product-container .JIIxO a").each(function(){

        var href = _self.$(this).attr('href');
        var product_id = _self.$(this).data('product-id');
        if(typeof product_id === 'undefined' && typeof href !== 'undefined' && href.length > 0){
            var product_arr = href.split('/');

            var code_position = 2;
            if(href.substring(1, 5) == 'item'){
                code_position = 2;
            } else {
                code_position = 4;
            }

            if(product_arr.length > 0){
                var  product_code = product_arr[code_position];
                var product_code1_arr = product_code.split('.');
                product_id = product_code1_arr[0];
            }
        }
        //var img_source = _self.$(this).find('img.top').attr('src');
        //var item_name = _self.$(this).find('a').attr('title');
        //var item_price = _self.$(this).find('span.sg_color').text();

        if( typeof href !== 'undefined' && href.length > 0 && product_id.length > 0){
            var href_data = href.substr(0, href.indexOf('?'));
            if(href_data.length > 0){
                var item_detail = {
                    href : href_data,
                    product_id : product_id
                    //image: img_source,
                    //short_desc: item_name,
                    //unit_price: item_price
                }
                items_arr.push(item_detail);
            }

        }
    });
    
    return {
        category_code: category_code,
        search_text: search_text,
        category_id: category_id,
        category_group_id: group_id,
        category_sub_id: sub_id,
        item_list: items_arr
    };

};

function findParam(url, param){
    var check = "" + param;
    if(url.search(check )>=0){
        return url.substring(url.search(check )).split('&')[0].split('=')[1];
    }
}

// get feedback
Aliexpress.prototype.getFeedback = function(e) {
    var _self = this;

    var item_code = findParam(location.href, 'productId');
    var feedback_arr = [];

    _self.$(".feedback-list-wrap .feedback-item").each(function(){
        var username = _self.$(this).find(".fb-user-info .user-name a").text();
        if(username.length == 0){
            username = 'Shopper';
        }
        var user_country = _self.$(this).find(".user-country b").text();
        var review_text = _self.$(this).find(".fb-main .buyer-feedback span:first").text();
        var review_time = _self.$(this).find(".fb-main .buyer-feedback .r-time-new").text();
        var review_image_arr = [];
        _self.$(this).find(".r-photo-list ul li.pic-view-item").each(function(){
            var img = _self.$(this).data('src');
            review_image_arr.push(img);
        });

        var width = _self.$(this).find(".f-rate-info .star-view span").width();
        var parentWidth = _self.$(this).find(".f-rate-info .star-view span").offsetParent().width();
        var review_rate = Math.round(100 * width / parentWidth);
        if(review_rate <= 4){
            review_rate = review_rate - 1;
        }
        if(review_rate == 6 || review_rate == 7){
            review_rate = review_rate - 2;
        }

        var ali_feedback_id = _self.$(this).find(".f-content .feedback-id").val();

        var feedback_obj = {
            username: username,
            ali_feedback_id: ali_feedback_id,
            user_country: user_country,
            review_text: review_text,
            review_time: review_time,
            review_rate: review_rate,
            review_image_arr: review_image_arr
        }
        feedback_arr.push(feedback_obj);

    });


    return {
        item_code: item_code,
        feedback_arr: feedback_arr
    };
};

// get feedback
Aliexpress.prototype.getFeedbackPagination = function(e) {
    var _self = this;
    var page = findParam(location.href, 'page');
    if(typeof page === 'undefined'){
        return location.href+"&page=2";
    } else if(page <= 3) {
        page = parseInt(page);
        var current_page = _self.$(".ui-pagination .ui-pagination-active").text();
        current_page = parseInt(current_page);
        if(current_page <= 3){
            var url = new URL(location.href);
            var search_params = url.searchParams;
            search_params.set('page', page+1);
            url.search = search_params.toString();
            var new_url = url.toString();
            return new_url;
        }
    }
    return null;

};

// get feedback
Aliexpress.prototype.get_item_code = function(e) {
    var _self = this;
    var item_code = _self.$("input[name=productId]").val();

    var item_url = location.href;
    var item_url_array = item_url.split('/');
    if(item_url_array.length > 4){
        var  item_url_code1 = item_url_array[4];
        var item_url_code1_arr = item_url_code1.split('.');
        item_code = item_url_code1_arr[0];
    }
    return item_code;

}


