<script>
	$("#bulk-upload-asset-form").validate({
		ignore: ":hidden:not(#location_id)",
		rules: {
			location_id: {
				required: true,
			},
			po_id: {
				required: true,
			},
			upload_asset_type_id: "required",
			asset_tag: {
				required: true,
				minlength: 2,
				unique: true,
				clientunique: true,
				unique_fields: [5, 'asset_tag']
			},
			serial_no: {
				required: true,
				unique: true,
				minlength: 2,
				serialunique: 5,
				unique_fields: [6, 'serial_no']
			},
			carrier_id: {
				required: {
					depends: function (element) {
						return jQuery.inArray(parseInt($("#upload_asset_type_id").val()), [6, 7]) != -1
					}
				}
			},
			imei: {
				unique: function (element) {
					if ($("#imei").val().length == 0) {
						return false;
					}
					return true;
				},
				required: function () {
					if ($("#asset_type_id option:selected").text() == "Mobile Device" || $("#asset_type_id option:selected").text() == "Mobile Phone Number") {
						return true;
					}
					return true;
				}
			},
			make_and_model_id: {
				required: function () {
					return true;
				},
				custome_required: true
			},
			technical_spec_id: {
				required: true,
				custome_required: true
			},
			// ticket_no: {
			// 	required: true,
			// },
			bulk_upload_asset_file: {
				extension: "csv",
				required: true,
			}
		},
		messages: {
			bulk_upload_asset_file: {
				extension: "Please upload a csv file"
			}
		},
		errorPlacement: function (error, element) {
			if (element.attr("type") == "file") {
				error.insertAfter('.errorTextfile');
			}
			else {
				error.insertAfter($(element).next($('.errorText')));
			}

		},
	});


	$("#upload_asset_type_id").change(function () {
		if ($(this).val() != '' && $(this).val() != '--Select--' && $(this).val() != '0') {
			try {
				if ($.trim($("#upload_asset_type_id option:selected").text()) == "Mobile Phone") {
					$(".upload_phone_number_div").show();
					$(".no_phone_number_div").show();
					$(".mobilephone").show();
					getCarriers($(this).val());
					$(".lease-fields").show('slow');
					$(".lblserial_and_phone").html("Serial #");
					$('#serial_no').unmask('(000) 000-0000');
				}
				else if ($.trim($("#upload_asset_type_id option:selected").text()) == "Mobile Phone Number") {
					$(".upload_phone_number_div").show();
					$(".no_phone_number_div").hide();
					$(".lblserial_and_phone").html("Mobile Phone Number");
					$('#serial_no').mask('(000) 000-0000');
					$(".mobilephone").hide();
					getCarriers($(this).val());
					$(".lease-fields").hide();
				}
				else if ($.trim($("#upload_asset_type_id option:selected").text()) == "Printer") {
					$(".lease-fields").show('slow');
				}
				else {
					$(".upload_phone_number_div").hide();
					$(".no_phone_number_div").show();
					$(".lblserial_and_phone").html("Serial #");
					$(".mobilephone").hide();
					$(".lease-fields").hide();
					$('#serial_no').unmask('(000) 000-0000');
				}

				$.ajax({
					type: "POST",
					data: { id: $(this).val(), type: $('#category').val() },
					url: "/assets-create/listHardware",
					success: function (data) {
						$('#upload_make_and_model_id').empty();
						$('#upload_make_and_model_id').append($('<option>', {
							value: '',
							text: "--Select--"
						}));
						$("#upload_make_and_model_id").select2();
						$('#upload_technical_spec_id').empty();
						$('#upload_technical_spec_id').append($('<option>', {
							value: '',
							text: "--Select--"
						}));
						$("#upload_technical_spec_id").select2();
						$.each(data, function (key, value) {
							$('#upload_make_and_model_id').append($('<option>', {
								value: value.id,
								text: value.hardware
							}));
						});
					},
					error: function (value) {
					}
				});

				$.ajax({
					type: "POST",
					data: { id: $(this).val() },
					url: "{{ route('assets-create.checkAttribute') }}",
					success: function (data) {
						$("#extra_fields").html(data);
					},
					error: function (data) {
					}
				});
			} catch (err) {

			}
		}
	});

	$("#upload_make_and_model_id").change(function () {
		if ($(this).val() != '' && $(this).val() != '--Select--' && $(this).val() != '0') {
			try {
				$.ajax({
					type: "POST",
					data: { id: $(this).val() },
					url: "/assets-create/listtechnics",
					success: function (data) {
						$('#upload_technical_spec_id').empty();
						$('#upload_technical_spec_id').append($('<option>', {
							value: '',
							text: "--Select--"
						}));
						$("#upload_technical_spec_id").select2();
						$.each(data, function (key, value) {
							$('#upload_technical_spec_id').append($('<option>', {
								value: value.id,
								text: value.details
							}));
						});
					},
					error: function (value) {

					}
				});
			} catch (err) {

			}
		}
	});

	$('#bulk-upload-asset-form').submit(function (e) {
		e.preventDefault();
		if ($('#bulk-upload-asset-form').valid()) {
			$('.alert-danger').hide();
			// get all the inputs into an array.
			var $inputs = $('#bulk-upload-asset-form :input');
			// get an associative array of just the values.
			var values = {};
			$inputs.each(function () {
				values[this.name] = $(this).val();
			});

			var formData = new FormData();
			formData.append('file', $('#bulk_upload_asset_file')[0].files[0]);
			formData.append('po_id', values['po_id']);
			formData.append('location_id', values['location_id']);
			formData.append('vendor_id', values['vendor_id']);
			formData.append('ticket_no', values['ticket_no']);
			formData.append('upload_asset_type_id', values['upload_asset_type_id']);
			formData.append('upload_make_and_model_id', values['upload_make_and_model_id']);
			formData.append('upload_technical_spec_id', values['upload_technical_spec_id']);
			formData.append('lease_start_date', values['lease_start_date']);
			formData.append('lease_end_date', values['lease_end_date']);
			formData.append('carrier_id', values['carrier_id']);
			formData.append('type', values['type']);
			formData.append('ip', values['ip']);
			formData.append('mac', values['mac']);
			formData.append('warranty_end_date', values['warranty_end_date']);
			formData.append('asset_tracking_id', values['asset_tracking_id']);
			formData.append('asset_original_value', values['asset_original_value']);
			// console.log(formData);
			$.ajax({
				type: "POST",
				url: $(this).attr('action'),
				data: formData,
				async: false,
				success: function (value) {
					var count = 0;
					if ($('#tblview tbody tr').length !== 0) {
						count = $('#tblview tbody tr').length;
					}
					count = parseInt(count) + parseInt(value.countVal)
					$('tbody').append(value.data);
					$('#tblview tbody tr').each(function(index) {
						$(this).find('td:first').text(index + 1);
					});
					$('#bulk-upload-asset-form').append(value.errors);
					$('#bulk-upload-asset-form').append(value.duplicate_errors);
					$('#asset_count').text(count);
					$('#bulk-upload-asset-form')[0].reset();
					$("select").val('').change();
					$(".select2").select2({
						placeholder: "Select"
					});
					$('.filter-field-storage-location').trigger("chosen:updated");
					if (count > 0) {
						$("#createAssetBtn").prop('disabled', false);
					} else {
						$("#createAssetBtn").prop('disabled', true);
					}
				},
				cache: false,
				contentType: false,
				processData: false
			});
		}
	});

	Array.prototype.getDuplicates = function () {
		var duplicates = {};
		for (var i = 0; i < this.length; i++) {
			if (duplicates.hasOwnProperty(this[i])) {
				duplicates[this[i]].push(i + 1);
			} else if (this.lastIndexOf(this[i]) !== i) {
				duplicates[this[i]] = [i + 1];
			}
		}

		return duplicates;
	};


	$('#createAssetBtn').click(function (e) {
		e.preventDefault();
		var html = '';
		$("#assetUploadErrorDiv").html('').hide();
		var formCheck = 0;
		var serialNoArray = $('#tblview .serial-no').map((i, e) => e.value).get();
		var assetTagArray = $('#tblview .asset-tag').map((i, e) => e.value).get();

		if (serialNoArray.length === new Set(serialNoArray).size) {
			formCheck++;
		} else {
			serialDuplicates = serialNoArray.getDuplicates();
			$.each(serialDuplicates, function (index, value) {
				html += '<p><strong>Warning!</strong> Serial No. ' + index + ' Duplicated in rows ' + value.toString() + '</p>';
			});
		}
		if (assetTagArray.length === new Set(assetTagArray).size) {
			formCheck++;
		} else {
			assetTagDuplicates = assetTagArray.getDuplicates();
			$.each(assetTagDuplicates, function (index, value) {
				html += '<p><strong>Warning!</strong> Asset Tag #. ' + index + ' Duplicated in rows ' + value.toString() + '</p>';
			});
		}
		if (formCheck == 2) {
			$('#bulk-upload-asset-table-form').submit();
		} else {
			$("#assetUploadErrorDiv").html(html).show();
			$('html, body').animate({
				scrollTop: $("#assetUploadErrorDiv").offset().top
			}, 2000);
		}

	});


	function getCarriers(id) {
		$.ajax({
			type: "POST",
			data: { id: id },
			url: "{{ route('list-carrier') }}",
			success: function (data) {
				$('#carrier_id').empty();
				$('#carrier_id').append(data);
			},
			error: function (value) {

			}
		});
	}

</script>