Drop procedure if exists assingFromPeriodsPerson;
DELIMITER $$
CREATE  PROCEDURE `assingFromPeriodsPerson`(from_year int, from_month int, personId int)
BEGIN
          declare done int default 0;
          declare counter int default 0;
          declare endYear, initialMonth, person_ids, endMonth int;
          declare code_period varchar(20);
          DECLARE currents CURSOR FOR
        	SELECT case when min(code) is not null then min(code) else pc.liquidation_start_period end as code, pc.person_id
        	  FROM person_configurations pc
        	  left join periods pd on pc.person_id = pd.person_id
              where pc.liquidation_start_period is not null
               and pc.person_id = personId
              GROUP BY person_id, pc.liquidation_start_period
          ;

          DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;

          insert into log_debug (function_name, message, date) VALUES('assingFromPeriodsPerson', concat('ejecutando funcion'), now() );

          OPEN currents;
          REPEAT
            FETCH currents INTO code_period, person_ids;

            IF NOT done THEN
        	set counter = 1;
        	set endYear = CAST(SUBSTRING(code_period,1,4) AS SIGNED);
            set endMonth = 0;

            insert into log_debug (function_name, message, date) VALUES('assingFromPeriodsPerson', concat('Iterando cada empresa, Empres id->', person_ids,', periodo->', code_period), now() );


        	 while from_year <= endYear do
        		insert into log_debug (function_name, message, date) VALUES('assingFromPeriodsPerson', concat('While de empresa, from_year->', from_year,', initialMonth->', initialMonth, ', contador->', counter), now() );

        		set initialMonth = from_month;
                if(from_year!=endYear) then
					set endMonth = 12;
				else
					set endMonth = CAST(SUBSTRING(code_period,6,LENGTH(code_period)) AS SIGNED) -1;
                end if;
                
                if(counter!=1)then
					set initialMonth = 1;
				else
					set initialMonth = from_month;
				end if;

               insert Into periods (code, year, period_number, date_from, date_to, person_id)
                 select concat(from_year, '-', lpad(m.month, 2, '0')), from_year, m.month,
                  concat(from_year, '-', m.month, '-01'), concat(from_year, m.date_to),
                  p.id from persons p, months m
                  where p.id = person_ids
                  and (m.month >= initialMonth and m.month <= endMonth)
                   order by 2,3;
               set from_year = from_year + 1;
               set counter = counter +1;
        	 END WHILE;
            END IF;

          UNTIL done END REPEAT;

          CLOSE currents;
        END$$
DELIMITER ;
