var option = {
    init: function() {
        var oThis = this;
        $('.optionProductList ul').children('li').find('.optionDelete').on('click', function() {
            oThis.deleteOption($(this));
        });
    },

    getItemList: function($subCategory) {
        var oThis = this,
        optionList = null,
        $optionContainer = $(".optionProductList").children('ul').html('');

        $.ajax({
            url: '/simulation/custom_admin/option/option_list/',
            type: 'POST',
            data: {
                'sub_category': $subCategory.data('category') 
            },
            async: false,
            success: function (context) {
                optionList = context['options'];
                $.each(optionList, function() {
                    $optionContainer.append(
                        $("<li>\
                            <div class='optionDelete'><img src='/static/base/image/closeIcon.png'></div>\
                            <div class='optionOptionTitle'>" + this.name + "</div>\
                            <div class='optionOptionPrice'>" + comma(this.price) + " 원</div>\
                            <img src=" + this.thumb + ">\
                        </li>")
                        .data('option', this.id)
                    );
                });

                oThis.init();
            }
        });
    },

    deleteOption: function($target) {
        var $optionContainer = $(".optionProductList ul"),
            $option = $target.closest('li'),
            optionId = $option.data('option');

        $.confirm({
            title: '알',
            content: '정말 삭제하시겠습니까?',
            useBootstrap: false,
            buttons: {
                yes: function () {
                    $.ajax({
                        url: '/simulation/custom_admin/option/delete/',
                        type: 'POST',
                        data: {
                          'option': optionId
                        },
                        async: false,
                        success: function (context) {
                            var $target = $optionContainer.children('li').filter(function() { 
                                return $(this).data("option") === context.id;
                            });
                            $optionContainer.find($target).remove();              
                        }
                    });
                },
                no: function () {
                }
            }
        });
    }
};
option.init();

var uploadOption = {
    init: function() {
        var oThis = this,
            $target = null;

        $('.optionImg input[type=file]').on('change', function() {
            $target = $(this).closest('.optionImg').find('.upload-img');
            oThis.readImageUrl($(this), $target);
        });

        $('.inp-file-thumb').on('change', function() {
            $('.option-upload-info').hide();
            
            if ($('.optionThumbnail').find('.upload-img').length === 0) {
                $('.optionThumbnail').append("<img class='upload-img'/>");
            }
            
            $target = $('.optionThumbnail').find('.upload-img');
            oThis.readImageUrl($(this), $target);
        });

        $('.optionUpload').on('click', function(e) {
            e.preventDefault();
            var returnVal = oThis.validUploadData();
            if (!returnVal) {
                return false;
            }
            oThis.upload();
        });

    },

    readImageUrl: function($input, $target) {
        if ($input[0].files && $input[0].files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $target.attr('src', e.target.result);
            }
            reader.readAsDataURL($input[0].files[0]);
        }
    },

    validUploadData: function() {
        var checkItems = {
            'optionName': '이름',
            'optionPrice': '가격'
        },
        returnValue = true,
        regInt = /^[0-9]+$/,
        price = $('input[name=optionPrice]').val();

        if ($('.option-category-sub').children('li.selected').data('category') === undefined) {
            $.alert({title: '알림', content: "서브 카테고리를 선택해주세요.", useBootstrap: false});

            returnValue = false;
            return false;
        }

        $.each(checkItems, function(key, value) {
            if ($('input[name='+key+']')[0].value === '') {
                $('input[name='+key+']').focus();
                $.alert({title: '알림', content: value + "은 필수 입력 사항입니다.", useBootstrap: false});
                returnValue = false;
                return false;
            }
        });
        if (!returnValue) return returnValue;

        if (!regInt.test(price)) {
            $.alert({title: '알림', content: "유효하지 않은 숫자 입니다.", useBootstrap: false});
            $('input[name=optionPrice]').focus();
            returnValue = false;
            return false;
        }

        if ($('.inp-file-thumb')[0].files[0] === undefined || $("input[name='file-image-front']")[0].files[0] === undefined) {
            $.alert({title: '알림', content: "썸네일, 앞면 이미지는 필수 사항입니다.", useBootstrap: false});
            returnValue = false;
            return false;
        }

        // if ($("input[name='file-image-front']")[0].files[0] === undefined && $("input[name='file-image-back']")[0].files[0] === undefined) {
        //     alert("앞, 뒤 이미지를 1개 이상 업로드 해주세요.");
        //     returnValue = false;
        //     return false;
        // }

        return returnValue;
    },

    upload: function() {
        var oThis = this,
            formData = new FormData($("#uploadForm")[0]),
            $optionContainer = $('.optionProductList ul'),
            newOption = null;
        formData.append('sub_category', $('.option-category-sub').children('li.selected').data('category'));

        $.ajax({
            url: '/simulation/custom_admin/option/add/',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function (context) {
                $.alert({title: '알림', content: "업로드가 완료되었습니다.", useBootstrap: false});
                oThis.resetUploadForm();
    
                newOption = context;
                $optionContainer.append(
                    $("<li>\
                        <div class='optionDelete'><img src='/static/base/image/closeIcon.png'></div>\
                        <div class='optionOptionTitle'>" + newOption.name + "</div>\
                        <div class='optionOptionPrice'>" + comma(newOption.price) + "</div>\
                        <img src=" + newOption.thumb + ">\
                    </li>")
                    .data("option", newOption.id)
                );
                option.init();
            }
        });
    },

    resetUploadForm: function() {
        $('#uploadForm')[0].reset();
        $('.option-upload-info').show();
        $('.upload-img').attr('src', '');
    }

};
uploadOption.init();

