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

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticket_cloneWeekly`(IN vWeek INT)
BEGIN
	DECLARE vIsDone BOOL;
	DECLARE vLanding DATE;
	DECLARE vShipment DATE;
	DECLARE vWarehouse INT;
    DECLARE vTicket INT;
    DECLARE vWeekDay INT;
    DECLARE vClient INT;
    DECLARE vEmpresa INT;
    DECLARE vAddressFk INT;
    DECLARE vAgencyModeFk INT;
    DECLARE vNewTicket INT;
    DECLARE vYear INT;
    
    DECLARE rsTicket CURSOR FOR
	SELECT tw.ticketFk, weekDay, t.clientFk, t.warehouseFk, t.companyFk, t.addressFk, tw.agencyModeFk
		FROM ticketWeekly tw 
		JOIN ticket t ON tt.ticketFk = t.id;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE;

    SET vYear = YEAR(CURDATE()) + IF(vWeek < WEEK(CURDATE()),1, 0);
    
	OPEN rsTicket;

	myLoop: LOOP
    BEGIN
		DECLARE vError TEXT;
        DECLARE vSalesPersonEmail VARCHAR(150);
        DECLARE vMailSent BOOL;
        DECLARE vSubject VARCHAR(150);
        DECLARE vMessage TEXT;
		DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
			BEGIN 
				GET DIAGNOSTICS CONDITION 1
					vError = MESSAGE_TEXT;
			END;

		SET vIsDone = FALSE;
		FETCH rsTicket INTO vTicket, vWeekDay, vClient, vWarehouse, vEmpresa, vAddressFk, vAgencyModeFk;

		IF vIsDone THEN

			LEAVE myLoop;
		END IF;
		SELECT date INTO vShipment 
			FROM `time`
			WHERE `year` = vYear AND `week` = vWeek
				AND WEEKDAY(date) = vWeekDay;

        -- busca si el ticket ya ha sido clonado
        IF (SELECT COUNT(*) FROM vn.ticket tOrig
				JOIN vn.sale saleOrig ON tOrig.id = saleOrig.ticketFk
                JOIN vn.saleCloned sc ON sc.saleOriginalFk = saleOrig.id
                JOIN vn.sale saleClon ON saleClon.id = sc.saleClonedFk
                JOIN vn.ticket tClon ON tClon.id = saleClon.ticketFk
			WHERE tOrig.id = vTicket AND DATE(tClon.shipped) = vShipment) > 0 
		THEN
			ITERATE myLoop;
		END IF;
		CALL vn.zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouse, TRUE);

		SELECT landed INTO vLanding from tmp.zoneGetLanded LIMIT 1;

		CALL vn.ticketCreateWithoutZone(vClient, vShipment, vWarehouse, vEmpresa, vAddressFk, vAgencyModeFk, NULL, vLanding, account.userGetId(), vNewTicket);

		IF (vLanding IS NULL) THEN
			
			SELECT e.email INTO vSalesPersonEmail
				FROM vn.client c
					JOIN vn.worker sp ON sp.id = c.salesPersonFk
					JOIN account.emailUser e ON e.userFk = sp.userFk
				WHERE c.id = vClient;
		
			SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ', vTicket,
						' para el dia: ', vShipment);
			SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicket, 
				' para el dia: ', vShipment, 
				' porque no hay una zona de envío disponible. Se ha creado el ticket: ', vNewTicket, 
				' pero ha que revisar las fechas y la agencia');
				
			SELECT COUNT(*) INTO vMailSent
				FROM vn.mail 
				WHERE sender = vSalesPersonEmail 
					AND subject = vSubject;

			IF NOT vMailSent THEN
				INSERT INTO vn.mail (sender,`subject`,body)  
					VALUES (vSalesPersonEmail, vSubject, vMessage);
			END IF;
			CALL vn.ticketStateUpdate (vNewTicket, 'FIXING');
		END IF;
        
		INSERT INTO vn.sale (ticketFk, itemFk, concept, quantity, price, discount, priceFixed, isPriceFixed)
			SELECT vNewTicket, saleOrig.itemFk , saleOrig.concept , saleOrig.quantity, saleOrig.price , saleOrig.discount, saleOrig.priceFixed, saleOrig.isPriceFixed
				FROM vn.ticket tOrig
				JOIN vn.sale saleOrig ON tOrig.id = saleOrig.ticketFk
                LEFT JOIN vn.saleCloned sc ON sc.saleOriginalFk = saleOrig.id
                LEFT JOIN vn.sale saleClon ON saleClon.id = sc.saleClonedFk
                LEFT JOIN vn.ticket tClon ON tClon.id = saleClon.ticketFk AND DATE(tClon.shipped) = vShipment
			WHERE tOrig.id = vTicket AND saleClon.id IS NULL;
		
		INSERT IGNORE INTO vn.saleCloned(saleOriginalFk, saleClonedFk)
			SELECT saleOriginal.id, saleClon.id 
				FROM vn.sale saleOriginal
					JOIN vn.sale saleClon ON saleOriginal.itemFk = saleClon.itemFk AND saleOriginal.quantity = saleClon.quantity
				WHERE saleOriginal.ticketFk = vTicket AND saleClon.ticketFk = vNewTicket;
				
		INSERT INTO ticketRequest (description, ordered, shipped, salesPersonCode, buyerCode, quantity, price,
					itemFk ,clientFk, response, total, buyed, saleFk)
			SELECT tr.description, tr.ordered, tr.shipped, tr.salesPersonCode, tr.buyerCode, tr.quantity, tr.price,
					tr.itemFk, tr.clientFk, tr.response, tr.total, tr.buyed, tr.saleFk
				FROM sale s JOIN ticketRequest tr ON tr.saleFk = s.id
					JOIN sale s2 ON s.concept = s2.concept AND s.quantity = s2.quantity AND m.Id_Article = m2.Id_Article
					WHERE s.ticketFk = vTicket AND s2.ticketFk = vNewTicket;

		CALL vn.ticketCalculateClon(vNewTicket, vTicket);
	END;
	END LOOP;

	CLOSE rsTicket;

END$$

DELIMITER ;

