DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_cloneWeekly`(
	vDateFrom DATE, 
	vDateTo DATE
)
BEGIN
	DECLARE vLanding DATE;
	DECLARE vShipment DATE;
	DECLARE vWarehouseFk INT;
	DECLARE vTicketFk INT;
	DECLARE vClientFk INT;
	DECLARE vCompanyFk INT;
	DECLARE vAddressFk INT;
	DECLARE vAgencyModeFk INT;
	DECLARE vCurrencyFk INT;
	DECLARE vNewTicket INT;
	DECLARE vYear INT;
	DECLARE vObservationSalesPersonFk INT
		DEFAULT (SELECT id FROM observationType WHERE code = 'salesPerson');
	DECLARE vObservationItemPickerFk INT
		DEFAULT (SELECT id FROM observationType WHERE code = 'itemPicker');
	DECLARE vEmail VARCHAR(255);
	DECLARE vIsDuplicateMail BOOL;
	DECLARE vSubject VARCHAR(100);
	DECLARE vMessage TEXT;
	DECLARE vDone BOOL;

	DECLARE vTickets CURSOR FOR
		SELECT tt.ticketFk,
				t.clientFk,
				t.warehouseFk,
				t.companyFk,
				t.currencyFk,
				t.addressFk,
				tt.agencyModeFk,
				ti.dated
			FROM ticketWeekly tt 
				JOIN ticket t ON tt.ticketFk = t.id
				JOIN tmp.time ti
			WHERE WEEKDAY(ti.dated) = tt.weekDay;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	CALL `util`.`time_generate`(vDateFrom, vDateTo);

	OPEN vTickets;
	l: LOOP
		SET vDone = FALSE;
		FETCH vTickets INTO 
			vTicketFk, 
			vClientFk, 
			vWarehouseFk, 
			vCompanyFk, 
			vCurrencyFk,
			vAddressFk, 
			vAgencyModeFk,
			vShipment;

		IF vDone THEN
			LEAVE l;
		END IF;

		-- Busca si el ticket ya ha sido clonado
		IF EXISTS (SELECT TRUE FROM ticket tOrig
				JOIN sale saleOrig ON tOrig.id = saleOrig.ticketFk
				JOIN saleCloned sc ON sc.saleOriginalFk = saleOrig.id
				JOIN sale saleClon ON saleClon.id = sc.saleClonedFk
				JOIN ticket tClon ON tClon.id = saleClon.ticketFk
			WHERE tOrig.id = vTicketFk 
				AND tClon.isDeleted = FALSE 
				AND DATE(tClon.shipped) = vShipment)
		THEN
			ITERATE l;
		END IF;

		IF vAgencyModeFk IS NULL THEN
			SELECT agencyModeFk INTO vAgencyModeFk 
				FROM address
				WHERE clientFk = vClientFk 
					AND isDefaultAddress;
		END IF;

		CALL zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk, FALSE);
		SET vLanding = NULL;
		SELECT landed INTO vLanding FROM tmp.zoneGetLanded LIMIT 1;

		CALL ticket_add(
			vClientFk,
			vShipment,
			vWarehouseFk,
			vCompanyFk,
			vAddressFk,
			vAgencyModeFk,
			NULL,
			vLanding,
			account.myUser_getId(),
			FALSE,
			vCurrencyFk,
			vNewTicket);

		UPDATE ticket 
			SET clonedFrom = vTicketFk 
			WHERE id = vNewTicket;

		INSERT INTO sale (ticketFk, 
				itemFk, 
				concept,
				quantity, 
				price,
				foreignPrice,
				discount, 
				priceFixed, 
				isPriceFixed)
			SELECT vNewTicket,
					itemFk,
					concept,
					quantity,
					price,
					foreignPrice,
					discount,
					priceFixed,
					isPriceFixed
				FROM sale
				WHERE ticketFk = vTicketFk;

		INSERT IGNORE INTO saleCloned(saleOriginalFk, saleClonedFk)
			SELECT saleOriginal.id, saleClon.id
				FROM sale saleOriginal
					JOIN sale saleClon ON saleOriginal.itemFk = saleClon.itemFk 
						AND saleOriginal.quantity = saleClon.quantity
				WHERE saleOriginal.ticketFk = vTicketFk
					AND saleClon.ticketFk = vNewTicket;

		INSERT INTO ticketRequest (description,
				ordered,
				shipped,
				quantity,
				price,
				itemFk,
				clientFk,
				response,
				total,
				buyed,
				requesterFk
				,attenderFk,
				ticketFk)
			SELECT description,
					ordered,
					shipped,
					quantity,
					price,
					itemFk,
					clientFk,
					response,
					total,
					buyed,
					requesterFk,
					attenderFk,
					vNewTicket 
				FROM ticketRequest
				WHERE ticketFk = vTicketFk;

		INSERT INTO ticketObservation(
				ticketFk,
				observationTypeFk,
				description) 
			VALUES(
				vNewTicket,
				vObservationSalesPersonFk,
				CONCAT('turno desde ticket: ',vTicketFk))
			ON DUPLICATE KEY UPDATE description = 
				CONCAT(ticketObservation.description,VALUES(description),' ');

		INSERT INTO ticketObservation(ticketFk,
				observationTypeFk,
				description) 
			VALUES(
				vNewTicket,
				vObservationItemPickerFk,
				'ATENCION: Contiene lineas de TURNO')
			ON DUPLICATE KEY UPDATE description = 
				CONCAT(ticketObservation.description,VALUES(description),' ');

		IF vLanding IS NULL THEN
			SELECT IFNULL(d.notificationEmail, e.email) INTO vEmail
				FROM client c
					JOIN account.emailUser e ON e.userFk = c.salesPersonFk
					LEFT JOIN workerDepartment wd ON wd.workerFk = c.salesPersonFk
					LEFT JOIN department d ON d.id = wd.departmentFk
				WHERE c.id = vClientFk;

			SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ',
						 vTicketFk,' para el dia: ', vShipment);
			SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicketFk, 
				' 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 vIsDuplicateMail
				FROM mail
				WHERE receiver = vEmail
					AND subject = vSubject;

			IF NOT vIsDuplicateMail THEN
				CALL mail_insert(vEmail, NULL, vSubject, vMessage);
			END IF;
			CALL ticket_setState(vNewTicket, 'FIXING');
		ELSE
			CALL ticketCalculateClon(vNewTicket, vTicketFk);
		END IF;
	END LOOP;
	CLOSE vTickets;

	DROP TEMPORARY TABLE IF EXISTS
		tmp.time,
		tmp.zoneGetLanded;
END$$
DELIMITER ;
