import { Component, Renderer2, OnDestroy } from '@angular/core';
import { NavController, ViewController, NavParams, LoadingController, AlertController, ToastController, IonicApp } from 'ionic-angular';
import { environment } from "../../environments/environment"
import { DoctorService } from '../../services/doctor.service';
import { AuthService } from '../../services/auth.service';
import { Pata } from '../../pata';
import { forkJoin } from 'rxjs/observable/forkJoin';

@Component({
  selector: 'page-checkout',
  templateUrl: 'checkout.html'
})
export class ModalCheckout implements OnDestroy {
  public msg: string;
  public cartFull: any = null;
  public addresses: any = [];
  public cities: any = [];
  public states: any = [];
  public loading: any = null;
  public order: any = {
    to: '',
    street: '',
    additional: '',
    city: '',
    state: '',
    ship_price: 0,
    items: [],
    comment: ''
  }
  public enablePay: boolean = false;

  constructor(
    public viewCtrl: ViewController,
    public alertCtrl: AlertController, 
    public loadingCtrl: LoadingController, 
    public params: NavParams,
    public service: Pata,
    public auth: AuthService,
    public doctorService: DoctorService,
    public toastCtrl: ToastController,
    public navCtrl: NavController,
    public ionicApp: IonicApp,
    private renderer: Renderer2
  ) {
    let load = this.loadingCtrl.create({content: 'actualizando...'});
    load.present();

    let loadCart = this.doctorService.getCart();
    let loadAddress = this.doctorService.getAddresses();
    let loadStates = this.auth.getStates();
    forkJoin(loadCart, loadAddress, loadStates).subscribe((data:any) => {
      this.cartFull = data[0].data;
      this.addresses = data[1].data;
      this.states = data[2].data;
      load.dismiss();
      if (this.addresses.length > 0) {
        this.order.to = this.addresses[0].id;
      }
      console.log(this.addresses);
    });
  }

  closeCart() {
    let data = this.cartFull;
    this.viewCtrl.dismiss(data);
  }

  calculateShipping(evt?:any) {
    let city = '';
    if (this.order.to == 'N') {
      city = this.order.city;
    } else {
      for (let x = 0; x < this.addresses.length; x++) {
        if (this.addresses[x].id == this.order.to) {
          city = this.addresses[x].city;
        }
      }
    }
    if (city != '') {
      let load = this.loadingCtrl.create({content:'calculando despacho...'});
      load.present();
      this.doctorService.shippingPrice(city).subscribe((data:any)=>{
        load.dismiss();
        this.order.ship_price = data.price;
        if (data.res == "OK") {
          this.enablePay = true;
        } else {
          this.enablePay = false;
        }
      }); 
    } else {
      this.enablePay = false;
      this.order.ship_price = 0;
    }
  }

  cartTotal() {
    let total = 0;
    if (this.cartFull != null) {
      for (let x = 0; x < this.cartFull.items.length; x++) {
        total += parseFloat(this.cartFull.items[x].total);
      }
    }
    total += parseFloat(this.order.ship_price);
    return total;
  }
  itemsTotal() {
    let total = 0;
    if (this.cartFull != null) {
      for (let x = 0; x < this.cartFull.items.length; x++) {
        total += parseFloat(this.cartFull.items[x].total);
      }
    }
    return total;
  }
  pagar() {
    if (!this.enablePay) {
      let toast = this.toastCtrl.create({
        message: 'No podemos despachar a la comuna indicada tu pedido.',
        duration: 3000,
        position: 'bottom'
      });   
      toast.present();

    } else {
      if (this.order.to != 'N') {
        for (let x = 0; x < this.addresses.length; x++) {
          if (this.addresses[x].id == this.order.to) {
            this.order.street = this.addresses[x].street;
            this.order.additional = this.addresses[x].additional;
            this.order.city = this.addresses[x].city;
            this.order.state = this.addresses[x].state;
            break;
          }
        }
      }
  
      if (this.order.street == '' || this.order.city == '') {
        this.service.logError({},"Verifica la dirección y comuna de despacho para realizar el pago del pedido")
      } else {

        this.order.items = this.cartFull.items;
        
        let prepay = this.loadingCtrl.create({content: 'Validando pedido...'});
        prepay.present();
        this.doctorService.putPedido(this.order).subscribe((data:any) => {
          if (data.res == "OK") {
            prepay.dismiss();
            let cleanCart = {
              items: [],
              total: 0,
              finish: 1,
              msg: data.msg
            };
            this.navCtrl.popToRoot();
            this.doctorService.finishCompra.emit(cleanCart);
            /*
            let activeModal=this.ionicApp._modalPortal.getActive();
            activeModal.dismiss(cleanCart).then((a)=> {
              console.log(a);
              this.service.showOk(data.msg);
              this.viewCtrl.dismiss(cleanCart);
            });
            */

          } else {
            prepay.dismiss();
            this.service.logError({},data.msg);
          }
        });
      }
    }

  }
  ngOnDestroy(){

  }
  changeDirection(evt:any) {
    console.log('changeDirection',evt);
    if (this.order.to == 'N' && this.order.city == '') {
      this.enablePay = false;
      this.order.ship_price = 0;
    } else {
      //this.order.to = evt;
      this.calculateShipping();
    }
  }
  changeCities(newObj) {

    this.order.city = "";
    this.loading = this.loadingCtrl.create();
    this.loading.present();

    this.auth.getCities(newObj).subscribe((data: any) => {
      this.cities = data.data;
      this.loading.dismiss();
    },
    err => {
      this.loading.dismiss();
      this.service.logError({});
    });
  }
}

