<template>
  <div>
    <div class="row">
      <card class="col-12">
        <el-table
          :data="
            ingresos.filter(
              (data) =>
                !search ||
                data.detalle.toLowerCase().includes(search.toLowerCase()) ||
                data.fecha.toLowerCase().includes(search.toLowerCase()) 
            )
          "
          border
          empty-text="No hay Ingresos registrados"
          stripe
          :summary-method="getSummaries"
          show-summary
          style="width: 100%"
        >
          <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 :formatter="cell">
          </el-TableColumn>

          <el-TableColumn>
            <div slot-scope="{ row, $index }">
              <el-tooltip content="Edit" effect="light">
                <base-button
                  type="success"
                  icon
                  size="sm"
                  class="btn-link"
                  @click="updateIngresoClic($index)"
                >
                  <i class="el-icon-edit"></i>
                </base-button>
              </el-tooltip>
              <el-tooltip content="Delete" effect="light">
                <base-button
                  type="danger"
                  icon
                  size="sm"
                  class="btn-link"
                  @click="deleteIngreso(row._id)"
                >
                  <i class="el-icon-delete-solid"></i>
                </base-button>
              </el-tooltip>
            </div>
            <template slot="header" slot-scope="scope">
              <el-input v-model="search" size="mini" placeholder="Buscar" />
            </template>
          </el-TableColumn>
        </el-table>
      </card>
      <Fingreso
       
        :newIngreso="newIngreso"
        :saveIngreso="saveIngreso"
        :updateIngreso="updateIngreso"
        :isUpdate="isUpdate"
        :openForm="openForm"
      />
    </div>
  </div>
</template>

<script>
import { Table, TableColumn } from "element-ui";
import { Select, Option } from "element-ui";
export default {
  middleware: "authenticated",
  components: {
    [Table.name]: Table,
    [TableColumn.name]: TableColumn,
    [Option.name]: Option,
    [Select.name]: Select,
  },
  data() {
    return {
      newIngreso: {
        fecha: "",
        detalle: "",
        valor: 0,
      },
      ingresos: [],
      search: "",
      isUpdate: false,
      openForm: false,
    };
  },
  mounted() {
    // this.$store.dispatch("getCategorias");
    //this.$store.dispatch("getMetodos");
    this.newIngreso.fecha = this.$store.state.fecha;
  
  

    this.getIngresos();
  },

  methods: {
    cell(row, column, cellValue, index) {
      return this.formatMoneda(cellValue);
    },
    getIngresos() {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
      };
      this.$axios
        .get("/ingreso", axiosHeader)
        .then((res) => {
          console.log(res.data.data);
          this.ingresos = res.data.data;
        })
        .catch((e) => console.log(e));
    },
    saveIngreso() {
      if (this.checkFormulario() === false) {
        return;
      }
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
      };
      const toSend = this.newIngreso;
      console.log(axiosHeader.data);
      this.$axios
        .post("/ingreso", toSend, axiosHeader)
        .then((res) => {
          this.clearFormIngreso();
          console.log(res.data.status);
          this.getIngresos();
        })
        .catch((e) => console.log(e));
    },
    updateIngreso(id) {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
      };
      const toSend = this.newIngreso;
      console.log(axiosHeader.data);
      this.$axios
        .put("/ingreso", toSend, axiosHeader)
        .then((res) => {
          this.clearFormIngreso();
          console.log(res.data.status);
          this.getIngresos();
        })
        .catch((e) => console.log(e));
    },
    updateIngresoClic(id) {
      this.isUpdate = true;
      this.newIngreso = JSON.parse(JSON.stringify(this.ingresos[id]));
      this.openForm = !this.openForm;
    },

    deleteIngreso(id) {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
        params: {
          id: id,
        },
      };
      this.$axios
        .delete("/ingreso", axiosHeader)
        .then((res) => {
          console.log(res.data);
          this.getIngresos();
          this.clearFormIngreso();
        })
        .catch((e) => console.log(e));
    },
    clearFormIngreso() {
      this.newIngreso._id = "";
      this.newIngreso.detalle = "";
      this.newIngreso.valor = 0;
      this.isUpdate = false;
    },
  
    formatMoneda(dato) {
      var num = dato;
      if (!isNaN(num)) {
        num = num
          .toString()
          .split("")
          .reverse()
          .join("")
          .replace(/(?=\d*\.?)(\d{3})/g, "$1.");
        num = num.split("").reverse().join("").replace(/^[\.]/, "");
        //return '$' +num;
        return `$ ${num}`;
      }
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "Valor total";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = this.formatMoneda(
            values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0)
          );
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },
    checkFormulario() {
      if (this.newIngreso.valor === 0) {
        this.$notify({
          type: "danger",
          icon: "tim-icons icon-alert-circle-exc",
          message: "el campo valor no puede estar en cero :(",
        });
        return false;
      }

      if (this.newIngreso.detalle === "") {
        this.$notify({
          type: "danger",
          icon: "tim-icons icon-alert-circle-exc",
          message: "el campo detalle no puede estar vacio :(",
        });
        return false;
      }

      return true;
    },
  },
};
</script>

<style>
</style>
