{% extends "base.html" %}
{% load widget_tweaks %}

{% block title %}Timbres{% endblock title %}

{% block titlePage %}
Timbres disponibles Comercio Digital: {{saldo}}
{% endblock titlePage %}

{% block content %}
<div class="table-responsive-sm">
  <table class="table">
      <thead>
        <tr>
          <th scope="col">
            <input id="table_rfcc" name="rfcc" value="True" type="checkbox" class="form-check-input" >
            Cliente RFC
          </th>
          <th>Nombre</th>
          <th>
            <div class="d-flex align-items-center"> 
              <div class="">
                <a  data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
                Total x mes
                </a> 
                
                  <small>
                    <strong>
                      Filtrado: Mes:{{mes}}, Año:{{year}}, PAC:<label id="lbl_pac"></label>
                    </strong>
                  </small>
                
              </div>        
              <div style="display:none;" id="spinner_id" class="spinner-border ml-auto spinner-border-sm" role="status" aria-hidden="true"></div>
            </div>
            <div class="collapse" id="collapseExample">
              <div class="card card-body">
                <!--PACS-->
                <select id="table_select_PAC" class="form-control form-control-sm my_event_cls">
                  <option value="00">Todos</option>
                  <!--option value="01">EDICOM</option-->            
                </select>
                <!--ANIOS-->
                <select style="display:inline" id="table_select_anio" class="form-control form-control-sm">
                  <!--option value="0"></option-->
                </select>                
                <!--MESES-->
                <select id="table_select" class="form-control form-control-sm">
                  <option value="01">Enero</option>
                  <option value="02">Febrero</option>
                  <option value="03">Marzo
                  </option>
                  <option value="04">Abril
                  </option>
                  <option value="05">Mayo
                  </option>
                  <option value="06">Junio
                  </option>
                  <option value="07">Julio
                  </option>
                  <option value="08">Agosto
                  </option>
                  <option value="09">Septiembre
                  </option>
                  <option value="10">Octubre
                  </option>
                  <option value="11">Noviembre
                  </option>
                  <option value="12">Diciembre
                  </option>
                </select>    
              </div>
            </div>            
          </th>
          <th>Estado</th>
          <th scope="col">
            <a target="_blank" rel="noopener noreferrer" href="{% url 'export_Excel' %}?mes={{mes}}">Excel Todos los clientes X Mes </a>
          </th>
        </tr>
      </thead>
      <tbody>
        {% for obj in lista %}
          <tr class="{% if not obj.Activo %}table-danger{% endif %}">
              <td >
                <a  href="{% url 'update_cliente' obj.pk %}">{{obj.RFC}}</a>
              </td>
              <td>{{obj.Nombre}} </td>
              <td>
                {{obj.conteo_mes}}
              </td>

              <td>
                {% if obj.Activo %}
                  Activo
                {% else %}
                  Inactivo
                {% endif %}
              </td>

              <td>
                  {% if request.user.is_staff %}
                    <div class="btn-group">
                      <button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Acciones
                      </button>
                      <div class="dropdown-menu">
                        
                        <a class="btn btn-outline-info w-100" href="{% url 'timbres_cliente' obj.RFC|urlencode %}" >
                          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-eye" viewBox="0 0 16 16">
                            <path d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8zM1.173 8a13.133 13.133 0 0 1 1.66-2.043C4.12 4.668 5.88 3.5 8 3.5c2.12 0 3.879 1.168 5.168 2.457A13.133 13.133 0 0 1 14.828 8c-.058.087-.122.183-.195.288-.335.48-.83 1.12-1.465 1.755C11.879 11.332 10.119 12.5 8 12.5c-2.12 0-3.879-1.168-5.168-2.457A13.134 13.134 0 0 1 1.172 8z"/>
                            <path d="M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5zM4.5 8a3.5 3.5 0 1 1 7 0 3.5 3.5 0 0 1-7 0z"/>
                          </svg>
                          Ver Timbres
                        </a>
                        <div class="dropdown-divider"></div>

                        <button class="btn btn-outline-secondary w-100" id ="id_b_{{obj.RFC}}" onclick="aclick(event, '{{obj.RFC}}','{{obj.conteo_mes}}')">
                          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-cloud-download" viewBox="0 0 16 16">
                            <path d="M4.406 1.342A5.53 5.53 0 0 1 8 0c2.69 0 4.923 2 5.166 4.579C14.758 4.804 16 6.137 16 7.773 16 9.569 14.502 11 12.687 11H10a.5.5 0 0 1 0-1h2.688C13.979 10 15 8.988 15 7.773c0-1.216-1.02-2.228-2.313-2.228h-.5v-.5C12.188 2.825 10.328 1 8 1a4.53 4.53 0 0 0-2.941 1.1c-.757.652-1.153 1.438-1.153 2.055v.448l-.445.049C2.064 4.805 1 5.952 1 7.318 1 8.785 2.23 10 3.781 10H6a.5.5 0 0 1 0 1H3.781C1.708 11 0 9.366 0 7.318c0-1.763 1.266-3.223 2.942-3.593.143-.863.698-1.723 1.464-2.383z"></path>
                            <path d="M7.646 15.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 14.293V5.5a.5.5 0 0 0-1 0v8.793l-2.146-2.147a.5.5 0 0 0-.708.708l3 3z"></path>
                          </svg>
                          Excel
                        </button>
                        <a style="display: none;" id="id_a_{{obj.RFC}}" target="_blank" rel="noopener noreferrer" href="{% url 'export_Excel' %}?RFC={{obj.RFC}}&mes={{mes}}">
                          Excel
                        </a>
                        <div class="dropdown-divider"></div>


                        <a class="btn btn-info w-100" href="{% url 'send_timbres_Email' %}?RFC={{obj.RFC}}&mes={{mes}}" >
                          <div>
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-envelope-at" viewBox="0 0 16 16">
                              <path d="M2 2a2 2 0 0 0-2 2v8.01A2 2 0 0 0 2 14h5.5a.5.5 0 0 0 0-1H2a1 1 0 0 1-.966-.741l5.64-3.471L8 9.583l7-4.2V8.5a.5.5 0 0 0 1 0V4a2 2 0 0 0-2-2H2Zm3.708 6.208L1 11.105V5.383l4.708 2.825ZM1 4.217V4a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v.217l-7 4.2-7-4.2Z"/>
                              <path d="M14.247 14.269c1.01 0 1.587-.857 1.587-2.025v-.21C15.834 10.43 14.64 9 12.52 9h-.035C10.42 9 9 10.36 9 12.432v.214C9 14.82 10.438 16 12.358 16h.044c.594 0 1.018-.074 1.237-.175v-.73c-.245.11-.673.18-1.18.18h-.044c-1.334 0-2.571-.788-2.571-2.655v-.157c0-1.657 1.058-2.724 2.64-2.724h.04c1.535 0 2.484 1.05 2.484 2.326v.118c0 .975-.324 1.39-.639 1.39-.232 0-.41-.148-.41-.42v-2.19h-.906v.569h-.03c-.084-.298-.368-.63-.954-.63-.778 0-1.259.555-1.259 1.4v.528c0 .892.49 1.434 1.26 1.434.471 0 .896-.227 1.014-.643h.043c.118.42.617.648 1.12.648Zm-2.453-1.588v-.227c0-.546.227-.791.573-.791.297 0 .572.192.572.708v.367c0 .573-.253.744-.564.744-.354 0-.581-.215-.581-.8Z"/>
                            </svg>
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-send" viewBox="0 0 16 16">
                              <path d="M15.854.146a.5.5 0 0 1 .11.54l-5.819 14.547a.75.75 0 0 1-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 0 1 .124-1.33L15.314.037a.5.5 0 0 1 .54.11ZM6.636 10.07l2.761 4.338L14.13 2.576 6.636 10.07Zm6.787-8.201L1.591 6.602l4.339 2.76 7.494-7.493Z"/>
                            </svg>
                          </div>
                          Email Timbres
                        </a>
                        <div class="dropdown-divider"></div>

                        <!-- Button trigger modal -->
                        <button class="btn btn-primary w-100" onclick="addValues('{{obj.RFC}}'); retriveEmails('{{obj.RFC}}');" type="button" data-toggle="modal" data-target="#exampleModalCenter">
                          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-envelope-plus" viewBox="0 0 16 16">
                            <path d="M2 2a2 2 0 0 0-2 2v8.01A2 2 0 0 0 2 14h5.5a.5.5 0 0 0 0-1H2a1 1 0 0 1-.966-.741l5.64-3.471L8 9.583l7-4.2V8.5a.5.5 0 0 0 1 0V4a2 2 0 0 0-2-2H2Zm3.708 6.208L1 11.105V5.383l4.708 2.825ZM1 4.217V4a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v.217l-7 4.2-7-4.2Z"/>
                            <path d="M16 12.5a3.5 3.5 0 1 1-7 0 3.5 3.5 0 0 1 7 0Zm-3.5-2a.5.5 0 0 0-.5.5v1h-1a.5.5 0 0 0 0 1h1v1a.5.5 0 0 0 1 0v-1h1a.5.5 0 0 0 0-1h-1v-1a.5.5 0 0 0-.5-.5Z"/>
                          </svg>
                          Enviar Email
                        </button>
                      </div>
                    </div>
                  {% endif %}
              </td>
          </tr>          
        {% endfor %}
        
      </tbody>
  </table>
