DS = { fn: {}, va: {} }

DS.fn.operateFormatter = function (value, row, index) {
    var operateBtns = [
        '<a class="edit operate-btn" title="Edit" data-target="#amazonItemModal" data-toggle="modal">',
        '<i class="glyphicon glyphicon-edit"></i>',
        '</a>',
        '<a class="remove operate-btn" title="Remove">',
        '<i class="glyphicon glyphicon-remove"></i>',
        '</a>'
    ];
    return operateBtns.join(' ');
}

DS.fn.getCoupangCategory = function (code) {
    DS.va.selectedCoupangCategoryCode = code;
    var attBox = $('.ds-item-attributes');
    $.get('/ds/coupang/category/' + code, {}, function (res) {
        if (res.code == 200) {
            console.log(res.data.data)
            var data = res.data.data;
            DS.va.category = data;
            var select = $('.ds-coupang-notification select');
            select.find('option:gt(0)').remove()
            var option = select.find('option').eq(0)
            $.map(data.noticeCategories, function (v, k) {
                var opt = option.clone()
                opt.text(v.noticeCategoryName)
                opt.val(k)
                select.append(opt)
            })

            // select = $('.ds-coupang-attributes select');
            // select.find('option:gt(0)').remove()
            // var option = select.find('option').eq(0)
            // $.map(data.attributes, function(v, k){
            //     var opt = option.clone()
            //     opt.text(v.noticeCategoryName)
            //     opt.val(k)
            //     select.append(opt)
            // })


            var tbody = $('.ds-coupang-attribute-names tbody');
            tbody.find('tr:gt(0)').remove();
            var trSample = tbody.find('tr').eq(0).clone();
            for (var i in DS.va.category.attributes) {
                var name = DS.va.category.attributes[i].attributeTypeName;
                var tr = trSample.clone()
                tr.find('td').eq(0).text(name)
                tbody.append(tr)
                tr.show()
            }
        }
    }, 'json')
}


DS.fn.amazonTableOperateEvents = {
    'click .edit': function (e, value, row, index) {
        var m = $('#amazonItemModal')
        var editor = tinymce.get('amazonProductDetail'); // use your own editor id here - equals the id of your textarea
        editor.setContent(row.detail == null ? row.spec : row.detail + row.spec);
        m.find('.ds-amz-title').val(row.title)
        m.find('.ds-amz-asin').val(row.asin)
        m.find('.ds-amz-price').val(row.price)
        m.find('.ds-amz-category').val(row.category)

    },
    'click .remove': function (e, value, row, index) {
        if (confirm('삭제할까요?')) {
            // $.get(location.href + '/remove/' + value, {}, function (d) {
            //     if (d.ok) {
            //         $('.ecms-table').bootstrapTable('refresh')
            //     }
            // }, 'json');
        }
    }
}

DS.fn.getCoupangCategories = function () {
    $.get('/ds/coupang/categories', {}, function (res) {
        if (res.code == 200) {
            var select = $('.ds-coupang-category-select');
            select.find('option:gt(0)').remove();
            var option = select.children().eq(0).clone();
            for (var k in res.data) {
                var opt = option.clone();
                opt.text(res.data[k].path)
                opt.attr('value', res.data[k].code)
                select.append(opt)
            }
            select.select2({ minimumInputLength: 1, width: '100%' }).on('change', function (e) {
                DS.fn.getCoupangCategory(this.value)
            });
        }
    }, 'json')
}

DS.fn.AmazonItemImageFormatter = function (value, row, index) {
    return value ? '<img src="' + value + '" width="70">' : 'No image';
}

DS.fn.AmazonItemAsinFormatter = function (value, row, index) {
    return '<a href="" class="ds-asin-format">' + row.asin + '</a>';
}

DS.fn.AmazonItemTitleFormatter = function (value, row, index) {
    return value ? '<a href="https://www.amazon.com/dp/' + row.asin + '" target="_blank">' + row.title + '</a>' : 'No Title';
}

