<template>
  <div>
  <b-modal id="telephone" :no-close-on-backdrop="true" size="lg">
    <template v-slot:modal-header="{  }">
      <b-container>
        <b-row class="d-flex justify-content-between mb-2 mt-1">
          <b-col class="d-flex modal-text-color ml-2" cols="8">
            <div class="d-flex align-self-center justify-content-center rounded-div mr-2 mt-1">
              <font-awesome-icon icon="exclamation-circle" class="align-self-center" />
            </div>
            <div class="pt-1">
              <div class="akkurat-bold max-header-text">Telefone</div>
            </div>
          </b-col>
          <b-col class="d-flex justify-content-end mr-2 mt-1">
            <span class="close-icon" @click="closeModal">
              <font-awesome-icon icon="times" class="align-self-center" />
            </span>
          </b-col>
        </b-row>
      </b-container>
    </template>
      <b-container>
        <b-row>
          <b-col cols="12" class="text-center">
            <h4 class="text-center">Histórico de ligações</h4>
          </b-col>
          <b-col cols="12">
          <b-table hover :items="historyCalls" :fields="fields" head-variant="dark" bordered="bordered" striped="striped" small="small">
              <template v-slot:cell(created_at)="data">
                {{ data.value | date }}
              </template>
              <template v-slot:cell(contact)="data">
                {{ data.item.contact.ddd }} {{ data.item.contact.number }}
              </template>
              <template v-slot:cell(confirmed)="data">
                {{ data.value ? 'Confirmado' : 'Não confirmado' }} 
              </template>
              <template v-slot:cell(user)="data">
                {{ data.item.user.name }} 
              </template>
          </b-table>
          </b-col>
        </b-row>
        <b-row class="justify-content-center mb-2">
            <b-form-group class="col-md-10 col-sm-12">
              <div class="text-left label"><label for="marketDefinition">Contatos:</label>
              </div>
              <b-form-select
                  v-model="selectedNumber"
                  :options="numbers"
                  id="marketDefinition"
                  class="radius-theme"
                />
            </b-form-group>
            <b-col cols="2">
               <div class="text-left label"><label>Ligar:</label>
              </div>
            <b-button
            @click="call"
              class="mr-2 btn shadow-none border-0 btn-default btn-theme text-white "
              >
              <font-awesome-icon icon="phone" class="align-self-center" />
            </b-button>
          </b-col>
        </b-row>

        <b-row>
          <b-col>
            <b-form-group >
              <b-form-checkbox v-model="confirmed" name="telephone" :value="true">Confirmado</b-form-checkbox>
            </b-form-group>
          </b-col>
        </b-row>

        <b-row>
          <b-col>
            <b-form-group >
              <label>Observação:</label>
               <b-form-textarea no-resize v-model="description">
                </b-form-textarea>
            </b-form-group>
          </b-col>
        </b-row>
      </b-container>

    <template v-slot:modal-footer="{  }">
      <b-container>
        <b-row>
          <b-col cols="12" class="d-flex justify-content-center my-3 px-3">
            <b-button
                class="mr-2 btn shadow-none border-0 btn-default btn-red"
                @click="closeModal"
              >
                Cancelar
            </b-button>
            
            <b-button
              class="mr-2 btn shadow-none border-0 btn-default"
              @click="done"
            >
              Salvar
            </b-button>
          </b-col>
        </b-row>
      </b-container>
    </template>
  </b-modal>

    <message-modal :message="message" :title="title"></message-modal>
  </div>
</template>

<script>
import SalesConsultantStatusService from "@/services/resources/SalesConsultantStatusService";
import PhoneCallService from "@/services/resources/PhoneCallService";
import MessageModal from '@/components/modals/MessageModal.vue';
import axios from 'axios';
import moment from "moment";

const service = PhoneCallService.build();

