<div class="col-xs-12">
  <div class="text-center">
    <span class="font-blue-madison title"><i class="fa fa-file-text"></i> Alterar Venda</span>
  </div>
  <?php foreach($customer as $cliente): ?>
  <h4><strong>Dados do cliente:</strong></h4>
  <strong>Email: </strong><a href="mailto:<?php echo e($cliente->email); ?>"><?php echo e($cliente->email); ?></a><br/>
  <?php if(!empty($cliente->phone)): ?>
  <strong>Telefone: </strong><?php echo e($cliente->phone); ?> <br/>
  <?php endif; ?>
  <?php if(!empty($cliente->mobile)): ?>
  <strong>Celular: </strong><?php echo e($cliente->mobile); ?> <br/>
  <?php endif; ?>
  <strong>Cliente desde:</strong> <?php echo e($cliente->data_cadastro); ?> <br/>
  <strong>Status:</strong> <?php echo e($cliente->situacao); ?> <br/>
  <strong>Dia de vencimento:</strong> <?php echo e($cliente->dia_vencimento); ?> <br/>
  <strong>Plano Atual:</strong> <?php echo e($cliente->Plano); ?><br/>
  <?php if(!empty($cliente->address)): ?>
  <strong>Endereço:</strong> <?php echo e($cliente->address); ?>, <?php echo e($cliente->neighborhood); ?> - <?php echo e($cliente->city); ?> (<?php echo e($cliente->state); ?>) - CEP: <?php echo e($cliente->zip_code); ?>  <br/>
  <?php endif; ?>
  <?php endforeach; ?>
</div>
<?php if($hafatura): ?>
  <div class="col-xs-12 text-center bg-red bg-font-red title" style="margin-top:20px;">
    <span class=""><i class="fa fa-bullhorn"></i>
      Aprovação Pendente - peça a aprovação para o responsável de vendas
    </span>
  </div>
<?php endif; ?>
<div class="col-xs-12" id="app">

  <div class="row" v-if="servicos.length==0 && init==0 && fault==0">
    <div class="col-xs-12 text-center">
      <div class="title-load-vue">
        Carregando dados 
        <img src='<?php echo e(asset('/assets/global/img/loading.gif')); ?>'>
      </div>
    </div>
  </div>

  <div class="row" v-if="servicos.length==0 && init==0 && fault==1">
    <div class="col-xs-12 text-center">
      <div class="title-load-vue">
        Indisponível Para Edição 
      </div>
    </div>
  </div>

  <custom-select v-bind:data="component.servicos" v-on:message="addItem" type='Serviços' v-if="init">
  </custom-select>  

  <custom-servicos-table v-bind:items="servicos">
  </custom-servicos-table>

  <div class="row" v-if="servicos.length>0">
    <div class="col-xs-12 text-center">
      <span  class="btn btn-success"  v-if="init" v-on:click='submit' >
        <i class=" fa fa-save"></i> Salvar
      </span>
      <span  class="btn red" data-dismiss="modal" aria-label="Close">
        <i class="fa fa-remove"></i> Cancelar
      </span>
    </div>
  </div>

</div>

<input type="hidden"  id="_token" value="<?php echo csrf_token(); ?>">
<template id="select-template">
  <div class="row" style="padding-bottom: 10px;" >
    <div class="form-group col-sm-7 form-md-line-input has-personalizado form-md-floating-label">
      <label class = "control-label">
        {{type}}
      </label>
      <select class="form-control "   v-model="selectedChoose" style="border-bottom: 2px solid rgb(87, 142, 190);">
        <option v-for="(item, index)  in data" v-bind:value="index"  :selected="selectedChoose == 0 ? 'selected' : ''">
          {{ item }}
        </option>
      </select>
    </div>
    <div class="form-group col-sm-5">
      <div class="clearfix" style="margin-top: 40px"></div>

      <span  class="btn blue-madison " v-on:click="handleSendMessage">
        <i class="fa fa-plus-circle"></i>
        Inserir {{type}} 
      </span>
    </div>
  </div>
</template>

