<template>
  <v-container>
    <v-toolbar>
      <v-toolbar-title> Cuadre del Tarro </v-toolbar-title>
    </v-toolbar>
    <v-card>
      <v-card-text>
        <v-form ref="taker" v-model="valid">
          <v-text-field
            v-model="reconciliation.date_time"
            label="Fecha"
            type="datetime-local"
            :rules="[rules.required]"
            required
            readonly
          ></v-text-field>
        <v-text-field
          v-model="reconciliation.reconcilier"
          label="Cajero"
          :rules="[rules.required]"
          required
        ></v-text-field>
        <v-text-field
          v-model="reconciliation.total_cash_purchases"
          label="Total Ventas en efectivo"
          :rules="[rules.required]"
          prefix="$"
          type="number"
          readonly
        ></v-text-field>
        <v-text-field
          v-model="reconciliation.cash_taken"
          label="Dinero Recogido"
          :rules="[rules.required]"
          prefix="$"
          type="number"
        ></v-text-field>
        <v-text-field
          v-model="reconciliation.cash_discrepancy"
          label="Descuadre"
          :rules="[rules.integer]"
          prefix="$"
          type="number"
        ></v-text-field>
        <v-btn @click="submit" color="green">Recoger Dinero</v-btn>
        </v-form>
      </v-card-text>
    </v-card>
    <v-tabs v-model="selectedTab">
      <v-tab
        v-for="(purchases, payment_method) in summary.purchases"
        :key="payment_method"
        :value="payment_method"
      >
        {{ payment_method }}&nbsp; <CurrencyText :value="totalByMethod(payment_method)"</CurrencyText>
      </v-tab>
    </v-tabs>

    <v-tabs-window v-model="selectedTab">
      <v-card>
        <v-card-text>
          <v-tabs-window-item
            v-for="(purchases, payment_method) in summary.purchases"
            :key="payment_method"
            :value="payment_method"
          >
            <v-data-table-virtual
              :headers="summary.headers"
              :items="summary.purchases[payment_method]"
            >
              <template v-slot:item.id="{ item }">
                <v-btn @click="openSummaryModal(item.id)">{{ item.id }}</v-btn>
              </template>
              <template v-slot:item.total="{ item }">
                <CurrencyText :value="parseFloat(item.total)"></CurrencyText>
              </template>
            </v-data-table-virtual>
          </v-tabs-window-item>
          <SummaryPurchaseModal :id="selectedPurchaseId" ref="summaryModal" />
        </v-card-text>
      </v-card>
    </v-tabs-window>
  </v-container>
</template>
<script>
  import { inject } from 'vue';
  import CurrencyText from './CurrencyText.vue';
  import SummaryPurchaseModal from './SummaryPurchaseModal.vue';

  export default {
    name: 'ReconciliationJar',
    props: {
      msg: String,
    },
    components: {
      SummaryPurchaseModal,
    },
    data () {
      return {
        api: inject('api'),
        valid: null,
        selectedPurchaseId: null,
        selectedTab: 'CASH',
        reconciliation: {
          date_time: '',
          total_cash_purchases: 0,
          cash_taken: 0,
          cash_discrepancy: 0,
          other_totals: {
          },
          cash_purchases: [],
        },
        summary: {
          headers: [
            {title: 'Id', value: 'id'},
            {title: 'Fecha', value: 'date'},
            {title: 'Cliente', value: 'customer.name'},
            {title: 'Total', value: 'total'},
          ],
          purchases: {},
        },
        rules: {
          required: value => !!value || 'Requerido.',
          integer: value => !!value || value === 0 || 'Requerido.',
        },
      };
    },
    mounted() {
      this.fetchPurchases();
      this.reconciliation.date_time = this.getCurrentDate();
    },
    watch: {
      'reconciliation.cash_taken'() {
        this.updateDiscrepancy();
      },
    },
    methods: {
      totalByMethod(method) {
        if (method in this.summary.purchases) {
          return this.summary.purchases[method].reduce((a, b) => a + parseFloat(b.total), 0);
        }
        return 0;
      },
      idsBymethod(method) {
        if (method in this.summary.purchases) {
          return this.summary.purchases[method].map(purchase => purchase.id)
        }
        return [];
      },
      processOtherMethods() {
        for (const method of Object.keys(this.summary.purchases)) {
          if (method !== 'CASH') {
            this.reconciliation.other_totals[method] = {
              total: this.totalByMethod(method),
              purchases: this.idsBymethod(method),
            }
          }
        }
      },
      updateDiscrepancy() {
        this.reconciliation.cash_discrepancy = (this.reconciliation.total_cash_purchases || 0 ) - (this.reconciliation.cash_taken || 0);
      },
      getCurrentDate() {
        const today = new Date();
        const gmtOffSet = -5;
        const localDate = new Date(today.getTime() + (gmtOffSet * 60 * 60 * 1000));
        // Formatear la fecha y hora en el formato YYYY-MM-DDTHH:MM
        const formattedDate = localDate.toISOString().slice(0,16);
        return formattedDate;
      },
      openSummaryModal(id) {
        this.selectedPurchaseId = id;
        this.$refs.summaryModal.dialog = true;
      },
      fetchPurchases() {
        this.api.getPurchasesForReconciliation()
            .then(data => {
              this.summary.purchases = data;
              this.reconciliation.cash_purchases = this.idsBymethod('CASH');
              this.reconciliation.total_cash_purchases = this.totalByMethod('CASH');
              this.processOtherMethods();
            })
            .catch(error => {
              console.error(error);
            });
      },
      async submit() {
        this.$refs.taker.validate();
        if (this.valid) {
          this.api.createReconciliationJar(this.reconciliation)
              .then(data => {
                console.log('Cuadre enviado:', data);
                this.$router.push({path: "/"});
              })
              .catch(error => console.error('Error:', error));
        }
      }
    },
  }
</script>