</div>

<div id='id_filters' style="display: none;">{% for i,v in filters.items %}&{{i}}={{v}}{% endfor%}</div>
<!-- Modal EMAIL-->
<div class="modal fade" data-backdrop="static" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <form enctype="multipart/form-data" id="id_form" action="{% url 'send_timbres_Email' %}?mes={{mes}}{% for i,v in filters.items %}&{{i}}={{v}}{% endfor%}" method="post">
    {% csrf_token %}
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalCenterTitle">Enviar Email</h5>
          <button id="cerrar2" type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="email"><strong>Email</strong></label>
            <!--input type="email" name="email" id="email_add" autocomplete="off" class="form-control" placeholder="Email"-->

            <div class="input-group mb-3">
              <input type="email" name="email" id="email_add" class="form-control" placeholder="Email" aria-label="Email" aria-describedby="button-addon2">
              <div class="input-group-append">
                <button class="btn btn-outline-secondary" type="button" data-toggle="modal" data-target="#exampleModalCenter2" id="button-addon2" >
                  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-search" viewBox="0 0 16 16">
                    <path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/>
                  </svg>
                </button>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label for="subject"><strong> Subject </strong></label>
            <input type="text" name="subject" maxlength="100" id="subject_add" autocomplete="off" class="form-control" placeholder="Subject">
          </div>
          <div class="form-group">
            <label for="adjunto"><strong>Adjunto</strong></label>
            <!--input type="file" name="adjunto" multiple="" id="adjunto_add" autocomplete="off" class="form-control" placeholder="Adjunto"-->
            {{emailForm.adjunto}}
          </div>
          <div class="form-group">
            <label for="message"><strong>Message</strong></label>
            <textarea name="message" cols="40" rows="10" id="message_add" autocomplete="off"  class="form-control" placeholder="Message" required></textarea>
          </div>
          <div hidden class="form-group">
            <label for="RFC"><strong> Rfc </strong></label>
            <input  type="text" name="RFC" maxlength="13" id="RFC_add" autocomplete="off" class="form-control" placeholder="RFC" required>
          </div>
          <div hidden class="form-group">
            <label for="mes"><strong> Mes </strong></label>
            <input  type="text" name="mes" maxlength="2" value="{{mes}}" id="mes_add" autocomplete="off" class="form-control" placeholder="Mes" required>
          </div>
        </div>

        <div class="modal-footer">
          <button id="cerrar1" type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
          <button id="enviar_btn" type="submit" class="btn btn-primary">
            <span id="spinner_enviar" style="display:none;" class="spinner-grow spinner-grow-sm" role="status" aria-hidden="false"></span>
            Enviar
          </button>
        </div>
      </div>
    </div>
  </form>
