$(function () {
	$(".clearjs").on("click", function () {
		return confirm('确定要清空购物车吗？');
	})

	// 加和减数量
	$('.minus').click(function () {
		var quantity = $(this).parents('tr').find('.quantity')
		var count = Number(quantity.val())
		if (count > 1) {
			quantity.val(count - 1)
		}else{
			layer.msg('数量不能少于1',{time:1000})
		}
		$(this).parents('tr').find('.quantity').change()
	})
	$('.add').click(function () {
		var quantity = $(this).parents('tr').find('.quantity')
		var count = Number(quantity.val())
		var inventory = Number($(this).parents('tr').find('.inventory').html())
		if (count < inventory) {
			quantity.val(count + 1)
		} else {	
			layer.msg('超出库存',{time:1000})
		}
		$(this).parents('tr').find('.quantity').change()
	})


	$('.quantity').change(function () {
		var inventory = Number($(this).parents('tr').find('.inventory').html())
		var quantity = Number($(this).val())
		if (quantity < 1) {
			$(this).val(1)
		}
		if (quantity > inventory) {
			layer.msg('超出最大库存量',{time:1000})
			$(this).val(inventory)
		}

		var set_quantity = $(this)
		var formData = new FormData();
		formData.append("action", 'cart_edit');
		formData.append("quantity", Number($(this).val()));
		formData.append("id", Number($(this).attr('cart-id')));
		$.ajax({
			scriptCharset: 'UTF-8',
			type: 'post',
			url: '',
			data: formData,
			cache: false,
			processData: false,
			contentType: false,
			dataType: "json",
			success: function (data) {
				if (data.status == 0) {
					layer.msg(data.msg,{time:1000})
					if (data.inventory) {
						set_quantity.val(data.inventory)
					}
				}
			}
		})
	})
	// 提交订单
	$('#submit').click(function () {
		console.log('提交')
		$('#carts').submit()
	})
	//数量发生改变
	$('body').on('change','.quantity',function(){
		let price = $(this).parents('tr').find('.cart-price').text()
		let count =  ($(this).val()*price).toFixed(1)
		console.log(count);
		$(this).parents('tr').find('.subtotal').text(count)
		count_price()
	})
	// 计算费用
	$('.select-checkbox').click(function () {
		count_price()
	})
	//删除
	$('.btn-delete').click(function () {
		formdata = {"action": 'cart_del', 'id': Number($(this).attr('cart-id'))}
		var this_tr = $(this).parents('tr')
		$.post('', formdata, function (data) {
			if(data.status == 0){
				this_tr.remove()
			}else{
				layer.msg(data.msg,{time:1000})
			}
		}, 'json')
	})
})
// 计算费用
let count_price =() =>{
	var count = 0
	var flag = 0
	$('.select-product').each(function () {
		if($(this).prop('checked')){
			count += Number($(this).parents('tr').find('.subtotal').html())
			flag = 1
		}
	})
	$("#count").text(count)
	if(flag == 1){
		$('#submit').removeAttr('disabled')
	}else{
		$('#submit').attr('disabled', 'disabled')
	}
}
