var apiProdListService = (function () {
    function appendProdToRootDiv($root, prod) {
        var imageUrl = prod.imgUrl ? prod.imgUrl : "";
        var companyName = prod.companyName ? prod.companyName : "";
        var productName = prod.productName ? prod.productName : "";
        var productVolume = prod.productVolume ? prod.productVolume : "-";
        var productPrice = prod.productPrice ? prod.productPrice : 0;
        var dtlHref = "/clfd/prod/dtl.do?cmsCode=" + prod.cmsCode
            + "&companyCode=" + prod.companyCode
            + "&productCode=" + prod.productCode;

        var $card = $("<div class=\"main-inner__rec\"></div>");
        var $anchor = $("<a href='"+dtlHref+"' target='_blank'></a>");
        var $divImg = $("<div class=\"main-inner__divImg\"></div>");
        var $img = $("<img src='"+imageUrl+"' alt=\"\">");
        var $prodDiv = $("<div class=\"main-inner__rec_list\"></div>");
        var $corpNm = $("<div class=\"main-text__co\">"+companyName+"</div>");
        var $prodNm = $("<div class=\"main-text__pr\">"+productName+"</div>");
        //var $prodDtlDiv = $("<div class=\"main-inner__rec_list__ac\"></div>");
        //var $price = $("<div class=\"main-text__am\">" + clfdUtils.formattingDot(productPrice) +"</div>");
        //var $capacity = $("<div class=\"main-text__ca\"> / "+productVolume + "ml</div>");

        //$prodDtlDiv.append($price);
        //$prodDtlDiv.append($capacity);
        $prodDiv.append($corpNm);
        $prodDiv.append($prodNm);
        //$prodDiv.append($prodDtlDiv);
        $divImg.append($img);
        $anchor.append($divImg);
        $anchor.append($prodDiv);
        $card.append($anchor);
        $root.append($card);
    }
    var prodList = [];
    return {
        drawBestProdList: function ($root, prodTyArr) {
            clfdCommonService.prodListApiRequest(
                {
                    scb: function (res) {
                        if (!res.prodList) return;
                        for (var i = 0; i<res.prodList.length; i++) {
                            appendProdToRootDiv($root, res.prodList[i]);
                        }
                    },
                    ecb: function (res) {
                        console.log(res);
                    }
                },
                {
                    pageNo: 1,
                    offset: 4,
                    keyword: null,
                    prodTyArray: prodTyArr,
                    skTy: null,
                    sort: 'may',
                }
            );
        },
        appendToProdList: function (_prodList) {
            preprocess(_prodList);
            prodList = _.concat(prodList, _prodList);

            function preprocess(_prodList) {
                _.forEach(_prodList, function (prod) {
                    prod.productLikeCnt = _.isNumber(prod.productLikeCnt) ? prod.productLikeCnt : 0;
                    prod.productLikeMe = prod.productLikeMe ? prod.productLikeMe : 'N';
                    prod.likeRootId = 'like_' + prod.cmsCode + prod.companyCode + prod.productCode;
                })
            }
        },
        findProdListByProdInfo: function (cmsCode, companyCode, productCode) {
            return _.filter(prodList, {'cmsCode': cmsCode, 'companyCode': companyCode, 'productCode': productCode})[0];
        },
        toggleLike: function (prod) {
            if (prod.productLikeMe == 'Y') {
                prod.productLikeMe = 'N';
            } else {
                prod.productLikeMe = 'Y';
            }

            if (prod.productLikeMe == 'Y') {
                prod.productLikeCnt++;
            } else {
                prod.productLikeCnt--;
            }
        },
    }
}());

