CREATE OR ALTER TRIGGER TTBNFS_A01I FOR TBNFS
ACTIVE AFTER INSERT POSITION 0
AS
DECLARE VARIABLE BASELEGAL_ID        INTEGER;
DECLARE VARIABLE CAMPO_LIVRE         INTEGER;
DECLARE VARIABLE BASELEGAL_DESCRICAO VARCHAR(8000);
BEGIN
   BASELEGAL_ID = COALESCE((SELECT FIRST 1 A.BASELEGAL_ID FROM TBESTABELECIMENTO A WHERE A.CODIGO = NEW.ESTABELECIMENTO_CODIGO),0);
   IF(BASELEGAL_ID > 0)THEN
   BEGIN
       BASELEGAL_DESCRICAO = FN_ELIPSES(COALESCE((SELECT FIRST 1 A.BASELEGAL FROM TBBASELEGAL A WHERE A.CODIGO = :BASELEGAL_ID),''),8000);
       IF(BASELEGAL_DESCRICAO <> '')THEN
         BEGIN
          FOR SELECT FIRST 1
                CASE 
                WHEN COALESCE(OBSERVACAO01,'') = '' THEN 1
                WHEN COALESCE(OBSERVACAO02,'') = '' THEN 2
                WHEN COALESCE(OBSERVACAO03,'') = '' THEN 3
                WHEN COALESCE(OBSERVACAO04,'') = '' THEN 4
                WHEN COALESCE(OBSERVACAO05,'') = '' THEN 5
                WHEN COALESCE(OBSERVACAO06,'') = '' THEN 6
                WHEN COALESCE(OBSERVACAO07,'') = '' THEN 7
                WHEN COALESCE(OBSERVACAO08,'') = '' THEN 8
                WHEN COALESCE(OBSERVACAO09,'') = '' THEN 9
                WHEN COALESCE(OBSERVACAO10,'') = '' THEN 10
                ELSE 0
                END AS CAMPO_LIVRE
    
                FROM TBNFS_OBSERVACAO
                WHERE NFS_CONTROLE = NEW.CONTROLE INTO CAMPO_LIVRE DO
                BEGIN
                    IF(:CAMPO_LIVRE > 0)THEN
                    BEGIN
                        EXECUTE STATEMENT 'UPDATE TBNFS_OBSERVACAO SET OBSERVACAO'||FN_LPAD(:CAMPO_LIVRE,2,0)||' = '||:BASELEGAL_DESCRICAO||' WHERE NFS_CONTROLE = '||NEW.CONTROLE;
                    END
                END
          END
    END
END;