var category = {
    init: function() {
        var oThis = this;
        $(".add-main").on('click', function(e) {
            e.stopImmediatePropagation();
            oThis.addMainCategory($(this).closest('.categorySelector'));
        });
        $(".add-sub").on('click', function(e) {
            e.stopImmediatePropagation();
            oThis.addSubCategory($(this).closest('.categorySelector'));
        });
        $(".delete-main").on('click', function(e) {
            e.stopImmediatePropagation();
            var url = '/simulation/custom_admin/option/delete_main_category/',
                $selectedCategory = $(".option-category-main");

            oThis.deleteCategory(url, $selectedCategory);
        });
        $(".delete-sub").on('click', function(e) {
            e.stopImmediatePropagation();
            var url = '/simulation/custom_admin/option/delete_sub_category/',
                $selectedCategory = $(".option-category-sub");

            oThis.deleteCategory(url, $selectedCategory);
        });
        $(".option-category-main").children('li').on('click', function(e) {
            e.stopImmediatePropagation();
            oThis.selectMainCategory($(this));
        });
        $(".option-category-sub").children('li').on('click', function(e) {
            oThis.selectSubCategory($(this));
        });
    },

    addMainCategory: function($selector) {
        var oThis = this,
            $input = $selector.find('.categoryName')[0],
            newMainCategory = null;

        if ($input.value === '') {
            $input.focus();
            $.alert({title: '알림', content: "필수 입력 사항입니다.", useBootstrap: false});
            return false;
        }

        $.ajax({
            url: '/simulation/custom_admin/option/add_main_category/',
            type: 'POST',
            data: {
              'new_name': $input.value
            },
            async: false,
            success: function (context) {
                newMainCategory = context;
                
                $('.option-category-main').append(
                    $('<li>' + newMainCategory.name + '</li>')
                    .data('category', newMainCategory.id)
                );
                $input.value = "";
                oThis.init();
            }
        });
    },

    addSubCategory: function($selector) {
        var oThis = this,
            $inputName = $selector.find('.categoryName')[0],
            $inputPrice = $selector.find('.categoryPrice')[0],
            selectedMainCategory = $('.option-category-main').children('li.selected').data('category'),
            newSubCategory = null,
            regInt = /^[0-9]+$/;

        if ($inputName.value === '') {
            $inputName.focus();
            $.alert({title: '알림', content: "필수 입력 사항입니다.", useBootstrap: false});

            return false;
        }
        if (!regInt.test($inputPrice.value) || ($inputPrice.value > 100)) {
            $inputPrice.focus();
            $.alert({title: '알림', content: "0 이상 100 이하의 정수로 입력해주세요.", useBootstrap: false});
            return false;
        }

        $.ajax({
            url: '/simulation/custom_admin/option/add_sub_category/',
            type: 'POST',
            data: {
                'main_category': selectedMainCategory,
                'new_name': $inputName.value,
                'discount_rate': $inputPrice.value
            },
            async: false,
            success: function (context) {
                newSubCategory = context;
                
                $('.option-category-sub').append(
                    $('<li>' + newSubCategory.name + " &nbsp;&nbsp;[ 최대할인률 : &nbsp;" + newSubCategory.max_discount_rate + "%&nbsp;] " + '</li>')
                    .data('category', newSubCategory.id)
                );
                $inputName.value = "";
                $inputPrice.value = "";
                oThis.init();
            }
        });
    },

    deleteCategory: function(url, $selector) {
        var oThis = this,
            selectedCategory = $selector.children('li.selected').data('category');

        $.confirm({
            title: '알림',
            content: '정말 삭제하시겠습니까?',
            useBootstrap: false,
            buttons: {
                yes: function () {
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: {
                          'deleteCategory': selectedCategory
                        },
                        async: false,
                        success: function (context) {
                            var $target = $selector.children('li').filter(function() { 
                                return $(this).data("category") === context.id;
                            });

                            var prevIndex = $target.index()-1;
                            $selector.find($target).remove();

                            if ($selector.selector === ".option-category-main") {
                                oThis.selectMainCategoryIndex(prevIndex);
                            } else if ($selector.selector === ".option-category-sub") {
                                oThis.selectSubCategoryIndex(prevIndex);
                            }
                            
                        }
                    });
                },
                no: function () {
                }
            }
        });        
    },
 
    selectMainCategory: function($category) {
        var oThis = this,
            subCategories = null,
            $subCategory = $(".option-category-sub").html('');

        $category.addClass('selected').siblings().removeClass('selected');

        $.ajax({
            url: '/simulation/custom_admin/option/sub_category_list/',
            type: 'POST',
            data: {
              'main_category': $category.data('category') 
            },
            async: false,
            success: function (context) {
                subCategories = context['categories'];

                $.each(subCategories, function() {
                    $subCategory.append(
                        $("<li>" + this.name + " &nbsp;&nbsp;[ 최대할인률 : &nbsp;" + this.max_discount_rate + "%&nbsp;] " + "</li>")
                        .data('category', this.id)
                    );
                });
                oThis.init();
                oThis.selectSubCategoryIndex(0);
            }
        });
    },

    selectMainCategoryIndex: function(index) {
        var $mainCategory = $('.option-category-main').find('li').eq(index);        
        this.selectMainCategory($mainCategory);
    },

    selectSubCategory: function($subCategory) {
        $subCategory.addClass('selected').siblings().removeClass('selected');
        uploadOption.resetUploadForm();
        option.getItemList($subCategory);
    },

    selectSubCategoryIndex: function(index) {
        var $subCategory = $('.option-category-sub').find('li').eq(index);
        this.selectSubCategory($subCategory);
    }
};
category.init();

function comma (str) {
    str = String(str);
    return str.replace(/(\d)(?=(?:\d{3})+(?!\d))/g, '$1,');
}
