<template>
  <div class="row dashboard" v-if="this.canAccess('dashboard')">
    <div class="col-12">
      <div
        class="page-title-box d-flex align-items-center justify-content-between"
      >
        <h3 class="mb-0">{{ $trans("Dashboard") }}</h3>
        <div class="d-flex ms-auto align-items-center">
          <div
            class="date-range d-flex align-items-center"
            style="width: 200px"
          >
            <div class="d-flex align-items-center input-wrapper">
              <input
                type="date"
                v-model="cardsFilter.from"
                class="form-control"
                @click="displayPicker"
              />
              <span class="input-separator">-</span>
              <input
                type="date"
                v-model="cardsFilter.to"
                class="form-control"
                @click="displayPicker"
              />
            </div>
            <div class="icon ms-auto">
              <i class="uil uil-calendar-alt"></i>
            </div>
          </div>
          <div class="ms-2">
            <button
              class="btn btn-primary"
              type="button"
              :disabled="cardsFilter.from >= cardsFilter.to"
              @click="handleDashboardFilter"
            >
              Go
            </button>
          </div>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-xl-3 col-sm-6">
        <div class="card">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <div class="flex-shrink-0 me-3">
                <div class="avatar-sm">
                  <div
                    class="avatar-title bg-primary-subtle text-white rounded-circle font-size-20"
                  >
                    <i class="uil uil-clipboard-notes"></i>
                  </div>
                </div>
              </div>
              <div class="flex-grow-1 overflow-hidden">
                <p class="mb-1 text-truncate text-muted">
                  {{ $trans("Total Sales") }}
                </p>
                <h4 class="font-size-18 mb-0">
                  {{ $helper.formatNumber(salesCount) }}
                </h4>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-xl-3 col-sm-6">
        <div class="card">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <div class="flex-shrink-0 me-3">
                <div class="avatar-sm">
                  <div
                    class="avatar-title bg-purple text-white rounded-circle font-size-18"
                  >
                    <i class="uil uil-chart-pie-alt"></i>
                  </div>
                </div>
              </div>
              <div class="flex-grow-1 overflow-hidden">
                <p class="mb-1 text-truncate text-muted d-flex justify-content-between align-items-center">
                  {{ $trans("Sales Amount") }}
                  <h6 class="font-size-13 mt-2">
                    <span 
                    :class="
                    totalSales > TotalInPreviousMonth
                      ? 'uil uil-arrow-up text-success'
                      : 'uil uil-arrow-down text-danger'
                  "
                    > {{ PercentageChange(totalSales,TotalInPreviousMonth) }}%</span>
                  </h6>
                </p>
                <h4 class="font-size-16 mb-0">
                  <span style="font-family: ubuntu">FBU</span>
                  {{ $helper.formatNumber(totalSales) }}
                </h4>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-xl-3 col-sm-6">
        <div class="card">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <div class="flex-shrink-0 me-3">
                <div class="avatar-sm">
                  <div
                    class="avatar-title bg-success text-white rounded-circle font-size-18"
                  >
                    <i class="uil uil-check"></i>
                  </div>
                </div>
              </div>
              <div class="flex-grow-1 overflow-hidden">
                <p class="mb-1 text-truncate text-muted d-flex justify-content-between align-items-center">
                  {{ $trans("Paid Amount") }} 
                  <h6 class="font-size-13 mt-2">
                    <span 
                    :class="
                    totalPaid > totalPaidPrvM
                      ? 'uil uil-arrow-up text-success'
                      : 'uil uil-arrow-down text-danger'
                  "
                    > {{ PercentageChange(totalPaid,totalPaidPrvM) }}%</span>
                  </h6>
                </p>
                <h4 class="font-size-16 mb-0">
                  <span style="font-family: ubuntu">FBU</span>
                  {{ $helper.formatNumber(totalPaid) }}
                </h4>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-xl-3 col-sm-6">
        <div class="card">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <div class="flex-shrink-0 me-3">
                <div class="avatar-sm">
                  <div
                    class="avatar-title bg-danger text-white rounded-circle font-size-18"
                  >
                    <i class="uil uil-adjust-half"></i>
                  </div>
                </div>
              </div>
              <div class="flex-grow-1 overflow-hidden">
                <p class="mb-1 text-truncate text-muted d-flex justify-content-between align-items-center">
                  {{ $trans("Debts Amount") }}
                  <h6 class="font-size-13 mt-2">
                    <span 
                    :class="
                    totalPending > PendingInPreviousMonth
                      ? 'uil uil-arrow-up text-success'
                      : 'uil uil-arrow-down text-danger'
                  "
                    > {{ PercentageChange(totalPending,PendingInPreviousMonth) }}%</span>
                  </h6>
                </p>
                <h4 class="font-size-16 mb-0">
                  <span style="font-family: ubuntu">FBU</span>
                  {{ $helper.formatNumber(totalPending) }}
                </h4>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xxl-3 col-xl-3 col-lg-3 col-md-4 col-sm-6">
      <div class="card shadow">
        <div class="card-body">
          <div class="d-flex justify-content-between">
            <div>
              <h6 class="font-size-17 text-capitalize">
                {{ $trans("Products Number") }}
              </h6>
              <h4
                class="mt-2 font-size-18 font-weight-bold d-flex align-items-center"
              >
                {{ $helper.formatNumber(total_products) }}
              </h4>
              <div class="text-muted font-size-13">
                {{ $trans("Products Number") }}
              </div>
            </div>
            <div>
              <div class="avatar-md">
                <div
                  class="avatar-title bg-default text-white rounded-circle font-size-20"
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="30"
                    height="30"
                    fill="currentColor"
                    class="bi bi-view-list"
                    viewBox="0 0 16 16"
                  >
                    <path
                      d="M3 4.5h10a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2zm0 1a1 1 0 0 0-1 1v3a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1H3zM1 2a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13A.5.5 0 0 1 1 2zm0 12a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13A.5.5 0 0 1 1 14z"
                    />
                  </svg>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xxl-3 col-xl-3 col-lg-3 col-md-4 col-sm-6">
      <div class="card">
        <div class="card-body">
          <div class="d-flex justify-content-between">
            <div>
              <h6 class="font-size-17 text-capitalize">
                {{ $trans("Main stock") }}
              </h6>
              <h4
                class="mt-2 font-size-18 font-weight-bold mb-2 d-flex align-items-center"
              >
                <span style="font-family: ubuntu" class="me-2">FBU</span>
                {{ $helper.formatNumber(stock_value) }}
              </h4>
              <div class="text-muted font-size-13">
                {{ $trans("All Products") }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xxl-3 col-xl-3 col-lg-3 col-md-4 col-sm-6">
      <div class="card">
        <div class="card-body">
          <div class="d-flex justify-content-between">
            <div>
              <h6 class="font-size-17 text-capitalize">
                {{ $trans("Total Receives") }}
              </h6>
              <h4
                class="mt-2 font-size-18 font-weight-bold mb-2 d-flex align-items-center"
              >
                <span style="font-family: ubuntu" class="me-2">FBU</span>
                {{ $helper.formatNumber(receives_amount) }}
              </h4>
              <div class="text-muted font-size-13">
                  <span 
                  :class="
                  receives_amount > receivesInPreviousMonth
                    ? 'uil uil-plus text-success'
                    : 'uil uil-minus text-danger'"
                  > {{ PercentageChange(receives_amount,receivesInPreviousMonth) }}%</span>
              </div>
            </div>
            <div>
              <div class="avatar-md">
                <div
                  class="avatar-title text-white rounded-circle font-size-20"
                  :class="receives_amount > receivesInPreviousMonth
                      ? 'bg-success'
                      : 'bg-danger'
                  "
                >
                  <i :class="receives_amount > receivesInPreviousMonth
                      ? 'uil uil-chart-line'
                      : 'uil uil-chart-down'
                  "
                  ></i>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xxl-3 col-xl-3 col-lg-3 col-md-4 col-sm-6">
      <div class="card">
        <div class="card-body">
          <div class="d-flex justify-content-between">
            <div>
              <h6 class="font-size-17 text-capitalize">
                {{ $trans("Expenses Amount") }}
              </h6>
              <h4
                class="mt-2 font-size-18 font-weight-bold mb-2 d-flex align-items-center"
              >
                <span style="font-family: ubuntu" class="me-2">FBU</span>
                {{ $helper.formatNumber(totalExpenses) }}
              </h4>
              <div class="text-muted font-size-13">
                <span 
                  :class="
                  totalExpenses > ExpensesInPreviousMonth
                    ? 'uil uil-plus text-success'
                    : 'uil uil-minus text-danger'"
                  > {{ PercentageChange(totalExpenses,ExpensesInPreviousMonth) }}%</span>
              </div>
            </div>
            <div>
              <div class="avatar-md">
                <div
                  class="avatar-title text-white rounded-circle font-size-20"
                  :class="totalExpenses > ExpensesInPreviousMonth
                      ? 'bg-success'
                      : 'bg-danger'
                  "
                >
                  <i :class="totalExpenses > ExpensesInPreviousMonth
                      ? 'uil uil-chart-line'
                      : 'uil uil-chart-down'
                  "
                  ></i>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-6">
      <div class="card card-h-100">
        <div class="card-body">
          <div class="float-end">
            <div class="dropdown">
              <a
                class="dropdown-toggle text-reset"
                href="#"
                data-bs-toggle="dropdown"
                aria-haspopup="true"
                aria-expanded="false"
              >
                <span class="fw-semibold">{{ $trans("Sort By:") }} </span>
                <span class="text-muted"
                  >{{ $trans("Yearly")
                  }}<i class="mdi mdi-chevron-down ms-1"></i
                ></span>
              </a>

              <div class="dropdown-menu dropdown-menu-end">
                <a class="dropdown-item" href="#">{{ $trans("Yearly") }}</a>
                <a class="dropdown-item" href="#">{{ $trans("Monthly") }}</a>
                <a class="dropdown-item" href="#">{{ $trans("Weekly") }}</a>
                <a class="dropdown-item" href="#">{{ $trans("Today") }}</a>
              </div>
            </div>
          </div>
          <h4 class="card-title mb-4">
            {{ $trans("Stock-In") }} vs. {{ $trans("Stock-Out") }}
          </h4>
          <div class="mt-3">
            <div id="chart">
              <apexchart
                type="line"
                height="350"
                :options="tVsRChartOptions"
                :series="tVsRChartSeries"
              ></apexchart>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-6">
      <div class="card card-h-100">
        <div class="card-body">
          <h4 class="card-title mb-4">
            {{ $trans("Paid sales vs Unpaid Sales") }}
          </h4>
          <div class="mt-3">
            <div id="chart">
              <apexchart
                type="line"
                height="350"
                :options="paidPerUpaidOptions"
                :series="paidPerUpaidSeries"
              ></apexchart>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div v-else class="p-2 w-100">
    <div class="ant-empty">
      <div class="ant-empty-description">
        <img src="/img/welcome.svg" width="600" />
      </div>
      <br />
      <p class="alert alert-success">
        {{ $trans("Hello") }} ! <b>{{ user.name }}</b>
        {{ $trans("You Successfuly Logged in to Levo0!") }} <br />
        {{ $trans("Have Great Work") }} !
      </p>
    </div>
  </div>
</template>
<script>
import VueApexCharts from "vue3-apexcharts";
import { encodeQuery } from "@/helpers/utils.js";
import { permissionsHandler } from "@/helpers/permissions-handler";
export default {
  name: "Index",
  components: {
    apexchart: VueApexCharts,
  },
  mixins: [permissionsHandler],
  data: () => ({
    total_products: 0,
    stock_value: 0,
    branch_stock: 0,
    receives_amount: 0,
    receives_chart: [],
    transfers_amount: 0,
    transfers_chart: [],
    // for sales
    salesCount: 0,
    totalSales: 0,
    totalExpenses: 0,
    totalPaid: 0,
    totalPaidPrvM: 0,
    TotalInPreviousMonth:0,
    PendingInPreviousMonth:0,
    ExpensesInPreviousMonth:0,
    receivesInPreviousMonth:0,
    totalPending: 0,
    labels: [],
    pendingChart: [],
    paidChart: [],
    cardsFilter: {
      from: new Date().toLocaleString("fr-CA", {}).slice(0, 10),
      to: new Date().toLocaleString("fr-CA", {}).slice(0, 10),
    },
  }),
  created() {
    this.$http.get("stock/reports/dashboard").then((response) => {
      this.stock_value = response.data.stock_value;
      this.branch_stock = response.data.branch_stock;
      this.receives_amount = response.data.receives_amount;
      this.receivesInPreviousMonth = response.data.receivesInPreviousMonth;
      this.receives_chart = response.data.receives_chart;
      this.transfers_amount = response.data.transfers_amount;
      this.transfers_chart = response.data.transfers_chart;
      this.total_products = response.data.total_products;
      const month = response.data.current_month;
      this.cardsFilter = {
        from: new Date(month[0]).toLocaleString("fr-CA", {}).slice(0, 10),
        to: new Date(month[1]).toLocaleString("fr-CA", {}).slice(0, 10),
      };
    });
  },
  computed: {
    user() {
      return this.$store.state.user || {};
    },
    isReady() {
      return this.user && Object.keys(this.user).length > 0;
    },
    permissions() {
      return this.isReady && this.user.role.permissions;
    },
    tVsRChartSeries() {
      return [
        {
          name: "Stock-In Chart",
          type: "line",
          data: this.receives_chart,
        },
        {
          name: "Stock-Out Chart",
          type: "line",
          data: this.transfers_chart,
        },
      ];
    },
    tVsRChartOptions() {
      return {
        chart: {
          height: 350,
          type: "area",
        },
        stroke: {
          curve: "smooth",
        },
        title: {
          text: "",
        },
        dataLabels: {
          enabled: true,
          enabledOnSeries: [1],
        },
        labels: [
          "Jan 2023",
          "Feb 2023",
          "Mar 2023",
          "Apr 2023",
          "May 2023",
          "Jun 2023",
          "Jul 2023",
          "Aug 2023",
          "Sep 2023",
          "Oct 2023",
          "Nov 2023",
          "Dec 2023",
        ],
        xaxis: {
          type: "string",
        },
        yaxis: [
          {
            title: {
              text: "Stock-In Chart",
            },
          },
          {
            opposite: true,
            title: {
              text: "Stock-Out Chart",
            },
          },
        ],
      };
    },

    paidPerUpaidSeries() {
      return [
        {
          name: "Paid Amount",
          data: this.paidChart,
        },
        {
          name: "Unpaid Amount",
          data: this.pendingChart,
        },
      ];
    },

    paidPerUpaidOptions() {
      return {
        chart: {
          height: 350,
          type: "area",
          toolbar: {
            show: false,
          },
        },
        colors: ["#8a04bc", "#000000"],
        dataLabels: {
          enabled: false,
        },
        stroke: {
          curve: "smooth",
          width: 3,
        },
        legend: {
          show: false,
        },
        grid: {
          show: false,
          strokeDashArray: 6,
          borderColor: "#dadada",
        },
        yaxis: {
          labels: {
            style: {
              colors: "#B5B5C3",
              fontSize: "12px",
              fontWeight: 400,
            },
            formatter: function (value) {
              return value + "k";
            },
          },
        },
        xaxis: {
          categories: this.labels,
          type: "string",
          labels: {
            style: {
              colors: "#B5B5C3",
              fontSize: "12px",
              fontWeight: 400,
            },
          },
        },
        fill: {
          type: "solid",
          opacity: 0.05,
        },
      };
    },
  },
  mounted() {
    this.$store.state.loadingTask == "GETTING_DASHBOARD_TASKS";
    this.$http.get("stock/pos/dashboard").then((response) => {
      this.salesCount = response.data.sales_count;
      this.totalSales = response.data.total_sales;
      this.totalExpenses = response.data.total_expenses;
      this.totalPaid = response.data.total_paid;
      this.totalPaidPrvM = response.data.PaidInPreviousMonth;
      this.TotalInPreviousMonth=response.data.TotalInPreviousMonth;
      this.PendingInPreviousMonth=response.data.PendingInPreviousMonth;
      this.ExpensesInPreviousMonth=response.data.ExpensesInPreviousMonth;
      this.totalPending = response.data.total_pending;
      this.labels = response.data.labels;
      this.pendingChart = response.data.pending_chart;
      this.paidChart = response.data.paid_chart;
    });
  },
  methods: {
    canAccess(menu, submenu = null) {
      if (!this.user.role_id) {
        return true;
      } else {
        if (!submenu) {
          return (
            this.permissions[menu] && this.permissions[menu].accessible == true
          );
        } else {
          return (
            this.permissions[menu][submenu] &&
            this.permissions[menu][submenu].includes("R")
          );
        }
      }
    },
    handleDashboardFilter() {
      this.$http
        .all([
          this.$http.get(
            encodeQuery("stock/pos/dashboard/cards-filter", this.cardsFilter)
          ),
          this.$http.get(
            encodeQuery(
              "stock/reports/dashboard/cards-filter",
              this.cardsFilter
            )
          ),
        ])
        .then(
          this.$http.spread((responseOne, responseTwo) => {
            this.salesCount = responseOne.data.sales_count;
            this.totalSales = responseOne.data.total_sales;
            this.totalExpenses = responseOne.data.total_expenses;
            this.totalPaid = responseOne.data.total_paid;
            this.totalPending = responseOne.data.total_pending;
            this.receives_amount = responseTwo.data.receives_amount;
            this.transfers_amount = responseTwo.data.transfers_amount;
          })
        )
        .catch((error) => {
          if (error.response.status == 400 || error.response.status == 422) {
            this.errors = error.response.data.errors;
            this.$notify({
              type: "error",
              message:
                "Invalid date range: 'From' date must be before 'To' date.",
            });
          }
        });
    },
    PercentageChange(current, previous) {
      if (previous === 0) {
        if (current === 0) {
          return 0;
        } else {
          return Infinity;
        }
      } else {
        return (
            ((current - previous) / previous).toFixed(3)
          );
      }
    },
    displayPicker(e) {
      e.target.showPicker();
    },
  },
};
</script>
<style scoped>
.card {
  border-radius: 15px;
  border: 1px solid #ddd;
}
</style>
