<template>
  <div>
    <card>
      <div class="row">
        <base-input class="col-6">
          <select
            class="form-control"
            @change="onChange()"
            v-model="selectedCreditoName"
          >
            <option v-for="Credito in Creditos">
              {{ Credito.nombreCredito }}
            </option>
          </select>
        </base-input>

        <base-button
          type="danger"
          icon
          size="sm"
          v-if="selectedCredito.nombreCredito !== ''"
          class="btn-link"
          @click="deleteCredito()"
        >
          <i class="el-icon-delete-solid"></i>
        </base-button>

        <div class="row pull-right pull-buttom">
          <div class="col-6">
            <Fcredito
              :newCredito="newCredito"
              :saveCredito="saveCredito"
              :isOpen="isOpen"
            />
          </div>
        </div>
      </div>
    </card>

    <card v-if="selectedCredito.nombreCredito !== ''">
      <table>
        <tr>
          <td><b>Credito:</b></td>
          <td>
            <span class="badge bg-Light">{{
              selectedCredito.nombreCredito
            }}</span>
          </td>
        </tr>

        <tr>
          <td><b>Valor Inicial:</b></td>
          <td>
            <span class="badge bg-Light">{{ formatMoneda(selectedCredito.valor) }}</span>
          </td>
        </tr>

        <tr>
          <td><b>Tasa Interés:</b></td>
          <td>
            <span class="badge bg-Light">{{ selectedCredito.tasa_interes }} %</span>
          </td>
        </tr>
      </table>
    </card>

    <card title="Credito" v-if="selectedCredito.nombreCredito !== ''">
      <div class="row">
        <div class="col-8">
          <el-table
            :data="selectedCredito.datos"
            border
            empty-text="No hay items"
            stripe
            style="width: 100%"
            height="300"
          >

            <el-TableColumn prop="fecha" label="Fecha" sortable>
            </el-TableColumn>

            <el-TableColumn prop="detalle" label="Detalle" sortable>
            </el-TableColumn>

            <el-TableColumn prop="valor" label="Valor" sortable>
            </el-TableColumn>

            <el-TableColumn prop="tipo" label="Tipo" sortable> </el-TableColumn>

            <el-TableColumn>
              <div slot-scope="{ row, $index }">
                <el-tooltip content="Delete" effect="light">
                  <base-button
                    type="danger"
                    icon
                    size="sm"
                    class="btn-link"
                    @click="deleteItem(row._id)"
                  >
                    <i class="el-icon-delete-solid"></i>
                  </base-button>
                </el-tooltip>
              </div>
            </el-TableColumn>
          </el-table>
        </div>

        <div class="col-4">
           <base-input
            label="Fecha"
            v-model="newItem.fecha"
            type="Date"
            required
          ></base-input>
          <base-input v-model="newItem.detalle" label="Descripción">
          </base-input>
          <base-input v-model="newItem.valor" type="Number"> </base-input>
          <base-input>
            <select class="form-control" v-model="newItem.tipo">
              <option>Cuota</option>
              <option>Abono Capital</option>
            </select>
          </base-input>
          <base-button
            type="info"
            class="mb-3 col-12"
            size="lg"
            @click="addItem()"
            >Guardar</base-button
          >
        </div>
      </div>
    </card>

    <card>
      <div class="row">
        <div class="col-4">
          <b>Total Cuotas: </b> {{ formatMoneda(totalCuotas) }}
        </div>
        <div class="col-4">
          <b>Total Abonos a Capital:</b> <span>{{ formatMoneda(totalAbonos) }} </span>
        </div>
        <div class="col-4">
          <b
            >Total:<span :class="[total < 0 ? 'text-danger' : 'text-success']">
              {{ formatMoneda(total) }}</span
            ></b
          >
        </div>
      </div>
    </card>
  </div>
</template>

<script>
import { Table, TableColumn } from "element-ui";