<template id="table-servicos-template">
  <table class="table table-responsive "  v-if="items.length">
   <tbody>
    <tr>
      <th></th> 
      <th  style="min-width: 150px;" > <i class="fa fa-briefcase"></i> Serviço</th> 
      <th>Tipo</th> 
      <th style="min-width: 100px">Franquia</th>
      <th style="min-width: 100px">Cobrança</th>
      <th style="min-width: 100px">Quantidade</th>
      <th style="min-width: 100px"> <i class="fa fa-dollar" ></i>  Desconto</th>
      <th style="min-width: 100px"> <i class="fa fa-shopping-cart"></i> Valor</th>
    </tr>
  </tbody>
  <tbody v-for="(item, index)  in items">
   <tr style="display: none " >
    <td colspan="9">
      {{item}}
    </td>
  </tr>
  <tr>
    <td>
      <a v-on:click="removerItem(index)" class="btn btn-outline btn-sm red">
        <i class="fa fa-remove"></i> Remover
      </a>
    </td>
    <td>
      <strong>Cod: {{item.item_id}}</strong>  <?php /* Cód. Serviço */ ?>
      -
      {{item.descricao}}
    </td> <?php /* Serviço */ ?>
    <td>
      <select class="form-control" v-if="item.tipo_conta" v-model="item.tipo_conta"  style="min-width: 120px">
        <option v-for="(itemTi, indexCont)  in item.tipos_conta" v-bind:value="itemTi"  :selected="item.tipo_conta == itemTi ? 'selected' : ''">
          {{ itemTi }}
        </option>
      </select>
    </td>  <?php /* Tipo */ ?>
    <td class="text-center">
      <select class="form-control" v-if="item.franquias.length>0" v-model="item.franquia" v-on:change="changeFranquia(item)"   v-on:change="trocaFranquias(item)" >
        <option v-for="(itemFr, indexCont)  in item.franquias" v-bind:value="itemFr" >
          {{ itemFr.name }}
        </option>
      </select>
      <label  class="label-control " v-if="item.franquias.length==0">Não Disponível</label>
    </td>  <?php /* Franquia */ ?>
    <td>
      <label class="label-control">{{item.cobranca}}</label>
    </td>  <?php /* Cobrança */ ?>
    <td>
      <input class="form-control" type="number" min='1' step="1" v-model="item.quantidade"  />  
    </td>  <?php /* Quantidade */ ?>
    <td>
      <input class="form-control" type="number" :min="0" step="0.001" v-model="item.desconto" />
    </td>  <?php /* Desconto */ ?>
    <td>
      <input class="form-control" type="number" :min="item.vlr_unitario_fix" step="0.01" v-model="item.vlr_unitario"  />
    </td>  <?php /* Valor */ ?>
  </tr>
  <tr >
   <td colspan="5" class="text-center">

    <span  v-for="(itemErro, indexCont)  in item.error" class="font-red-sunglo" >{{itemErro}} </span>
  </td>
  <td>
  </td>
  <td colspan="2" class="text-right">
    <strong v-if="items.length==1" > Total: </strong>
    <strong v-else> Subtotal: </strong>
    <span>R$ {{totalItem(item)}}</span>  
  </td>
</tr>
</tbody>
<tbody>
  <tr v-if="items.length>1" >
    <td colspan="6">
    </td>
    <td colspan="2">
      <strong class="total-venda-vue">Total: </strong>
      <span class="total-venda-vue">R$ {{totalAll()}}</span>  
    </td>
  </tr>
</tbody>
</table>
</template>

