<template>
    <Summary
        warningMsg='Check out the global performances of your products and compare the optimized strategy to doing no discount "No Markdown" or keeping your current prices "Current Markdown".'
        :bigCards="summaryBigCards"
        :smallCards="summarySmallCards"
    >
        <div class="charts-container">
            <HorizontalBarChart
                class="bar-chart"
                title="Optimized Markdown vs. Current Strategy"
                chartTitle="Improvement compared to the Current Strategy"
                :data="chartDataConstantMarkdown"
                v-if="chartDataConstantMarkdown"
            />
            <HorizontalBarChart
                class="bar-chart"
                title="Optimized Markdown vs. No Markdown"
                chartTitle="Improvement compared to No Markdown"
                :data="chartDataNoMarkdown"
                :x-range="xBounds"
                v-if="chartDataNoMarkdown"
            />
        </div>
    </Summary>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import Summary from "./Summary.vue";
import HorizontalBarChart from "./HorizontalBarChart.vue";
import { API } from "../Api";
import useProductStore from "../store/ProductStore";
import { BIG_CARDS_KEYS, CARD_LABELS, CHART_LABELS, appendCurrency, formatNumbers } from "./utils";
interface SummaryData {
    label: any;
    value: number;
    tooltip: {
        uplift: any;
        constantMarkdown?: any;
        noMarkdown?: any;
        markdownOptimization: any;
        percentage: string;
    };
}
interface SummaryCard {
    title: any;
    infoText?: string;
    items: {
        "Markdown optimization": any;
        "Current markdown": any;
        "No markdown": any;
    };
    subItems: {
        "Current markdown":
            | {
                  color: string;
                  icon?: undefined;
                  "Uplift%": any;
                  infoText: string;
              }
            | any;
        "No markdown": any;
    };
    order: number;
}
export default defineComponent({
    components: { Summary, HorizontalBarChart },

    data() {
        return {
            chartDataConstantMarkdown: undefined as undefined | SummaryData[] ,
            chartDataNoMarkdown: undefined  as undefined | SummaryData[],
            summaryBigCards: [] as SummaryCard[],
            summarySmallCards: [] as SummaryCard[],
            store: undefined as undefined | any,
            xBounds: [0, 0],
        };
    },
    mounted() {
        this.store = useProductStore();
    },
    watch: {
        "store.selectedStore": "getData"
    },
    methods: {
        createGraphData(
            label: string,
            uplift: number,
            strategy: string,
            markdownOptimization: any,
            strategyValue: any
        ) {
            this.xBounds = [Math.min(this.xBounds[0], uplift), Math.max(this.xBounds[1], uplift)];
            return {
                label,
                value: uplift,
                tooltip: {
                    uplift: uplift,
                    [strategy]: strategyValue,
                    markdownOptimization,
                    percentage: uplift.toFixed(2) + "%",
                },
            };
        },
        createSummaryCard(row: any): SummaryCard {
            const upliftTooltip = BIG_CARDS_KEYS.includes(row["KPI"])
                ? "Relative change from "
                : "Uplift of the flow's markdown optimization outcome compared to";
            const title = appendCurrency(row["KPI"], this.store.currency)
            return {
                title: CARD_LABELS[title] || title,
                items: {
                    "Markdown optimization": formatNumbers(row["Markdown optimization"]),
                    "Current markdown": formatNumbers(row["Constant Markdown"]),
                    "No markdown": formatNumbers(row["No Markdown"]),
                },
                subItems: {
                    "Current markdown": {
                        "Uplift": row["'Constant Markdown' Uplift"]+'%',
                        infoText: `${upliftTooltip} Current Markdown strategy`,
                        ...this.upliftIcon(row["'Constant Markdown' Uplift"]),
                    },
                    "No markdown": {
                        "Uplift": row["'No Markdown' Uplift"]+'%',
                        infoText: `${upliftTooltip} No Markdown strategy`,
                        ...this.upliftIcon(row["'No Markdown' Uplift"]),
                    },
                },
                order: 1,
            };
        },

        upliftIcon(val: number) {
            if (val === 0) return { color: "grey" };
            if (val > 0) return { icon: "mdi-arrow-up", color: "green" };
            return { icon: "mdi-arrow-down", color: "red" };
        },
        getData() {
            if(!this.store.selectedStore) return;
            this.store.loading = true;
            API.getSummary(this.store.selectedStore, "").then((response) => {
                const rows = response["rows"];
                const kpiOrderMapping = {
                    total_profit: 1,
                    "forecasted_volume": 2,
                    "revenue": 3,
                    "margin_percent": 4,
                    sellthrought_rate: 5,
                };

                rows.forEach((row: any) => {
                    const output = this.createSummaryCard(row);
                    output.order = kpiOrderMapping[row["KPI"]] || 4
                    row.order = output.order;
                    switch (row["KPI"]) {
                        case "total_profit":
                            output.infoText =
                                "Gains after taking the product costs out of the sales revenue";
                            this.summaryBigCards.push(output);
                            break;
                        case "forecasted_volume":
                            output.infoText =
                                "Predicted number of units the will be sold in the next time increment";
                            this.summaryBigCards.push(output);
                            break;
                        default:
                            this.summarySmallCards.push(output);
                            break;
                    }
                });
                const sortedRows = rows.sort((a: any,b: any) => b.order - a.order)

                this.chartDataConstantMarkdown = sortedRows.map((row: any) =>
                    this.createGraphData(
                        CHART_LABELS[row.KPI] || row.KPI,
                        row["'Constant Markdown' Uplift"],
                        "constantMarkdown",
                        row["Markdown optimization"],
                        row["Constant Markdown"]
                    )
                );

                this.chartDataNoMarkdown = rows.map((row: any) =>
                    this.createGraphData(
                        CHART_LABELS[row.KPI] || row.KPI,
                        row["'No Markdown' Uplift"],
                        "noMarkdown",
                        row["Markdown optimization"],
                        row["No Markdown"]
                    )
                );
                this.summaryBigCards.sort(
                    (a: SummaryCard, b: SummaryCard) => a.order - b.order
                );
                this.summarySmallCards.sort(
                    (a: SummaryCard, b: SummaryCard) => a.order - b.order
                );
            }).finally(() => this.store.loading = false);
        },
    },
});
</script>
