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

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`(
     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 vAgencyModeFk IS NOT NULL THEN
		
		CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk);
    
		SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped
			WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1;
		
		IF vZoneFk IS NULL OR vZoneFk = 0 THEN
			CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); 
		END IF;
	END IF;
	INSERT INTO ticket (
			clientFk,
			shipped,
			addressFk,
			agencyModeFk,
			nickname,
			warehouseFk,
			routeFk,
			companyFk,
			landed,
            zoneFk
		)
		SELECT
					vClientId,
					vShipped,
					a.id,
					vAgencyModeFk,
					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;

    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 ;
