USE `vn`;
DROP procedure IF EXISTS `ticketCreateWithoutZone`;

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone`(
     vClientId INT
    ,vShipped DATE
    ,vWarehouseFk INT
    ,vCompanyFk INT
    ,vAddressFk INT
    ,vAgencyModeFk INT
    ,vRouteFk INT
    ,vlanded DATE
    ,vUserId INT
    ,OUT vNewTicket INT)
BEGIN

	DECLARE vZoneFk INT;
    
	IF vClientId IS NULL THEN  
		CALL util.throw ('CLIENT_NOT_ESPECIFIED'); 
	END IF;

    IF NOT vAddressFk OR vAddressFk IS NULL THEN
        SELECT id INTO vAddressFk 
            FROM address
            WHERE clientFk = vClientId AND isDefaultAddress;
    END IF;
    
    IF NOT vAgencyModeFk OR vAgencyModeFk IS NULL THEN
        SELECT agencyModeFk INTO vAgencyModeFk 
            FROM address
            WHERE clientFk = vClientId AND isDefaultAddress;
    END IF;

	CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk);
    
	SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped
		WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1;
	
	INSERT INTO vn2008.Tickets (
			Id_Cliente,
			Fecha,
			Id_Consigna,
			Id_Agencia,
			Alias,
			warehouse_id,
			Id_Ruta,
			empresa_id,
			landing,
            zoneFk
		)
		SELECT
					vClientId,
					vShipped,
					a.id,
					IF(vAgencyModeFk, vAgencyModeFk, a.agencyModeFk),
					a.nickname,
					vWarehouseFk,
					IF(vRouteFk,vRouteFk,NULL),
					vCompanyFk,
					vlanded,
                    vZoneFk
			FROM address a
				JOIN agencyMode am ON am.id = a.agencyModeFk
			WHERE a.id = vAddressFk;

	SET vNewTicket = LAST_INSERT_ID();

	INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
		SELECT vNewTicket, ao.observationTypeFk, ao.description
			FROM addressObservation ao
				JOIN address a ON a.id = ao.addressFk
			WHERE a.id = vAddressFk;

	-- CALL logAddWithUser(vNewTicket, vUserId, 'insert', 'ticket', CONCAT('Ha creado el ticket', ' ', vNewTicket));
    INSERT INTO vn.ticketLog
		SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket);

	IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN
		INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador)
			SELECT id, vNewTicket, getWorker()
				FROM state
				WHERE `code` = 'DELIVERED';
	END IF;
END$$

DELIMITER ;

