/** @odoo-module */

import { registry } from "@web/core/registry"
/*import { KpiCard } from "./kpi_card/kpi_card"*/
import { ChartRenderer } from "./chart_renderer/chart_renderer"
import { loadJS } from "@web/core/assets"
import { useService } from "@web/core/utils/hooks"
//import { Chart } from "chart.js/auto" // Ensure Chart.js is available
const { Component, onWillStart, useRef, onMounted, useState } = owl

export class OwlMaterialDashboard extends Component {
    components = { ChartRenderer };
    static datalist = null;
    
    setup(){
        this.state = useState({
            quotations: {
               value:10,
               percentage:6,
            },chartdata: {
               datalist:[0,0,0]
            },
            component:'Select All Material',
        })

        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.getmaterialdata();
            await this.mounted();
        })
        // Create an instance of the component
        this.chartRenderer = new ChartRenderer();
        this.chartRenderer.chartRef = useRef("chart")
        
    }

    async mounted() {
        const domain = [['name','!=','']]
        const materials = await this.orm.searchRead("sos_material_types",domain,['id','name']);
        this.state.materials = materials;
        //alert(" MMMM "+materials);
    }
    

    async onChangeComponent(event){
        
        const compdata = this.state.component;
        
        if(compdata=="Select All Material"){
            this.getmaterialdata(compdata);
        }else{
            //alert(" compdata "+compdata);
            this.getindividualmaterialdata(compdata);
        }

    }

    async getindividualmaterialdata(compdata){

        const domain1  = [['material_type_id','=','1']];
        //alert(domain1);
        let totaldata1 = await this.orm.searchRead(
                            "sos_material", domain1,
                            ['material_sub_type','inhand_stock_qty','inhand_stock_val'],0,80); // singleid 

        //console.log(totaldata1);
        //alert(" totaldata1 "+totaldata1);
        
        const json_datas = JSON.stringify(totaldata1);
        const datas = JSON.parse(json_datas);
    
        let stockqty = [];
        let stockval = [];
        let lables   = [];
        
        for (const items of datas) {
            const material        = items.material_sub_type.toString();
            const materialsubtype = material.split(',');
            
            stockqty.push(items.inhand_stock_qty);
            stockval.push(items.inhand_stock_val);
            lables.push(materialsubtype[1]);
        }
        
        this.state.orders = {
            lables: lables,
            stockqty: stockqty,  
            stockval: stockval,
        }
     
    }
    
    async getmaterialdata(self){

        const domain = [['name','!=','']]
        let totaldata = await this.orm.searchRead("sos_material_types",domain,['id','name']);
        const json_data = JSON.stringify(totaldata);
        const data   = JSON.parse(json_data);
        let lables   = [];
        let stockqty = [];
        let stockval = [];
        let totalstockVal = 0;
        let totalstockQty = 0;
        for (const item of data) {
            //alert(item.id);
            const domains = [['material_type_id', '=', item.id]];
            let totaldatas = await this.orm.searchRead(
                             "sos_material",
                             domains,
                             ['inhand_stock_qty', 'inhand_stock_val']
                            );

            const json_datas = JSON.stringify(totaldatas);
            //alert(json_datas);
            const datas = JSON.parse(json_datas);
            lables.push(item.name);
            let totalQty = 0;
            let totalVal = 0;
            for (const items of datas) {
                totalQty += items.inhand_stock_qty;
                totalVal += items.inhand_stock_val;
            }
            totalstockVal+= totalVal;
            totalstockQty+= totalQty;
            
            stockqty.push(totalQty);
            stockval.push(totalVal);
        }
  

        this.state.orders = {
            lables: lables,
            stockqty: stockqty,  
            stockval: stockval,
            totalstockQty: Math.round(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);
}
OwlMaterialDashboard.template = "owl.OwlMaterialDashboard"
//OwlMaterialDashboard.components = { KpiCard, ChartRenderer }
OwlMaterialDashboard.components = { ChartRenderer }

registry.category("actions").add("owl.material_dashboard", OwlMaterialDashboard)