<script type="text/javascript">
  Vue.component('custom-select', {
    template: '#select-template',
    props: ['name','data','type'],
    data: function () {
      return { 
        items: [],
        selectedChoose: '0'
      }
    },
    methods: {
      handleSendMessage: function (){
        this.$emit('message',{ selected: this.selectedChoose , type: this.type });
      }
    }
  });

  Vue.component('custom-servicos-table', {
    template: '#table-servicos-template',
    props: ['name','items'],
    data: function () {
      return {};
    },
    created:function () {
    },
    methods: {
      removerItem: function (index){
        this.items.splice(index, 1);
      },
      changeFranquia: function (item){
        var item_franquia_valor =  item.franquia.valor.toString().split('.');
        item.franquia_aberta = 0;
        item.franquia_local = 0;
        if(item.franquia.tipo =='local'){
          item.franquia_local = item_franquia_valor[0];
          item.franquia_aberta = 0;
        }else if(item.franquia.tipo =='aberta'){
          item.franquia_aberta = item_franquia_valor[0];
          item.franquia_local = 0;
        }

      },
      totalItem: function (item){
        var vlr_total = 0;

        item.vlr_total = (( (item.vlr_unitario -item.desconto) * item.quantidade)).toFixed(3);

        return item.vlr_total.toString().replace(".", ",");
      },
      totalAll: function (){
        var i = this.items.length;
        var total = 0.00;
        for ( i - 1; i >= 0; i--) {
         if(this.items[i]!== undefined){
          total = total + parseFloat(this.items[i].vlr_total); 
        }
      }
      return total.toFixed(3).toString().replace(".", ",");
    }
  }
});

  var vm = new Vue({
    el: '#app',
    data: {
      init: 0,
      fault: 0,
      component:[],
      servicos:[],
      venda:[],
      ajaxResponse:false,
      ajaxResponseSubmit:false
    },
    created:function () {
     axios.get('<?php echo e(route('admin.vendas.faturas.customers.produto.servicos',$idVenda)); ?>').then(response => {
      this.component = response.data.rescolher;
      this.servicos = response.data.vendaItems.servico;
      this.venda = response.data.venda;
      if(this.servicos.length>0){
        this.init = 1
      }else{
        this.fault = 1
      }

    });
   },
   methods:
   {
    addItem: function (data) {
      /* if else previne bug duplo click: evita adidionar duas vezes */
      if(!this.ajaxResponse){
        this.ajaxResponse = true;

        /* destrava ajax após 1,5 segundo */
        setTimeout(function(){if(vm.ajaxResponse==true){vm.ajaxResponse = false}}, 1500);

        /* Verifica se selected esta preenchido */
        data.valid =  (data.selected !='' &&  data.selected !=0);

        if(data.valid){

          /* Verifica se existe um item_id já adicionado */
          var i = this.servicos.length;
          var ajax = true;
          for (i - 1; i >= 0; i--) {
           /* Verifica se o objeto existe */
           if(this.servicos[i] !== undefined ){
            if(this.servicos[i].item_id == data.selected){
              ajax = false;
              break;
            }
          }
        }

        if(ajax){
         axios.get('<?php echo e(route('admin.vendas.faturas.customers.produto.servicos.add')); ?>?id='+data.selected).then(response => {
          this.servicos.push(response.data.servico);
          this.ajaxResponse = false;
        });
       }
     }
     /* if else previne bug duplo click: adidionar duas vezes */
   }else{
    this.ajaxResponse = false;
  }
},
submit: function (){
  /* if else previne bug duplo click: evita adidionar duas vezes */
  if(!this.ajaxResponseSubmit){
    this.ajaxResponseSubmit = true;
    /* destrava ajax após 1,5 segundo */
    setTimeout(function(){if(vm.ajaxResponseSubmit==true){vm.ajaxResponseSubmit = false}}, 1500);

    var meta = document.querySelector("#_token").value;
    var error = [], errorLog = '', message = [],messageLog = '' ;

    var params = { servicos: this.servicos, venda: this.venda };
    /* Inicio Ajax */
    axios.post('<?php echo e(route('admin.vendas.faturas.customers.produto.servicos.post')); ?>', params, "headers: {'X-CSRF-TOKEN':"+meta+" }").then(
      response => {

        /* Não altera os serviços se a resposta não conte-los */
        if(response.data.servicos.length>0){
          this.servicos = response.data.servicos;
        }

        /* Inicio Resposta da validação do php*/
        if(response.data.error.length>0){
         error = response.data.error;
         if(error.length>0){
          for (var i = error.length - 1; i >= 0; i--) {
            errorLog = errorLog + error[i] +'<br>';
          }

          alert_error_vue(errorLog);
        }
      } else if(response.data.message.length>0){
       message = response.data.message;

       if(message.length>0){
         for (var i = message.length - 1; i >= 0; i--) {
           messageLog = messageLog + message[i] +'<br>';
         }
         alert_success_vue(messageLog);
         $("#openModal").modal("hide");
       }
     }
     /* Fim Resposta da validação do php*/

   }).catch(error => {
    console.log(error);
    alert_error_vue('Erro: Pedido falhou');
  });
   /* Fim Ajax */
 }

}
}
});

  function alert_error_vue(text) {
    swal({
      title: "",
      type: "warning",
      text: text,
      confirmButtonClass: "btn-danger",
      html: true,
      dangerMode: true,
      customClass: 'sweet-order-custom'
    });
  }

  function alert_success_vue(text) {
    swal({
      title: "",
      type: "success",
      text: "<strong>"+text+"</strong>",
      confirmButtonClass: "btn-success",
      html: true,
      dangerMode: true,
      customClass: 'sweet-order-custom'
    },
    function(isConfirm) {
      window.location.href = '<?php echo e(route("admin.vendas.faturas.customers.contrato",["id" => $customer[0]->id])); ?>';
    });
  }

</script>