<template>
  <div>
    <div>
      <b-row class="mb-3">
        <b-col>
          <div class="text-left mb-1 akkurat-regular">Cadastro:</div>
          <div class="profile-card px-2 pt-3 pb-0">
            <b-form>
              <b-form-row class="custom-form-row mb-3">
                <b-form-group class="col-md-4 col-sm-12">
                  <cpf :disabled="campaign_code == null && false" v-model="cpf" :submit="submit" />
                </b-form-group>

                <b-form-group class="col-md-4 col-sm-12">
                  <phone-number :disabled="campaign_code == null && false" v-model="mobilePhone" :submit="submit" />
                </b-form-group>

                <b-form-group class="col-md-4 col-sm-12">
                  <phone-number :disabled="campaign_code == null && false" title="Telefone 2" v-model="residentialPhone" :submit="submit" />
                </b-form-group>
              </b-form-row>
            </b-form>
          </div>
        </b-col>
      </b-row>
      <b-row class="my-2">
        <b-col class="d-flex justify-content-center align-items-center">
          <signup-button
            :loading="loading"
            title="Continuar"
            icon="user-friends"
            btn-color="#278937"
            @clicked="done"
            class="align-self-center"
          />
        </b-col>
      </b-row>
    </div>
    <accept-credit-card @response="response"></accept-credit-card>
    <message-modal :message="message"></message-modal>
  </div>
</template>

<script>
import Cpf from "@/components/shared-components/inputs/Cpf.vue";
import SignupButton from "@/components/signup/SignupButton.vue";
import PhoneNumber from "@/components/shared-components/inputs/PhoneNumber.vue";
import SalesConsultantsWebService from "@/services/resources/SalesConsultantsWebService";
import CampaignCalendarService from "@/services/resources/CampaignCalendarService";
import ConsultaSpcService from "@/services/resources/ConsultasSPCService";
import CreditAnalysisService from "@/services/resources/CreditAnalysisService";
import AcceptCreditCard from "@/components/modals/AcceptCreditCard.vue";
import MessageModal from "@/components/modals/MessageModal.vue";
import moment from "moment";

const service = SalesConsultantsWebService.build();
const serviceCalendar = CampaignCalendarService.build();
const consultaSpcService = ConsultaSpcService.build();
const creditAnalysisService = CreditAnalysisService.build();

import { validationCPF } from "@/utils/validation.js";
import {toHTMLErrorsByValidatorLaravel } from "@/utils/requests.js";
export default {
  name: "signup-form",
  components: {
    Cpf,
    PhoneNumber,
    SignupButton,
    AcceptCreditCard,
    MessageModal
  },
  data: () => ({
    cpf: "",
    mobilePhone: "",
    residentialPhone: "",
    campaign_code: null,
    message: "",
    submit: false,
    loading: false,
    idConsultaSPC: 0,
    credit_limit: 0
  }),
  computed: {
    isValid() {
      return;
    }
  },
  methods: {
    done() {
      if (
        !validationCPF(this.cpf) ||
        this.mobilePhone.length < 10 ||
        this.residentialPhone.length < 10
      ) {
        this.submit = true;
        return;
      }
      var vm = this;
      let data = {
        cpf: this.cpf,
        cellphone: this.mobilePhone,
        residencial: this.residentialPhone,
        campaign_code: this.campaign_code,
        new_sales_consultant: true,
      };
      vm.loading = true;

      consultaSpcService
        .create(data)
        .then(response => {
          vm.loading = false;
          vm.idConsultaSPC = response.id;
          vm.creditAnalysis();
        })
        .catch(err => {
          let resp = JSON.parse(err.response.data);
          vm.loading = false;

          console.log(err);
          vm.$fire({
            title:  resp.msg,
            type: "error",
            html:toHTMLErrorsByValidatorLaravel(resp.data)
          });
        });
      /**
       * Apagar Após teste
       */
      return;
    /*  service
        .create(data)
        .then(response => {
          if (typeof response.msg != "undefined") {
            this.message = "Esta consultora já está cadastrada!";
            this.$bvModal.show("message-modal");
          } else if (
            typeof response.spc != "undefined" &&
            response.spc == "BOL"
          ) {
            this.verifyPhone(false);
          } else if (
            typeof response.spc != "undefined" &&
            response.spc == "CC"
          ) {
            this.$bvModal.show("accept-credit-card");
          }
          vm.loading = false;
        })
        .catch(err => {
          vm.loading = false;
          let resp = JSON.parse(err.response.data);
          vm.$fire({
            title: "Falha ao salvar dados",
            type: "error",
            text: resp.msg
          });
          console.log(err);
        });*/
    },
    creditAnalysis() {
      var vm = this;

      this.loading = true;
      creditAnalysisService
        .create({
          consulta_spc_id: this.idConsultaSPC
        })
        .then(response => {
          vm.loading = false;
          if(response.data.credit_limit > 0){
            vm.credit_limit = response.data.credit_limit;
            vm.toNextStep();
          }else{
            vm.$bvModal.show("accept-credit-card");
          }

        })
        .catch(err => {
          let resp = err.response.data;
          console.error(err);

          vm.$fire({
            title: "Falha na Análise de crédito.",
            type: "error",
            text: resp.msg
          });

          vm.loading = false;
        });
    },
    toNextStep(){

        let data = {
            cpf: this.cpf,
            mobilePhone: this.mobilePhone,
            residentialPhone: this.residentialPhone,
            spc_restrition: this.credit,
            campaign_code: this.campaign_code
          };

          localStorage.step_1 = JSON.stringify(data);

          this.$router.push({
            name: "Dados Pessoais"
          });

    },
    response(answer) {
      if (answer) {
        this.toNextStep();
      } else {
        this.message = "Infelizmente seu cadastro não pode ser concluído.";
        this.$bvModal.show("message-modal");
      }
    },
   /* verifyPhone(spc_restrition) {
      let data = {
        step: "verify-cellphone",
        cellphone: this.mobilePhone,
        cpf: this.cpf
      };

      service
        .create(data)
        .then(response => {
          let data = {
            cpf: this.cpf,
            mobilePhone: this.mobilePhone,
            residentialPhone: this.residentialPhone,
            spc_restrition: spc_restrition,
            campaign_code: this.campaign_code
          };

          localStorage.step_1 = JSON.stringify(data);

          this.$router.push({
            name: "Dados Pessoais"
          });
        })
        .catch(err => {
          console.log(err);
        });
    },*/
    //Buscar Campanha de Cadastro
    loadCampains() {
      let data = {
        register_in_date: new moment().format("YYYY-MM-DD H:mm:ss")
      };
      var vm = this;
      this.loading = true;
      serviceCalendar
        .search(data)
        .then(response => {
          if (response.length == 0) {
            vm.$fire({
              title: "Não há campanha ativa para cadastro!",
              type: "error",
              text: "Verifique o calendário para maiores informações"
            });
          vm.loading = false;
          vm.$router.go(-1);
            return;
          }

          this.campaign_code = response[0].campaign.code;
          vm.loading = false;
        })
        .catch(err => {
          console.log(err);
          vm.$fire({
            title: "Falha ao consultar campanhas!",
            type: "error",
            text: "Erro 500"
          });
          vm.loading = false;
        });
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      console.log(from, next);
    });
  },
  mounted() {
    this.loadCampains();
    localStorage.removeItem("step_1");
    localStorage.removeItem("step_2");
    localStorage.removeItem("step_3");
    localStorage.removeItem("step_4");
  }
};
</script>

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