var tableTotal = {
	getTotal: function($table, inventory) {
		var $totalRow = $table.find('.total'),
			$rowList = $table.find('.row-size'),
			rowTotal = 0;

		for (var i = 8; i > 0; i--) {
			$rowList.each(function() {
				var $row = $(this);
				if (inventory && i > 1) {
					rowTotal += Number($row.find('td:nth-last-child('+i+')').children('input').val());
				} else {
					rowTotal += Number($row.find('td:nth-last-child('+i+')').text());
				}		
			})
			$totalRow.find('td:nth-last-child('+i+')').text(rowTotal);
			rowTotal = 0;
		}	
	}
};
tableTotal.getTotal($('table:eq(0)'));
tableTotal.getTotal($('table:eq(2)'), true);
tableTotal.getTotal($('table:eq(3)'));

var inventory = {
	$table: $('.table-inventory'),
	initEvent: function() {
		var oThis = this;
		$(".inp-stock").attr('readonly', true);

		$(".sizeSetting").on('click', function(e) {
			e.stopPropagation();
			oThis.initEdit();
		});

		$(".sizeSave").on('click', function(e) {
			e.stopPropagation();
			oThis.initSubmit();
			oThis.submit();
		});

		$(".inp-stock").on('keyup', function() {
			oThis.getTotalByProduct($(this));
			oThis.getTotalBySize($(this));
			oThis.getTotal();
		});

	},
	initEdit: function() {
		$(".inp-stock").attr('readonly', false);
		$(".sizeSetting").addClass('hide');
		$(".sizeSave").removeClass('hide');

		this.$table.find(".row-size").eq(0).find('.inp-stock').eq(0).focus();
	},
	initSubmit: function() {
		$(".inp-stock").attr('readonly', true);
		$(".sizeSetting").removeClass('hide');
		$(".sizeSave").addClass('hide');
	},
	submit: function() {
		var arrInventory = this.dataToDict(this.$table.find('.row-size'));
		var oThis = this;

		$.ajax({
            url: '/measurement/stats/inventory/submit/',
            type: 'POST',
            cache: false,
            data: {
                'order_id': order_id,
                'inventory': JSON.stringify(arrInventory)
            },
            async: false,
            success: function (response) {
          		oThis.requiredStatus();
            }
        });
	},
	dataToDict: function($selector) {
		return $selector.map(function(i) {
			var row = {};
			var $target = $(this);

			$target.find($('input')).each(function (i) {
				var inputName = $(this)[0].name;
				row['product'] = $target.data('product');
				row['gender'] = $target.data('gender');
				row['size' + inputName.split("-")[2]] =  Number($(this)[0].value);
			});
			return row;
		}).get();
	},
	getTotalByProduct: function($input) {
		var $targetRow = $input.closest('.row-size'),
			$inpInventory = $targetRow.find('.inp-stock'),
			$inpTotal = $targetRow.find('td').last(),
			total = 0;

		$inpInventory.each(function() {
			total += Number($(this).val());
		});
		$inpTotal.text(total);
	},
	getTotalBySize: function($input) {
		var $targetRow = $input.closest('.row-size'),
			$inpInventory = $targetRow.find('.inp-stock'),
			total = 0;
			columnIdx = $inpInventory.index($input),
			$inpTotal = this.$table.find('.total').find('td').eq(columnIdx+6);

		this.$table.find('.row-size').each(function() {
			total += Number($(this).find('.inp-stock').eq(columnIdx).val());
		});
		$inpTotal.text(total);
	},
	getTotal: function() {
		var $target = this.$table.find('.total').children('td:gt(5)').not(':last-child'),
			$total = this.$table.find('.total').children('td').last();
			total = 0;
		
		$target.each(function() {
			total += Number($(this).text());
		});
		$total.text(total);
	},
	requiredStatus: function() {
		var oThis = this,
			$sizeRowList = $("table:eq(0)").find('.row-size'),
			$inventoryRowList = this.$table.find('.row-size'),
			$requiredRowList = $("table:eq(3)").find('.row-size'),
			$sizeRow = null,
			$inventoryRow = null,
			$requiredRow = null,
			sizeVal = 0,
			inventoryVal = 0,
			i = 0;
		
		$sizeRowList.each(function(idx) {
			$size = $(this);
			$inventory = $inventoryRowList.eq(idx);
			$requiredRow = $requiredRowList.eq(idx);

			for (var i = 8; i > 0; i--) {
				sizeVal = Number(oThis.getRowChild($size, i).text());
				inventoryVal = Number(oThis.getRowChild($inventory, i).find('input').val());;
				if (i === 1) {
					inventoryVal = Number(oThis.getRowChild($inventory, i).text());
				}
				requiredVal = sizeVal - inventoryVal;
				oThis.getRowChild($requiredRow, i).text(requiredVal);
			}		
		});
		tableTotal.getTotal($('table:eq(3)'));
	},
	getRowChild: function(row, idx) {
		return row.find('td:nth-last-child('+idx+')');
	}
};
inventory.initEvent();


var pdf = {
	$elements: $('h3, table, .SizeRatio'),
	count: 0,
	docDefinition : {
        content: [],
        styles: {
            header: {
                fontSize: 18,
                bold: true,
                margin: [20,10]
            }
        },
        defaultStyle: {
            font: 'font'
        }
    },
	initEvent: function() {
		var oThis = this;
		$('.pdfBtn').on('click', function() {
			for (var i = oThis.$elements.length - 1; i >= 0; i--) {
		        oThis.makeCanvas(i); 
		    } 
		});
	},
	makeCanvas: function(idx) {
		var oThis = this;
		this.count += 1;

        html2canvas(oThis.$elements[idx], {
            onrendered: function(canvas) {
                var data = canvas.toDataURL();
                oThis.docDefinition.content[idx] = {
                    image:data, 
                    width:520,
                    margin: [0,5],
                    pageBreak: (function() {
                    	var temp = '';
                    	if (idx !== 0 && idx % 4 == 0) {
                    		temp = 'before';
                    	} else {
                    		temp = '';
                    	}
                    	return temp;
                    })()
                };
                oThis.count -= 1;
                if (oThis.count === 0) {
                    pdfMake.fonts = {
                        font: {
                            normal: 'malgun.ttf',
                            bold: 'malgunbd.ttf'
                        }
                    };
                    pdfMake.createPdf(oThis.docDefinition).download('사이즈_합계.pdf');
                }
            }
        })
	}
};
pdf.initEvent();



$('table').each(function() {
	$(this).find('.seasonGroup').closest('tr').not(':eq(0)').addClass('divide-line-season');
});




