import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { MatDialog } from '@angular/material';
import { ApiService } from 'app/api.service';
import { UsersAddComponent } from 'app/users-add/users-add.component';
import { UsersMessageComponent } from 'app/users-message/users-message.component';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss']
})
export class UsersComponent implements OnInit {

  public users: any = [];

  constructor(private title: Title, public dialog: MatDialog, public apiService: ApiService) {
    this.title.setTitle("ERP - Usuarios");
  }
  ngOnInit() {
    this.filterdata();
  }
  filterdata() {
    this.apiService.getUsers().subscribe((data:any) => {
      this.users = data.data;
    });
  }
  addUser() {
    let data = {
      type: 'add',
      first_name: '',
      last_name: '',
      avatar: '',
      level: 10,
      status: '1',
      email: '',
      phone: '',
      card_code: '',
      password: '',
      pw: ''
    }
    const dialogRef = this.dialog.open(UsersAddComponent, { width: '70%', data: data });
    dialogRef.afterClosed().subscribe(result => {
      this.filterdata();
    });
  }
  editUser(index:number) {
    let data = this.users[index];
    data.type = 'edit';   
    data.pw = '';
    const dialogRef = this.dialog.open(UsersAddComponent, { width: '70%', data: data });
    dialogRef.afterClosed().subscribe(result => {
      this.filterdata();
    });
  }
  messageUser(index:string) {
    let id = this.users[index].id;
    let data: any = { id: id };
    const dialogRef = this.dialog.open(UsersMessageComponent, { width: '50%', data: data });
    dialogRef.afterClosed().subscribe(result => {
      this.filterdata();
    }); 
  }
  deleteUser(index:string) {
    let id = this.users[index].id;
    let confirm = this.apiService.confirm("Confirmar","¿Deseas eliminar el usuario "+this.users[index].first_name+"?");
    confirm.then((data:any)=> { 
      if (data.dismiss=="cancel") { }
      else if (data.value) {
        this.apiService.deleteUser(id).subscribe((data:any)=>{
          if (data.res == "OK") {
            this.users.splice(index, 1);
          } else {
            this.apiService.showError("Error",data.msg);
          }
        });
      }
    });
  }

}
