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

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

        DECLARE vClientOrnamentales INT DEFAULT 5270;
        DECLARE vCompanyOrn INT DEFAULT 1381;
        DECLARE vProvinceName VARCHAR(255);

        SELECT p.name INTO vProvinceName
            FROM vn.client c
                JOIN province p ON p.id = c.provinceFk
            WHERE c.id = vClientId;

        IF vProvinceName IN ('SANTA CRUZ DE TENERIFE', 'LAS PALMAS DE GRAN CANARIA') AND vClientId <> vClientOrnamentales THEN
            SET vCompanyFk = vCompanyOrn;
        END IF;

    IF NOT vAddressFk THEN
        SELECT id INTO vAddressFk 
            FROM address
            WHERE clientFk = vClientId AND isDefaultAddress;
    END IF;

        INSERT INTO vn2008.Tickets (
                        Id_Cliente,
                        Fecha,
                        Id_Consigna,
                        Id_Agencia,
                        Alias,
                        warehouse_id,
                        Id_Ruta,
                        empresa_id,
                        landing
                )
                SELECT
                            vClientId,
                            vShipped,
                            a.id,
                            IF(vAgencyType, vAgencyType, a.agencyModeFk),
                            a.nickname,
                            vWarehouseId,
                            IF(vRouteFk,vRouteFk,NULL),
                            vCompanyFk,
                            vlanded
                    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));

        IF (SELECT isCreatedAsServed FROM vn.client WHERE 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 ;

