# Exemplos Práticos

## 📚 Guia de Exemplos

Este documento contém exemplos práticos de uso dos componentes da biblioteca `@seniorsistemas/components-ai`.

---

## 🎯 Dynamic Form - Exemplos Completos

### Exemplo 1: Formulário de Cadastro Simples

```typescript
import { Component } from '@angular/core';
import { DynamicFormComponent, DynamicFormFieldConfig, FieldType } from '@seniorsistemas/components-ai';

@Component({
  selector: 'app-product-form',
  template: `
    <sia-dynamic-form
      [formFields]="formFields"
      [mode]="'create'"
      (onSubmit)="handleSubmit($event)"
    ></sia-dynamic-form>
  `
})
export class ProductFormComponent {
  formFields: DynamicFormFieldConfig[] = [
    {
      name: 'name',
      label: 'Nome do Produto',
      type: FieldType.TEXT,
      required: true,
      placeholder: 'Digite o nome do produto',
      cols: 12
    },
    {
      name: 'description',
      label: 'Descrição',
      type: FieldType.TEXTAREA,
      rows: 4,
      cols: 12
    },
    {
      name: 'price',
      label: 'Preço',
      type: FieldType.NUMBER,
      required: true,
      min: 0,
      step: 0.01,
      cols: 6
    },
    {
      name: 'stock',
      label: 'Estoque',
      type: FieldType.NUMBER,
      required: true,
      min: 0,
      cols: 6
    },
    {
      name: 'active',
      label: 'Ativo',
      type: FieldType.SWITCH,
      value: true,
      cols: 12
    }
  ];

  handleSubmit(formValue: any): void {
    console.log('Produto criado:', formValue);
    // Chamar serviço para salvar
  }
}
```

---

### Exemplo 2: Formulário com Seções

```typescript
import { Component } from '@angular/core';
import { DynamicFormSection, FieldType } from '@seniorsistemas/components-ai';

@Component({
  selector: 'app-customer-form',
  template: `
    <sia-dynamic-form
      [formSections]="formSections"
      [mode]="'create'"
      (onSubmit)="handleSubmit($event)"
    ></sia-dynamic-form>
  `
})
export class CustomerFormComponent {
  formSections: DynamicFormSection[] = [
    {
      title: 'Dados Pessoais',
      fields: [
        {
          name: 'name',
          label: 'Nome Completo',
          type: FieldType.TEXT,
          required: true,
          cols: 8
        },
        {
          name: 'document',
          label: 'CPF',
          type: FieldType.TEXT,
          required: true,
          mask: '000.000.000-00',
          cols: 4
        },
        {
          name: 'email',
          label: 'E-mail',
          type: FieldType.EMAIL,
          required: true,
          cols: 6
        },
        {
          name: 'phone',
          label: 'Telefone',
          type: FieldType.TEXT,
          mask: '(00) 00000-0000',
          cols: 6
        }
      ]
    },
    {
      title: 'Endereço',
      collapsible: true,
      fields: [
        {
          name: 'zipCode',
          label: 'CEP',
          type: FieldType.TEXT,
          mask: '00000-000',
          cols: 4
        },
        {
          name: 'street',
          label: 'Rua',
          type: FieldType.TEXT,
          cols: 8
        },
        {
          name: 'number',
          label: 'Número',
          type: FieldType.TEXT,
          cols: 3
        },
        {
          name: 'complement',
          label: 'Complemento',
          type: FieldType.TEXT,
          cols: 3
        },
        {
          name: 'neighborhood',
          label: 'Bairro',
          type: FieldType.TEXT,
          cols: 6
        },
        {
          name: 'city',
          label: 'Cidade',
          type: FieldType.TEXT,
          cols: 6
        },
        {
          name: 'state',
          label: 'Estado',
          type: FieldType.SELECT,
          options: [
            { label: 'São Paulo', value: 'SP' },
            { label: 'Rio de Janeiro', value: 'RJ' },
            { label: 'Minas Gerais', value: 'MG' }
          ],
          cols: 6
        }
      ]
    }
  ];

  handleSubmit(formValue: any): void {
    console.log('Cliente criado:', formValue);
  }
}
```

---

### Exemplo 3: Formulário em Dialog

