<template>
  <div>
    <div class="row">
      <card class="col-12">
        <el-table
          :data="
            compras.filter(
              (data) =>
                !search ||
                data.detalle.toLowerCase().includes(search.toLowerCase()) ||
                data.fecha.toLowerCase().includes(search.toLowerCase()) ||
                data.metodopago.toLowerCase().includes(search.toLowerCase()) ||
                data.categoria.toLowerCase().includes(search.toLowerCase())
            )
          "
          border
          empty-text="No hay compras realizadas"
          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
            prop="metodopago"
            label="Metodo de pago"
            sortable
          ></el-TableColumn>
          <el-TableColumn
            prop="categoria"
            label="Categoria"
            sortable
          ></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="updateCompraClic($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="deleteCompra(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>

      <Fcompras
        :categorias="categorias"
        :metodos_pago="metodos_pago"
        :newCompra="newCompra"
        :saveCompra="saveCompra"
        :updateCompra="updateCompra"
        :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 {
      newCompra: {
        fecha: "",
        detalle: "",
        valor: 0,
        metodopago: "",
        categoria: "",
      },
      compras: [],
      search: "",
      metodos_pago: [],
      categorias: [],
      isUpdate: false,
      openForm: false,
    };
  },
  mounted() {
    this.newCompra.fecha = this.$store.state.fecha;
    this.$store.dispatch("getCategorias");
    this.$store.dispatch("getMetodos");
    this.categorias = this.$store.state.categorias;
    this.metodos_pago = this.$store.state.metodos_de_pago;
    this.getCompras();
  },

  methods: {
    cell(row, column, cellValue, index) {
      return this.formatMoneda(cellValue);
    },
    getCompras() {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
      };
      this.$axios
        .get("/compras", axiosHeader)
        .then((res) => {
          console.log(res.data.data);
          this.compras = res.data.data;
        })
        .catch((e) => console.log(e));
    },
    saveCompra() {
      if (this.checkFormulario() === false) {
        return;
      }
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
      };
      const toSend = this.newCompra;
      console.log(axiosHeader.data);
      this.$axios
        .post("/compra", toSend, axiosHeader)
        .then((res) => {
          this.clearFormCompra();
          console.log(res.data.status);
          this.getCompras();
        })
        .catch((e) => console.log(e));
    },
    updateCompra(id) {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
      };
      const toSend = this.newCompra;
      console.log(axiosHeader.data);
      this.$axios
        .put("/compra", toSend, axiosHeader)
        .then((res) => {
          this.clearFormCompra();
          console.log(res.data.status);
          this.getCompras();
        })
        .catch((e) => console.log(e));
    },
    updateCompraClic(id) {
      this.isUpdate = true;
      this.newCompra = JSON.parse(JSON.stringify(this.compras[id]));
      this.openForm = !this.openForm;
    },

    deleteCompra(id) {
      const axiosHeader = {
        headers: {
          token: this.$store.state.auth.token,
        },
        params: {
          id: id,
        },
      };
      this.$axios
        .delete("/compra", axiosHeader)
        .then((res) => {
          console.log(res.data);
          this.getCompras();
          this.clearFormCompra();
        })
        .catch((e) => console.log(e));
    },
    clearFormCompra() {
      this.newCompra._id = "";
      this.newCompra.detalle = "";
      this.newCompra.valor = 0;
      this.newCompra.metodopago = "";
      this.newCompra.categoria = "";
      this.isUpdate = false;
    },
    getIcon(name) {
      const found = this.$store.state.categorias.find((ic) => ic.name === name);
      console.log(found);
    },

    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.newCompra.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.newCompra.detalle === "") {
                this.$notify({
              type: "danger",
              icon: "tim-icons icon-alert-circle-exc",
              message: "el campo detalle no puede estar vacio :("
            });
        return false;
      }

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

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

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

<style>
</style>