</div>

<!-- Modal LISTA EMAILS-->
<div class="modal fade bd-example-modal-lg"  id="exampleModalCenter2" tabindex="-1" role="contentinfo" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalCenterTitle">Lista email</h5>
        <button id="close_emails_list" type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="table-responsive">
          <table id="email_list" class="table table-hover">
            <thead>
              <tr>
                <th scope="col">EMAIL</th>
              </tr>
            </thead>
            <tbody id="table_body" style="cursor: pointer;">
              <!--This is a exaple append js rows structure---->
              <!--tr class="table_row"><td id="1">@Mark</td></tr-->                
            </tbody>
          </table>
        </div>
      </div>
      <div class="modal-footer">
        <h1>Footer</h1>
      </div>
    </div>
  </div>
</div>
{% endblock content %}

{% block scripts %}
<script>
  
  function retriveEmails(RFC){    
    fetch(`{% url 'Retrive_Cliente_Email' %}?RFC=${RFC}`,{
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With':'XMLHttpRequest',
      },
      credentials:"same-origin"      
    })
    .then(res=>{
      return res.json()
    })
    .then(data=>{
      
      if(table_body.querySelectorAll('tr').length >0){
        const table_rows = document.querySelectorAll('.table_row')
        table_rows.forEach((rem)=>{
          rem.remove()
        })
      }
      const re = Object.values(data['data'])
      re.forEach((val,index)=>{ 
             
         const row = document.createElement("tr")
         row.setAttribute("class","table_row")
         const cell = document.createElement("td")
         cell.setAttribute("id",index)
         const cellText = document.createTextNode(`${val.email}`)
         cell.appendChild(cellText)
         row.appendChild(cell)
         
         table_body.appendChild(row)          
      })
               
      email_list.appendChild(table_body) 
      const table_rows = document.querySelectorAll('.table_row')
      table_rows.forEach((box)=>{
        box.addEventListener('click',(event)=>{          
          email_add.value=event.target.textContent
          close_emails_list.click()
        })
      })
    })//.then(data)
  }

  let filters = document.getElementById('id_filters').textContent
  let mes ='{{mes}}'
  let year = parseInt('{{year}}')
  let anc = document.getElementById('home_id')
  let PAC = Object.values(filters.split('&'))
  PAC.filter(val=>{
    lbl_pac.innerHTML="Todos"
    if(val.length >0){
      lbl_pac.innerHTML=  val.split('=')[1]=="" ? "Todos" :val.split('=')[1]
    }
  })

  
  
  /*-------------------------Carga los pacs*/
  fetch("{% url 'PACS_Retrive_RFCS' %}",{
    method:'GET',
    headers:{
      'Content-Type':'application/json',
      'X-Requested-With':'XMLHttpRequest',
    },
    credentials:"same-origin"
  })
  .then(res=>{
    return res.json()
  })
  .then(data=>{
    let pacs = [...new Set(data['PACS'].map((arr)=>arr.rfcp) )]
    
    pacs.forEach((val,index)=>{          
      let option = document.createElement('option')
      option.value=val
      option.text=val
      table_select_PAC.add(option)
      PAC.filter(val=>val.includes('PAC'))
      .forEach((val,index)=>{
        table_select_PAC.value = val.split('=')[1]
      })
    })
  })
  .catch(error=>{
    console.log(error)
  })
  /*----------------------fin carga pacs*/

  function aclick(event,RFC ,cuantos){

    if( parseInt(cuantos)===0){

      alert(`No hay timbres de este mes para el cliente ${RFC}`)
    }else{
      document.getElementById(`id_a_${RFC}`).click()
    }
  }

  table_rfcc.addEventListener('click',(event)=>{
    document.getElementById('rfcc').checked= table_rfcc.checked? true:false;    
  })
  
  window.addEventListener("load", (event)=>{
//    let mes ='{{mes}}'
    
    mes.length == 1 ? mes="0"+mes: mes
    if(mes !="None"){
      document.getElementById('table_select').value=mes
      mes_id.value=mes
    }else{
      document.getElementById('table_select').value='{{fecha|date:"m"}}'
      mes_id.value='{{fecha|date:"m"}}'
    }
    
    
    /*Add years to select anio tag*/
    
    let anio = parseInt('{{fecha|date:"Y"}}')
    
    let fin = anio-5
    for(var i = anio; i >= fin ;i--){      
      let option = document.createElement('option')
      option.value=i
      option.text=i
      table_select_anio.add(option)
    }
    /*despues de agregar los anios al control agrega el value del contexto*/
    table_select_anio.value=year

  })

  document.getElementById('table_select').addEventListener('change',(event)=>{
    spinner_id.setAttribute('style','display:inline;')
    
    
    anc.href=''
    
    let url = `?mes=${event.target.value}&year=${year}${filters}`
    
    setTimeout(()=>{
      anc.href=url
      anc.click()
    },1000)
    
  })

  table_select_anio.addEventListener('change',(event)=>{
    spinner_id.setAttribute('style','display:inline;')
    
    
    anc.href=''
    
    let url = `?mes=${mes}&year=${event.target.value}${filters}`
    
    setTimeout(()=>{
      anc.href=url
      anc.click()
    },1000)
  })

  table_select_PAC.addEventListener('change',(event)=>{
    spinner_id.setAttribute('style','display:inline;');
    anc.href='';
    let url =`?mes=${mes}&year=${year}&PAC=${event.target.value}`
    setTimeout(()=>{
      anc.href=url
      anc.click()
    },1000)
  
  })
  
  enviar_btn.addEventListener('click',(e)=>{

    if(id_form.checkValidity()){
      //
      spinner_enviar.removeAttribute('style');
      
    }
  })

  id_adjunto.addEventListener('change',(e)=>{
    if(id_adjunto.files.length){
      let fsize;

      for (var i =0; i<= id_adjunto.files.length-1; i++){
        fsize = id_adjunto.files.item(i).size

        fsize +=fsize;
        
        if( 25 <= ((fsize/1024)/1024) ){
          alert('Limite excedido de 25 MegaBytes adjuntos');
          id_adjunto.value=''
          return false;
        }
      }
    }
  })
  cerrar1.addEventListener('click', (event)=>{
    id_form.reset()
  })
  cerrar2.addEventListener('click', (event)=>{
    id_form.reset()
  })

  function addValues(RFC){
    
    RFC_add.value = RFC
    
  }

</script>
{% endblock scripts %}