DS.fn.AmazonItemCategoryFormatter = function (value, row, index) {
    return value ? '<a href="' + value + '" target="_blank">' + row.category + '</a>' : 'No Category';
}

DS.fn.AmazonItemVideoFormatter = function (value, row, index) {
    return value ? '<a href="' + value + '" target="_blank">' + row.video + '</a>' : 'No Video';
}

DS.fn.addItem = function (asinInput) {
    $('#show-table').bootstrapTable('showLoading')
    $.get('/ds/amazon/add_asin/' + asinInput.value, {}, function (res) {
        if (res.code == 200) {
            // alert('Saved!')                        
            asinInput.value = '';
        } else {
            alert(res.message)
        }
        asinInput.readOnly = false;
        $('#show-table').bootstrapTable('refresh')
    })
}

DS.fn.getCoupangCategoryNotification = function () {
    var notices = [];
    var noticeCategoryName = DS.va.category.noticeCategories[$('.ds-coupang-notification select').val()].noticeCategoryName
    var noticeRows = $('.ds-coupang-notification-names tbody tr:gt(0)');
    var noticeCategoryDetailNames = DS.va.category.noticeCategories[$('.ds-coupang-notification select').val()].noticeCategoryDetailNames;
    for (var i = 0; i < noticeRows.length; i++) {
        if(noticeRows.eq(i).find('td').eq(0).text() != 'A/S 책임자와 전화번호') {
            notices.push({
                "noticeCategoryName": noticeCategoryName,
                "noticeCategoryDetailName": noticeRows.eq(i).find('td').eq(0).text(),
                "content": noticeRows.eq(i).find('td:gt(0) input').val() ? noticeRows.eq(i).find('td:gt(0) input').val() : "상세정보 별도 표기"
            })
        }
        
    }
    console.log(notices)
    return notices;
}

DS.fn.getCoupangCategoryAttribute = function () {
    var attributes = [];
    var attributeRows = $('.ds-coupang-attribute-names tbody tr:gt(0)');
    for (var i = 0; i < attributeRows.length; i++) {
        attributes.push({
            "attributeTypeName": attributeRows.eq(i).find('td').eq(0).text(),
            "attributeValueName": attributeRows.eq(i).find('td:gt(0) input').val() ? attributeRows.eq(i).find('td:gt(0) input').val() : "상세정보 별도 표기"
        })
    }
    console.log(attributes)
    return attributes;
}