export default {
  name: 'accept-credit-card',
  props:{
    sales_consultant_id:{
      type: Number
    },
    contacts:{
      type: Array
    }
  },
  components:{
    MessageModal
  },
  data: () => ({
    title: 'Ligação',
    message: '',
    description: '',
    selectedNumber: -1,
    numbersList: [],
    confirmed: false,
    asterisk_protocol: null,
    historyCalls: [],
    fields:[
      {key: 'created_at', label: 'Data'},
      {key: 'contact', label: 'Número'},
      {key: 'confirmed', label: 'Status'},
      {key: 'observation', label: 'Observação'},
      {key: 'user', label: 'Analista'}
    ]
  }),
  methods: {
    closeModal() {
      this.$bvModal.hide('telephone');
    },
    call(){
      
      if(this.selectedNumber != -1){
        var ramal = this.ramal ? this.ramal : 0;
        var number = this.contacts[this.selectedNumber].ddd + this.contacts[this.selectedNumber].number;
        var url = 'http://server3.kingtelecom.com.br/api/adorata.php?action=originate&numero='+ number +'&ramal=' + ramal;

        axios
          .get(url)
          .then(response => {
            if(response.data.status == "ok"){
              this.message = 'A ligação foi feita.';
              this.$bvModal.show('message-modal');
              this.asterisk_protocol = response.data.id;
            }else{
              this.message = 'Houve um erro na realização da ligação.';
              this.$bvModal.show('message-modal');
            }
          }).catch(error => {
              this.message = 'Houve um erro na realização da ligação.';
              this.$bvModal.show('message-modal');
          });
      }

    },
    done(){
      if(this.selectedNumber != -1){
          let data = {
            sales_consultant_id: this.sales_consultant_id,
            contact_id: this.contacts[this.selectedNumber].id,
            observation: this.description,
            confirmed: this.confirmed,
            asterisk_protocol: this.asterisk_protocol
          };

          service
          .create(data)
          .then(response => {
            let object = {
              contact:{
                ddd: this.contacts[this.selectedNumber].ddd,
                number: this.contacts[this.selectedNumber].number,
              },
              user:{
                name: this.name
              },
              confirmed: this.confirmed,
              observation: this.description,
              created_at: moment()
            }
            this.historyCalls.push(object);
            this.description = '';
            this.closeModal();

          })
          .catch(err => {
            
          });
      }
    },
    load(){
      
      let data = {
        sales_consultant_id: this.sales_consultant_id
      };

      service
      .search(data)
      .then(response => {
        this.historyCalls = response;
      })
      .catch(err => {
        
      });
    }
  },
  filters:{
    date(date){
      return moment(date, "YYYY-MM-DD HH:mm:ss").format('DD/MM/YYYY HH:mm')
    }
  },
  computed:{
    name(){
      return this.$store.state.user.user.name;
    },
    ramal(){
      return this.$store.state.user.user.ramal;
    },
    numbers(){
      this.numbersList = [{text: 'SELECIONE UM CONTATO', value: -1}];
      this.contacts.forEach((element, index) => {
        this.numbersList.push({text: element.ddd + element.number, value: index});
      });

      return this.numbersList;
    }
  },
  mounted(){
    this.load();
  }
};
</script>

<style scoped lang="scss">
@import '../../../../../assets/css/main.scss';


.item-attachment{
  height: 150px;
  overflow: hidden;
  cursor: pointer;
}

.modal-text-color {
  color: #3E3E3E;
}

.min-header-text {
  letter-spacing: 0.2px;
  font-size: 9px;
}

.max-header-text {
  letter-spacing: 0.4px;
  font-size: 16px;
}


.close-icon {
  color: #979797;
  font-size: 20px;
}

.btn-default {
  border-radius: 20px;
  width: 100%;
  max-width: 192px;
  height: 35px;
  background: #278937;
}

.btn-red {
  background: #CB2D2D;
}

.btn-theme{
  background: $theme-color-blue;
}


</style>
