/** @odoo-module */

import { registry } from "@web/core/registry"
import { ChartRenderer } from "./chart_renderer/chart_renderer"
import { loadJS } from "@web/core/assets"
import { useService } from "@web/core/utils/hooks"

const { Component, onWillStart, useRef, onMounted, useState } = owl

export class OwlSFGDashboard extends Component {
    components = { ChartRenderer };
    
    setup(){
        
        this.state = useState({
            
        })

        this.orm = useService("orm")
        this.actionService = useService("action")
        this.records = [];

        onWillStart(async ()=>{
            await loadJS("https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js")
            await this.getsfgdata();
        })
        // Create an instance of the component
        this.chartRenderer = new ChartRenderer();
        this.chartRenderer.chartRef = useRef("chart")
        
    }

    async getsfgdata() {
        
        const datas = await this.orm.readGroup(
            "sos_sfg", 
            [],  
            ['sfg_type', 'inhand_stock_qty', 'inhand_stock_val'],  // fields
            ['sfg_type']  
        );
    
        let lables   = [];
        let stockqty = [];
        let stockval = [];
        let totalstockVal = 0;
        let totalstockQty = 0;

        datas.forEach(data => {
            lables.push(data.sfg_type);
            stockqty.push(data.inhand_stock_qty);
            stockval.push(data.inhand_stock_val);
            totalstockQty+= data.inhand_stock_qty;
            totalstockVal+= data.inhand_stock_val;
        });

        this.state.orders = {
            lables: lables,
            stockqty: stockqty,  
            stockval: stockval,
            totalstockQty: totalstockQty,
            totalstockVal: `₹${formatIndianCurrency(totalstockVal)}`,
        }
    }
}
function formatIndianCurrency(value) {
    const number = Math.trunc(value); // Ensure the value is a whole number
    return new Intl.NumberFormat('en-IN', { maximumFractionDigits: 0 }).format(number);
}
OwlSFGDashboard.template = "owl.OwlSFGDashboard"
OwlSFGDashboard.components = { ChartRenderer }

registry.category("actions").add("owl.sfg_dashboards", OwlSFGDashboard)