prodListService.apiModule = function () {
    var that = this;
    var prodListSearchOption = {
        pageNo: 1,
        offset: 16,
        keyword: null,
        prodTyArray: null,
        skTyCus: null,
        skTy: null,
        sort: 'new',
    }

    var sortToken = "";
    var mSideBar = "";
    var listLength = 0;
    var isExistNextPaging = true;
    return {
        prodListPageRequest: function () {
            location.href = "/clfd/prod/list.do" +
                "?searchText=" + prodListSearchOption.keyword
                + getArrayQueryString(prodListSearchOption.prodTyArray, 'prodTyArray')
                + (prodListSearchOption.skTyCus === null ? "" : "&skTyCus=" + prodListSearchOption.skTyCus)
                + (prodListSearchOption.skTy === null ? "" : "&skTy=" + prodListSearchOption.skTy)
                + (sortToken === "" ? "" : "&sortToken=" + sortToken)
                + (mSideBar === "" ? "" : "&mSideBar=" + mSideBar);

            function getArrayQueryString(targetArray, queryName) {
                if (!targetArray || targetArray.length < 1) {
                    return "";
                }
                var arrayQueryString = "";
                for (var i = 0; i < targetArray.length; i++) {
                    var prodTy = targetArray[i];
                    arrayQueryString += "&" + queryName + "=" + prodTy;
                }
                return arrayQueryString;
            }
        },
        prodListApiRequest: function (option) {
            var module = this;
            console.log('prodListSearchOption', prodListSearchOption);
            $.ajax({
                url: "/clfd/api/prod/list.json?" + $.now(),
                data: prodListSearchOption,
                type: "GET",
                success: function (res) {
                    if (res.result === "success") {
                        that.appendToProdList(res.prodList);
                        console.log(res.prodList);
                        if (res.prodList == null) {
                            listLength = 0;
                        } else {
                            listLength = res.prodList.length;
                            if (res.prodList.length < 12) {
                                isExistNextPaging = false;
                            } else {
                                module.plusPageNo();
                            }
                        }
                        if (option && option.scb) {
                            option.scb(res);
                        }
                    } else {
                        if (option && option.ecb) {
                            option.ecb(res);
                        }
                    }
                }
            });
        },
        isProdListZero: function () {
            return listLength === 0;
        },
        isExistNextPaging: function () {
            return isExistNextPaging;
        },
        setSearchText: function (searchText) {
            prodListSearchOption.keyword = searchText;
        },
        setProdTyArray: function (prodTyArray) {
            prodListSearchOption.prodTyArray = prodTyArray;
        },
        setSkTyCus: function (skTyCus) {
            prodListSearchOption.skTyCus = skTyCus;
        },
        setSkTy: function (skTy) {
            prodListSearchOption.skTy = skTy;
        },
        setSortToken: function (token) {
            sortToken = token;
            prodListSearchOption.sort = token;
        },
        setMsideBarToOn: function () {
            let height = Math.max($('.product__container').height(), $('.sidebar__menu').height());
            $('.sidebar__menu').height(height +'px');
            $('.m__filterbtn_black').height(height +'px');
            $('.sidebar__menu').addClass("active");
            $('.m__filterbtn_black').addClass("active");
            mSideBar = "on";
        },
        setMsideBarToOff: function () {
            $('.sidebar__menu').removeClass("active");
            $('.m__filterbtn_black').removeClass("active");
            mSideBar = "";
        },
        plusPageNo: function () {
            prodListSearchOption.pageNo++;
        }
    }
};

prodListService.viewModule = function () {
    return {
        appendProdList: function ($prodRootDiv, prodList) {
            if (!$prodRootDiv || !prodList || prodList.length === 0) {
                return;
            }
            for (var i = 0; i < prodList.length; i++) {
                var prod = prodList[i];
                var $card = this.getProdCard(prod);
                $prodRootDiv.append($card);
            }
        },
        getProdCard: function (prod) {
            var imageUrl = prod.imgUrl ? prod.imgUrl : "";
            var companyName = prod.companyName ? prod.companyName : "";
            var productName = prod.productName ? prod.productName : "";
            var productVolume = prod.productVolume ? prod.productVolume : "-";
            var productPrice = prod.productPrice ? prod.productPrice : 0;

            var dtlHref = "/clfd/prod/dtl.do?cmsCode=" + prod.cmsCode
                + "&companyCode=" + prod.companyCode
                + "&productCode=" + prod.productCode;

            var $cardAnchor = $("<a href='" + dtlHref + "' target='_blank' style='width: 100%; text-align: center;'></a>");
            var $card = $("<div class='cardbarIn__item'></div>");
            var $divImg = $("<div class='cardbarIn__divImg'></div>")
            var $img = $("<img src='" + imageUrl + "' alt=''>");
            var $cardContents = $("<div class='card__contents' style='text-align: left'></div>");
            var $cText = $("<a class='c__text'>" + companyName + "</a><br>");
            var $bText = $("<a class='b__text'>" + productName + "</a>");
            var $likeRoot = $("<div style='padding: 8px 12px; float: left;' id='" + prod.likeRootId + "' class='like__icon' " +
                "data-prodId='" + prod.prodId + "' data-cmsCode='" + prod.cmsCode + "' data-companyCode='" + prod.companyCode + "' data-productCode='" + prod.productCode + "'></div><br>");
            this.drawLikeView($likeRoot, prod);
            //var $wText = $("<a class='w__text' href='" + dtlHref +"'>"+productVolume + "ml / " + clfdUtils.formattingDot(productPrice) +"원</a>");

            $divImg.append($img);
            $cardAnchor.append($divImg);
            $cardContents.append($cText);
            $cardContents.append($bText);
            //$cardContents.append($wText);
            $cardAnchor.append($cardContents);
            $cardAnchor.append($likeRoot);
            $card.append($cardAnchor);
            return $card;
        },
        appendProdListZeroAlert: function ($prodCardRoot) {
            var $card = $("<div class='cardbarIn__item' style='visibility: hidden'></div>");
            var $zeroAlert = $("<p>조건에 맞는 화장품이 없습니다.</p>");
            $prodCardRoot.append($zeroAlert);
            $prodCardRoot.append($card);
        },
        prodListMoreBtnHidden: function ($moreBtn) {
            $moreBtn.css('display', 'none');
        },
        prodListMoreBtnShow: function ($moreBtn) {
            $moreBtn.css('display', 'inline-block');
        },
        drawLikeView: function ($likeRoot, prod) {
            $likeRoot.empty();
            if (prod.productLikeMe == 'Y') {
                $likeButton = $('<i class="fas fa-heart" style="font-size: 14px; cursor: pointer; color: red">' + prod.productLikeCnt + '</i>');
            } else {
                $likeButton = $('<i class="fas fa-heart" style="font-size: 14px; cursor: pointer; color: gray">' + prod.productLikeCnt + '</i>');
            }
            $likeRoot.append($likeButton)
        }
    }
}