$(function () {
    $('.ds-send-newitem-coupang').on('click', function (e) {
        var item = $('#show-table').bootstrapTable('getSelections')[0];
        var price = Math.ceil($('.ds-amz-price').val().substring(1).trim()) * 1200;
        price.substring(-1) != '0'
        var params = {
            "displayCategoryCode": DS.va.selectedCoupangCategoryCode,
            "sellerProductName": item.title,
            "saleStartedAt": "2019-10-11T00:00:00",
            "saleEndedAt": "2099-01-01T23:59:59",
            "displayProductName": item.title,
            "brand": item.title.split(' ')[0],
            "generalProductName": $('.ds-coupang-category-selectn option:selected').text().split(' > ')[-1],
            "productGroup": $('.ds-coupang-category-selectn option:selected').text().split(' > ')[-2],
            "items": [
                {
                    "itemName": item.title,
                    "originalPrice": price,
                    "salePrice": price * 2.5,
                    "maximumBuyCount": "20",
                    "maximumBuyForPerson": "0",
                    "outboundShippingTimeDay": "7",
                    "maximumBuyForPersonPeriod": "1",
                    "unitCount": 0,
                    "adultOnly": "EVERYONE",
                    "taxType": "TAX",
                    "parallelImported": "NOT_PARALLEL_IMPORTED",
                    "overseasPurchased": "NOT_OVERSEAS_PURCHASED",
                    "pccNeeded": "false",
                    "externalVendorSku": "",
                    "barcode": "",
                    "emptyBarcode": true,
                    "emptyBarcodeReason": "COUPANG",
                    "modelNo": "",
                    "extraProperties": {},
                    "certifications": [
                        {
                            "certificationType": "NOT_REQUIRED",
                            "certificationCode": ""
                        }
                    ],
                    "searchTags": [],
                    "images": [
                        // {
                        //     "imageOrder": 0,
                        //     "imageType": "REPRESENTATION",
                        //     "cdnPath": "vendor_inventory/images/2018/11/29/14/5/0bd272e6-94f6-4759-9c4a-169c14c30f71.jpg",
                        //     "vendorPath": "0bd272e6-94f6-4759-9c4a-169c14c30f71.jpg"
                        // }
                        {
                            "imageOrder": 0,
                            "imageType": "REPRESENTATION",
                            "vendorPath": "http://image11.coupangcdn.com/image/product/image/vendoritem/2017/02/21/3000169918/34b79649-d625-4f49-a260-b78bf7a573a8.jpg"
                        },
                        // {
                        //     "imageOrder": 1,
                        //     "imageType": "DETAIL",
                        //     "vendorPath": "http://image11.coupangcdn.com/image/product/image/vendoritem/2017/02/21/3000169918/34b79649-d625-4f49-a260-b78bf7a573a8.jpg"
                        // },
                        // {
                        //     "imageOrder": 2,
                        //     "imageType": "DETAIL",
                        //     "vendorPath": "http://image11.coupangcdn.com/image/product/image/vendoritem/2018/06/28/3000169918/5716aa61-70bd-47cd-8f3d-f3d49e7f496d.jpg"
                        // }
                    ],
                    "notices": DS.fn.getCoupangCategoryNotification(),
                    "attributes": DS.fn.getCoupangCategoryAttribute(),
                    "contents": [
                        {
                            "contentsType": "TEXT",
                            "contentDetails": [
                                {
                                    "content": $(tinyMCE.activeEditor.getContent()).children().html(),
                                    "detailType": "TEXT"
                                }
                            ]
                        }
                    ],
                    "offerCondition": "NEW",
                    "offerDescription": ""
                }
            ],
            "manufacture": item.title.split(' ')[0]
        }
        $.post('/ds/coupang/sendnew', params, function (res) {
            if (res.code == 200) {
                if (res.data.code == 'ERROR') {
                    alert(res.data.message)
                }else {
                    alert("쿠팡 상품전송 등록완료")
                }
            }
        }, 'json')
    })
    $('.ds-coupang-notification select').on('change', function (e) {
        var tbody = $('.ds-coupang-notification-names tbody');
        tbody.find('tr:gt(0)').remove();
        var trSample = tbody.find('tr').eq(0).clone();
        for (var i in DS.va.category.noticeCategories[this.value].noticeCategoryDetailNames) {
            var name = DS.va.category.noticeCategories[this.value].noticeCategoryDetailNames[i].noticeCategoryDetailName;
            var tr = trSample.clone()
            tr.find('td').eq(0).text(name)
            tbody.append(tr)
            tr.show()
        }

    })
    DS.fn.getCoupangCategories();
    $('.input-daterange input').each(function () {
        $(this).datepicker({ format: 'yyyy-mm-dd' });
    });

    $('.ds-input-asin').on('keydown', function (e) {
        if (e.keyCode == 13) {
            this.readOnly = true;
            DS.fn.addItem(this)
        }
    })

    $('.ds-search-btn').on('click', function (e) {
        var options = SHOW.node('#show-table').bootstrapTable('getOptions');
        options.queryParams = function (a) {
            var params = {
                'keyword': SHOW.node('input[name=keyword]').val(),
                'app': $('.app-select').val(),
                'category_type': $('.category-type-select').val()
            }
            if (SHOW.node('.video-list-app-select').length) {
                if (SHOW.node('.video-list-app-select').val()) {
                    params.appid = SHOW.node('.video-list-app-select').val();
                }
            }
            if (SHOW.node('.video-list-category-select').length) {
                if (SHOW.node('.video-list-category-select').last().val()) {
                    params.category = SHOW.node('.video-list-category-select').last().val();
                }
            }
            return $.extend(a, params)
        }
        SHOW.node('#show-table').bootstrapTable('destroy').bootstrapTable(options)
    })
})