export default {
  components: {
    [Table.name]: Table,
    [TableColumn.name]: TableColumn,
  },
  middleware: "authenticated",
  data() {
    return {
      isOpen: false,

      newCredito: {
        nombreCredito: "",
        valor: 0,
        tasa_interes: 0.0,
      },
      selectedCredito: {
        _id: "",
        nombreCredito: "",
        valor: 0,
        tasa_interes: 0.0,
        datos: [],
      },
      selectedCreditoName: "",
      newItem: {
        _id: "",
        fecha:"",
        detalle: "",
        valor: 0,
        tipo: "Cuota",
      },

      Creditos: [],
      totalCuotas: 0,
      totalAbonos: 0,
      total: 0,
    };
  },
  methods: {
    saveCredito() {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
      };
      this.newCredito.nombreCredito = this.newCredito.nombreCredito.trim();
      const toSend = this.newCredito;
      this.$axios
        .post("/Credito", toSend, axiosHeader)
        .then((res) => {
          this.$notify({
            type: "success",
            icon: "tim-icons icon-check-2",
            message: "Credito Creado",
          });
          this.isOpen = false;
          this.getCredito();
        })
        .catch((e) => {
          this.$notify({
            type: "danger",
            icon: "tim-icons icon-alert-circle-exc",
            message: "El Credito ya existe :(",
          });
          return;
        });
    },
    addItem() {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
      };
      const toSend = this.newItem;
      this.$axios
        .put("/Credito", toSend, axiosHeader)
        .then((res) => {
          console.log(res.data.status);
          this.getItems();
        })
        .catch((e) => console.log(e));
    },
    deleteItem(item_id) {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
        params: {
          idCredito: this.selectedCredito._id,
          iditem: item_id,
        },
      };
      this.$axios
        .delete("/Creditoitem", axiosHeader)
        .then((res) => {
          this.getItems();
        })
        .catch((e) => console.log(e));
    },
    getItems() {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
        params: {
          credito_id: this.selectedCredito._id,
        },
      };
      this.$axios
        .get("/Credito_items", axiosHeader)
        .then((res) => {
          this.selectedCredito.datos = res.data.data;
          this.sumItems();
        })
        .catch((e) => console.log(e));
    },

    sumItems() {
      this.totalCuotas = this.selectedCredito.datos.reduce(
        (acc, x) => (x.tipo === "Cuota" ? acc + Number(x.valor) : acc),
        0
      );

      this.totalAbonos = this.selectedCredito.datos.reduce(
        (acc, x) => (x.tipo === "Abono Capital" ? acc + Number(x.valor) : acc),
        0
      );
      this.total = this.totalCuotas + this.totalAbonos;
    },
    formatMoneda(dato) {
      var num = dato;
      if (!isNaN(num)) {
        num = Math.abs(num)
          .toString()
          .split("")
          .reverse()
          .join("")
          .replace(/(?=\d*\.?)(\d{3})/g, "$1.");
        num = num.split("").reverse().join("").replace(/^[\.]/, "");
        return `$ ${num}`;
      }
    },
    getCredito() {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
          limite: this.$store.state.filtro.nCredito,
        },
      };

      this.$axios
        .get("/Credito", axiosHeader)
        .then((res) => {
          this.Creditos = [];
          if (res.data.data.length) {
            this.Creditos = res.data.data;
            this.selectedCredito = this.Creditos[0];
            this.selectedCreditoName = this.selectedCredito.nombreCredito;
            this.newItem._id = this.selectedCredito._id;
            console.log(this.selectedCredito);
            this.sumItems();
          }
        })
        .catch((e) => console.log(e));
    },
    onChange() {
      this.selectedCredito = this.Creditos.find(
        (x) => x.nombreCredito === this.selectedCreditoName
      );
      this.newItem._id = this.selectedCredito._id;
      this.sumItems();
    },
    deleteCredito() {
      console.log(this.selectedCredito._id);
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
        params: {
          id: this.selectedCredito._id,
        },
      };
      this.$axios
        .delete("/Credito", axiosHeader)
        .then((res) => {
          console.log(res.data);

          this.selectedCredito = {
            _id: "",
            nombreCredito: "",
            datos: [],
          };
          this.selectedCreditoName = "";
          this.getCredito();
        })
        .catch((e) => console.log(e));
    },
  },
  mounted() {
    this.getCredito();
    this.newItem.fecha = this.$store.state.fecha;
  },
};
</script>

<style>
</style>