<template>
  <div>
    <card>
      <div class="row">
        <base-input class="col-6">
          <select
            class="form-control"
            @change="onChange()"
            v-model="selectedAhorroName"
          >
            <option v-for="ahorro in ahorros">
              {{ ahorro.nombreAhorro }}
            </option>
          </select>
        </base-input>

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

        <div class="pull-right pull-buttom col-4">
          <div class="col-12">
            <Fahorro
              :newAhorro="newAhorro"
              :saveAhorro="saveAhorro"
              :isOpen="isOpen"
            />
          </div>
        </div>
      </div>
    </card>

    <card v-if="selectedAhorro.nombreAhorro !== ''">
      <table>
        <tr>
          <td>
            <span class="badge bg-Light">{{
              selectedAhorro.nombreAhorro
            }}</span>
          </td>
        </tr>
        <tr>
          <td>
            <span class="badge bg-Light">{{
              selectedAhorro.detalleAhorro
            }}</span>
          </td>
        </tr>
      </table>
    </card>
    <card v-if="selectedAhorro.nombreAhorro !== ''">
      <div class="row">
        <div class="col-8">
          <el-table
            :data="selectedAhorro.datos"
            border
            empty-text="No hay items"
            stripe
            style="width: 100%"
            height="300"
          >
            <el-TableColumn prop="detalle" label="Detalle" sortable>
            </el-TableColumn>

            <el-TableColumn
              prop="valor"
              label="Valor"
              sortable
              :formatter="cell"
            >
            </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 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>Aporte</option>
              <option>Retiro</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>Aportes: </b> {{ formatMoneda(totalAportes) }}
        </div>
        <div class="col-4">
          <b>Retiros:</b> <span>{{ formatMoneda(totalRetiros) }} </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,

      newAhorro: {
        nombreAhorro: "",
        detalleAhorro: "",
      },
      selectedAhorro: {
        _id: "",
        nombreAhorro: "",
        detalleAhorro: "",
        datos: [],
      },
      selectedAhorroName: "",
      newItem: {
        _id: "",
        detalle: "",
        valor: 0,
        tipo: "Aporte",
      },

      ahorros: [],
      totalAportes: 0,
      totalRetiros: 0,
      total: 0,
    };
  },
  methods: {
    cell(row, column, cellValue, index) {
      return this.formatMoneda(cellValue);
    },
    saveAhorro() {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
      };
      this.newAhorro.nombreAhorro = this.newAhorro.nombreAhorro.trim();
      const toSend = this.newAhorro;
      this.$axios
        .post("/ahorro", toSend, axiosHeader)
        .then((res) => {
          this.$notify({
            type: "success",
            icon: "tim-icons icon-check-2",
            message: "Ahorro Creado",
          });
          this.isOpen = false;
          this.getAhorro();
        })
        .catch((e) => {
          this.$notify({
            type: "danger",
            icon: "tim-icons icon-alert-circle-exc",
            message: "El ahorro ya existe :(",
          });
          return;
        });
    },
    addItem() {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
      };
      const toSend = this.newItem;
      this.$axios
        .put("/Ahorro", toSend, axiosHeader)
        .then((res) => {
          this.getItems();
        })
        .catch((e) => console.log(e));
    },
    deleteItem(item_id) {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
        params: {
          idAhorro: this.selectedAhorro._id,
          iditem: item_id,
        },
      };
      this.$axios
        .delete("/ahorroitem", axiosHeader)
        .then((res) => {
          this.getItems();
        })
        .catch((e) => console.log(e));
    },
    getItems() {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
        params: {
          ahorro_id: this.selectedAhorro._id,
        },
      };
      this.$axios
        .get("/ahorro_items", axiosHeader)
        .then((res) => {
          this.selectedAhorro.datos = res.data.data;
          this.sumItems();
        })
        .catch((e) => console.log(e));
    },

    sumItems() {
      this.totalAportes = this.selectedAhorro.datos.reduce(
        (acc, x) => (x.tipo === "Aporte" ? acc + Number(x.valor) : acc),
        0
      );

      this.totalRetiros = this.selectedAhorro.datos.reduce(
        (acc, x) => (x.tipo === "Retiro" ? acc + Number(x.valor) : acc),
        0
      );
      this.total = this.totalAportes - this.totalRetiros;
    },
    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}`;
      }
    },
    getAhorro() {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
          limite: this.$store.state.filtro.nahorro,
        },
      };

      this.$axios
        .get("/ahorro", axiosHeader)
        .then((res) => {
          this.ahorros = [];
          if (res.data.data.length) {
            this.ahorros = res.data.data;
            this.selectedAhorro = this.ahorros[0];
            this.selectedAhorroName = this.selectedAhorro.nombreAhorro;
            this.newItem._id = this.selectedAhorro._id;

            this.sumItems();
          }
        })
        .catch((e) => console.log(e));
    },
    onChange() {
      this.selectedAhorro = this.ahorros.find(
        (x) => x.nombreAhorro === this.selectedAhorroName
      );
      this.newItem._id = this.selectedAhorro._id;
      this.sumItems();
    },
    deleteAhorro() {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
        params: {
          id: this.selectedAhorro._id,
        },
      };
      this.$axios
        .delete("/ahorro", axiosHeader)
        .then((res) => {
          this.selectedAhorro = {
            _id: "",
            nombreAhorro: "",
            datos: [],
          };
          this.selectedAhorroName = "";
          this.getAhorro();
        })
        .catch((e) => console.log(e));
    },
  },
  mounted() {
    this.getAhorro();
  },
  watch: {
    data() {
      this.sumItems();
    },
  },
};
</script>

<style>
</style>