```typescript
import { Component } from '@angular/core';
import { DynamicFormFieldConfig, FieldType } from '@seniorsistemas/components-ia';

@Component({
  selector: 'app-category-list',
  template: `
    <p-button 
      label="Nova Categoria" 
      icon="pi pi-plus"
      (onClick)="openDialog()"
    ></p-button>

    <sia-dynamic-form
      [(visible)]="showDialog"
      [formFields]="formFields"
      [entity]="selectedCategory"
      [mode]="selectedCategory ? 'edit' : 'create'"
      [displayMode]="'dialog'"
      [dialogHeader]="selectedCategory ? 'Editar Categoria' : 'Nova Categoria'"
      (onSubmit)="handleSubmit($event)"
    ></sia-dynamic-form>
  `
})
export class CategoryListComponent {
  showDialog = false;
  selectedCategory: any = null;

  formFields: DynamicFormFieldConfig[] = [
    {
      name: 'name',
      label: 'Nome',
      type: FieldType.TEXT,
      required: true,
      cols: 12
    },
    {
      name: 'description',
      label: 'Descrição',
      type: FieldType.TEXTAREA,
      rows: 3,
      cols: 12
    },
    {
      name: 'active',
      label: 'Ativa',
      type: FieldType.SWITCH,
      value: true,
      cols: 12
    }
  ];

  openDialog(category?: any): void {
    this.selectedCategory = category || null;
    this.showDialog = true;
  }

  handleSubmit(formValue: any): void {
    if (this.selectedCategory) {
      console.log('Categoria atualizada:', formValue);
      // Chamar serviço de update
    } else {
      console.log('Categoria criada:', formValue);
      // Chamar serviço de create
    }
    this.showDialog = false;
  }
}
```

---

### Exemplo 4: Formulário de Filtro

```typescript
import { Component } from '@angular/core';
import { DynamicFormFieldConfig, FieldType } from '@seniorsistemas/components-ia';

@Component({
  selector: 'app-product-list',
  template: `
    <sia-dynamic-form
      [formFields]="filterFields"
      [mode]="'filter'"
      [submitButtonLabel]="'Filtrar'"
      (onSubmit)="applyFilter($event)"
    ></sia-dynamic-form>

    <!-- Tabela de produtos -->
  `
})
export class ProductListComponent {
  filterFields: DynamicFormFieldConfig[] = [
    {
      name: 'name',
      label: 'Nome',
      type: FieldType.TEXT,
      placeholder: 'Buscar por nome',
      cols: 4
    },
    {
      name: 'category',
      label: 'Categoria',
      type: FieldType.SELECT,
      options: [
        { label: 'Todas', value: null },
        { label: 'Eletrônicos', value: 1 },
        { label: 'Roupas', value: 2 },
        { label: 'Alimentos', value: 3 }
      ],
      cols: 4
    },
    {
      name: 'active',
      label: 'Status',
      type: FieldType.SELECT,
      options: [
        { label: 'Todos', value: null },
        { label: 'Ativos', value: true },
        { label: 'Inativos', value: false }
      ],
      cols: 4
    }
  ];

  applyFilter(filterValues: any): void {
    console.log('Filtros aplicados:', filterValues);
    // Chamar serviço com filtros
  }
}
```

---

### Exemplo 5: Formulário com Lookup

```typescript
import { Component } from '@angular/core';
import { DynamicFormFieldConfig, FieldType } from '@seniorsistemas/components-ia';

@Component({
  selector: 'app-order-form',
  template: `
    <sia-dynamic-form
      [formFields]="formFields"
      [mode]="'create'"
      (onSubmit)="handleSubmit($event)"
    ></sia-dynamic-form>
  `
})
export class OrderFormComponent {
  formFields: DynamicFormFieldConfig[] = [
    {
      name: 'customer',
      label: 'Cliente',
      type: FieldType.LOOKUP,
      required: true,
      lookupConfig: {
        service: this.customerService,
        displayField: 'name',
        valueField: 'id',
        searchFields: ['name', 'document'],
        columns: [
          { field: 'name', header: 'Nome' },
          { field: 'document', header: 'CPF/CNPJ' },
          { field: 'email', header: 'E-mail' }
        ]
      },
      cols: 12
    },
    {
      name: 'product',
      label: 'Produto',
      type: FieldType.LOOKUP,
      required: true,
      lookupConfig: {
        service: this.productService,
        displayField: 'name',
        valueField: 'id',
        searchFields: ['name', 'code'],
        columns: [
          { field: 'code', header: 'Código' },
          { field: 'name', header: 'Nome' },
          { field: 'price', header: 'Preço' }
        ]
      },
      cols: 8
    },
    {
      name: 'quantity',
      label: 'Quantidade',
      type: FieldType.NUMBER,
      required: true,
      min: 1,
      value: 1,
      cols: 4
    },
    {
      name: 'deliveryDate',
      label: 'Data de Entrega',
      type: FieldType.DATE,
      required: true,
      minDate: new Date(),
      cols: 6
    },
    {
      name: 'notes',
      label: 'Observações',
      type: FieldType.TEXTAREA,
      rows: 3,
      cols: 12
    }
  ];

  constructor(
    private customerService: CustomerService,
    private productService: ProductService
  ) {}

  handleSubmit(formValue: any): void {
    console.log('Pedido criado:', formValue);
  }
}
```

