DROP PROCEDURE IF EXISTS nomer_lot;
DELIMITER //
create procedure nomer_lot
(
IN in_id int
)
BEGIN
Set @id = in_id;
Set @nmr_mulai = (select case when cast(tb_seq.mulai AS INT) = 1 then cast((tb_seq.mulai) AS INT) 
                 else cast((tb_seq.mulai + 1) AS INT)
				  end from(
				select tb.rowid,tb.id,tb.tgl,ifnull(B.nmr,1) as mulai,tb.nmr as hingga from(
				select row_number() over (order by A.id asc) as rowid,A.id,A.tgl,A.nomor,
				sum(A.nomor) over (order by A.id asc) as nmr
				from tb_lot A
				where A.tgl = (select tgl from tb_lot where id = @id)
				) as tb
				Left join(select (row_number() over (order by id asc)+1) as rowid,
				sum(nomor) over (order by id asc) as nmr
				from tb_lot where tgl = (select tgl from tb_lot where id = @id)
				)B on B.rowid = tb.rowid
				) as tb_seq
				where tb_seq.id = @id);
set @nmr_hingga = (select cast(tb_seq.hingga AS INT) from(
				select tb.rowid,tb.id,tb.tgl,ifnull(B.nmr,0) as mulai,tb.nmr as hingga from(
				select row_number() over (order by A.id asc) as rowid,A.id,A.tgl,A.nomor,
				sum(A.nomor) over (order by A.id asc) as nmr
				from tb_lot A
				where A.tgl = (select tgl from tb_lot where id = @id)
				) as tb
				Left join(select (row_number() over (order by id asc)+1) as rowid,
				sum(nomor) over (order by id asc) as nmr
				from tb_lot where tgl = (select tgl from tb_lot where id = @id)
				)B on B.rowid = tb.rowid
				) as tb_seq
				where tb_seq.id = @id);
Set @nomer_lot = (select concat(shift,date_format(tgl,'%y'),date_format(tgl,'%m'),date_format(tgl,'%d'),LPAD(kd_mesin, 2, '0')) from tb_lot where id = @id);
Set @warna = (select B.warna from tb_lot A Left join tb_fg B on B.sku = A.sku where A.id = @id);
WITH RECURSIVE nmer_lot AS (
    SELECT @nmr_mulai  AS n
    UNION ALL
    SELECT n + 1 FROM nmer_lot WHERE n < @nmr_hingga
)
SELECT ifnull(CONCAT(@nomer_lot, LPAD(n, 3, '0')),0) AS lotfg,@warna as warna FROM nmer_lot;
END;
//