CREATE OR ALTER trigger tbwhatsapp_b01u for tbwhatsapp
active before update position 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
DECLARE VARIABLE DESC_REPRESENTANTE_OLD VARCHAR(500);
DECLARE VARIABLE DESC_REPRESENTANTE_NEW VARCHAR(500);
BEGIN

    HISTORICO = '';

    DESC_REPRESENTANTE_OLD = '';
    DESC_REPRESENTANTE_NEW = '';

    SELECT TRIM(T.NOMEFANTASIA) FROM TBEMPRESA T WHERE T.CODIGO = OLD.REPRESENTANTE_ID INTO DESC_REPRESENTANTE_OLD;

    SELECT TRIM(E.NOMEFANTASIA) FROM TBEMPRESA E WHERE E.CODIGO = NEW.REPRESENTANTE_ID INTO DESC_REPRESENTANTE_NEW;

    IF ( OLD.NUMERO <> NEW.NUMERO) THEN
    BEGIN
        HISTORICO = HISTORICO||'NUMERO: '|| OLD.NUMERO||'->'||NEW.NUMERO;
    END

    IF ( OLD.NOME <> NEW.NOME) THEN
    BEGIN
        HISTORICO = HISTORICO||' NOME: '|| OLD.NOME||'->'||NEW.NOME;
    END
    
    IF ( OLD.MENU <> NEW.MENU) THEN
    BEGIN
        HISTORICO = HISTORICO||' MENU: '|| OLD.MENU||'->'||NEW.NUMERO;
    END

    IF ( OLD.FUNCAO <> NEW.FUNCAO) THEN
    BEGIN
        HISTORICO = HISTORICO||' FUNCAO: '|| OLD.FUNCAO||'->'||NEW.FUNCAO;
    END
    
    IF ( OLD.NIVEL <> NEW.NIVEL) THEN
    BEGIN
        HISTORICO = HISTORICO||' NIVEL: '|| OLD.NIVEL||'->'||NEW.NIVEL;
    END

    IF ( OLD.SETOR <> NEW.SETOR) THEN
    BEGIN
        HISTORICO = HISTORICO||' SETOR: '|| OLD.SETOR||'->'||NEW.SETOR;
    END

    IF ( OLD.SUPERVISOR_ID IS DISTINCT FROM NEW.SUPERVISOR_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' SUPERVISOR: '|| COALESCE(OLD.SUPERVISOR_ID, 0)||'->'||COALESCE(NEW.SUPERVISOR_ID, 0);
    END

    IF ( OLD.REPRESENTANTE_ID <> NEW.REPRESENTANTE_ID) THEN
    BEGIN

            HISTORICO = HISTORICO||' REPRESENTANTE: '||DESC_REPRESENTANTE_OLD||'->'||DESC_REPRESENTANTE_NEW;
    END

    IF ( OLD.VENDEDOR_ID IS DISTINCT FROM NEW.VENDEDOR_ID) THEN
    BEGIN
       HISTORICO = HISTORICO||' VENDEDOR: '||COALESCE(OLD.VENDEDOR_ID, 0)||'->'||COALESCE(NEW.VENDEDOR_ID, 0);
    END

    IF ( OLD.status <> NEW.status) THEN
    BEGIN
        IF(OLD.STATUS = '0' AND NEW.STATUS = '1') THEN  HISTORICO = HISTORICO||'Status habilitado';

        IF(OLD.STATUS = '1' AND NEW.STATUS = '0') THEN HISTORICO = HISTORICO||'Status desabilitada';
    END

    IF ( OLD.WHATSAPP_COMANDOS_ID <> NEW.WHATSAPP_COMANDOS_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' WHATSAPP COMANDOS: '|| OLD.WHATSAPP_COMANDOS_ID||'->'||NEW.WHATSAPP_COMANDOS_ID;
    END

    IF ( OLD.OBSERVACAO <> NEW.OBSERVACAO) THEN
    BEGIN
        HISTORICO = HISTORICO||' OBS. '|| OLD.OBSERVACAO||'->'||NEW.OBSERVACAO;
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBWHATSAPP',NEW.id, HISTORICO);
    END
end;