---

## 📤 Export Dialog - Exemplo

```typescript
import { Component } from '@angular/core';
import { ColumnOption } from '@seniorsistemas/components-ai';

@Component({
  selector: 'app-product-list',
  template: `
    <p-button 
      label="Exportar" 
      icon="pi pi-download"
      (onClick)="showExportDialog = true"
    ></p-button>

    <sia-export-dialog
      [(visible)]="showExportDialog"
      [data]="products"
      [columns]="exportColumns"
      [fileName]="'produtos'"
    ></sia-export-dialog>
  `
})
export class ProductListComponent {
  showExportDialog = false;
  products: any[] = [];

  exportColumns: ColumnOption[] = [
    { field: 'code', header: 'Código', selected: true },
    { field: 'name', header: 'Nome', selected: true },
    { field: 'category', header: 'Categoria', selected: true },
    { field: 'price', header: 'Preço', selected: true },
    { field: 'stock', header: 'Estoque', selected: true },
    { field: 'active', header: 'Status', selected: false }
  ];
}
```

---

## 🗑️ Bulk Delete Dialog - Exemplo

```typescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-product-list',
  template: `
    <p-button 
      label="Excluir Selecionados" 
      icon="pi pi-trash"
      [disabled]="selectedProducts.length === 0"
      (onClick)="showBulkDeleteDialog = true"
    ></p-button>

    <sia-bulk-delete-dialog
      [(visible)]="showBulkDeleteDialog"
      [selectedItems]="selectedProducts"
      [entityName]="'produto'"
      [entityPluralName]="'produtos'"
      (onConfirm)="handleBulkDelete()"
    ></sia-bulk-delete-dialog>
  `
})
export class ProductListComponent {
  showBulkDeleteDialog = false;
  selectedProducts: any[] = [];

  handleBulkDelete(): void {
    const ids = this.selectedProducts.map(p => p.id);
    this.productService.bulkDelete(ids).subscribe({
      next: () => {
        this.messageService.add({
          severity: 'success',
          summary: 'Sucesso',
          detail: `${this.selectedProducts.length} produtos excluídos`
        });
        this.selectedProducts = [];
        this.loadProducts();
      },
      error: (error: any) => {
        this.messageService.add({
          severity: 'error',
          summary: 'Erro',
          detail: 'Erro ao excluir produtos'
        });
      }
    });
  }
}
```

---

## 🍞 Breadcrumb - Exemplo

```typescript
import { Component, OnInit } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-product-edit',
  template: `
    <sia-breadcrumb
      [items]="breadcrumbItems"
      [home]="{ icon: 'pi pi-home', routerLink: '/' }"
    ></sia-breadcrumb>

    <!-- Formulário de edição -->
  `
})
export class ProductEditComponent implements OnInit {
  breadcrumbItems: MenuItem[] = [];

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    const productId = this.route.snapshot.params['id'];
    
    this.breadcrumbItems = [
      { label: 'Cadastros' },
      { label: 'Produtos', routerLink: '/products' },
      { label: `Editar #${productId}` }
    ];
  }
}
```

---

## 🔗 Veja Também

- [Documentação de Componentes](./COMPONENTS.md)
- [Referência da API](./API.md)
- [Guia de Migração](./MIGRATION.md)
