// dashboard.component.ts
import { Component, OnInit,ViewChild } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { VlexreportService } from './vlexreport.service';
import { DxDataGridComponent } from 'devextreme-angular';
import { LotComment, LotCommentService } from '../masters/lot-comment/lot-comment.service';
import * as ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';

@Component({
  selector: 'app-vlexreport',
  templateUrl: './vlexreport.component.html',
  styleUrls: ['./vlexreport.component.css']
})
export class VlexreportComponent implements OnInit {
  @ViewChild('gridContainer', { static: false }) gridContainer: any;
  @ViewChild(DxDataGridComponent, { static: false }) 
  dataGrid!: DxDataGridComponent;

  batchData: any[] = [];
  batchDatafinal: any[] = [];
  statusChartData: any[] = [];
  jobmonthwisedata: any[] = [];
  customPalette: string[] = [];   
  roleId = 0;
  querylist: any[]= [];
  constructor(private http: HttpClient,
    private vlexreportservice : VlexreportService,
    private lotCommentService: LotCommentService
  ) {}

ngOnInit() {
    this.roleId = +localStorage.getItem('roleid');
    const input = { p_projectdefinitionid: 367 };

    this.vlexreportservice.GetVlexreportdata(input).subscribe((res: any) => {
      debugger;
      if (res && res.body) {
        // parse data
        this.batchData = JSON.parse(res.body.joblist[0]);
    this.batchDatafinal = JSON.parse(res.body.joblist[0]);
        // ======= ADD FIXED SERIAL NUMBER HERE =======
        // this.batchData = (this.batchData || []).map((item: any, index: number) => ({
        //   ...item,
        //   slNo: index + 1 // fixed, continuous serial number across all pages
        // }));
        // ============================================

        console.log('batchData with slNo', this.batchData);

        // existing computations (unchanged)
        const totalCount = this.batchData.length;

const noCaseCount = this.batchData.filter(
  (row: any) => row.bmpcount === 0 || row.bmpcount === '0'
).length;


const deliveredCount = this.batchData.filter(
  //(row: any) => row.datedelivered != null && row.datedelivered !== ''
  (row: any) =>  row.status === 'Delivered'
).length;

console.log('Total rows with valid datedelivered:', deliveredCount);

const holdCount = this.batchData.filter(
  (row: any) =>
  
    row.querystatus === 'Submitted'
).length;

// console.log('Total addressed query count:', holdCount);

// ✅ QA in progress — QAStatus = "WIP"
const qa_inprogress = this.batchData.filter(
  (row: any) =>
    
    row.status === 'QA'
).length;

// ✅ Total received — ConversionStatus = "YTS"
const total_received = this.batchData.filter(
  (row: any) =>
    
    row.status=== 'Production YTS'
).length;

// ✅ Conversion in progress — ConversionStatus = "YTS"
const con_inprogress = this.batchData.filter(
  (row: any) =>
    
    row.status === 'Production'
).length;

console.log('QA In Progress:', qa_inprogress);
console.log('Total Received:', total_received);
console.log('Conversion In Progress:', con_inprogress);
        const download_inprog =
          totalCount -
          (noCaseCount +
            con_inprogress +
            qa_inprogress +
            total_received +
             holdCount +
            deliveredCount);

        this.statusChartData = [
          { status: 'Download In-Progress', count: download_inprog },
          { status: 'Conversion YTS', count: total_received },
          { status: 'Conversion In-Progress', count: con_inprogress },
          { status: 'QA_InProgress', count: qa_inprogress },
           { status: 'On_Query', count: holdCount },
          { status: 'Delivered', count: deliveredCount },
          { status: 'Total Received', count: totalCount },
          { status: 'No Case', count: noCaseCount }
        ];

        this.customPalette = [
          '#90ac7d',
          '#ffc107',
          '#ee7b26',
          '#7f669c',
          '#28a745',          
          '#2196f3', 
          '#dc3545'      
        ];

        this.jobmonthwisedata = JSON.parse(res.body.monthwisejob[0]);
        console.log(this.jobmonthwisedata);
      }
    });
  }
onExporting(e: any) {
    //this.loadComments();
    e.cancel = true;
    this.lotCommentService.getCommentsByProject(367).subscribe({
      next: (res) => {
        this.querylist = res;
        const grid = e.component;
        const dataSource = grid.getDataSource();

        dataSource.store().load().then((allData: any[]) => {
            if (!allData || allData.length === 0) return;

            const workbook = new ExcelJS.Workbook();
            const now = new Date();
            const formattedDate =
                now.getFullYear() + '-' +
                String(now.getMonth() + 1).padStart(2, '0') + '-' +
                String(now.getDate()).padStart(2, '0') + '_' +
                String(now.getHours()).padStart(2, '0') + 'h' +
                String(now.getMinutes()).padStart(2, '0') + 'm';

            const sheetName = 'vLex_Job_Report_' + formattedDate;
            const fileName = sheetName + '.xlsx';

            const worksheet = workbook.addWorksheet(sheetName);
            const querySheet = workbook.addWorksheet('Queries');

            const allColumns = (grid.getVisibleColumns && grid.getVisibleColumns()) || (grid.getColumns && grid.getColumns()) || [];

            // --- Exclusions for Main Sheet ---
            const excludeMainColumns = ['querytype','querydescription','querystatus','startpage','endpage','holdcomment'];

            // --- MAIN SHEET ---
            const mainHeaders: string[] = [];
            allColumns.forEach(c => {
                if (c.dataField && !excludeMainColumns.includes(c.dataField)) {
                    mainHeaders.push(c.caption || c.dataField);
                }
            });
            worksheet.addRow(mainHeaders);
            worksheet.getRow(1).font = { bold: true };

            allData.forEach(row => {
                const mainRow: any[] = [];
                allColumns.forEach(c => {
                    if (c.dataField && !excludeMainColumns.includes(c.dataField)) {
                        // Take exact value from DB as-is
                        const value = row[c.dataField];
                        mainRow.push(value != null ? value : '');
                    }
                });
                worksheet.addRow(mainRow);
            });

            // --- QUERIES SHEET FIELDS & CAPTIONS ---
            const queryFieldsOrder = [
                'reportername', 'volumne', 'edition', 'issue', 'dateofpublication',
                'startpage','endpage','status', 'querytype',  'comment_text'
            ];

            const queryFieldsCaptions = [
                'Reporter Name', 'Volume', 'Edition', 'Issue', 'Publishing Date',
                'Start Page','End Page', 'Query Status','Query Type',  'Query Description'
            ];

            const queryHeaders = ['S.No', ...queryFieldsCaptions];
            querySheet.addRow(queryHeaders);
            querySheet.getRow(1).font = { bold: true };

            let queryIndex = 1;
            this.querylist.forEach(row => {
              debugger;
              console.log('row--- ',row);
                // Only include rows with query info
                if (row.comment_text || row.querytype || row.status) {
                    const queryRow: any[] = [queryIndex++]; // S.No
                    queryFieldsOrder.forEach(f => {
                        // Take exact value from DB as-is
                        const value = row[f];
                        queryRow.push(value != null ? value : '');
                    });
                    querySheet.addRow(queryRow);
                }
            });

            // --- AUTO FIT COLUMNS ---
            [worksheet, querySheet].forEach(sheet => {
                sheet.columns.forEach((column: any) => {
                    let maxLength = 0;
                    column.eachCell({ includeEmpty: true }, (cell: any) => {
                        const len = cell.value ? cell.value.toString().length : 10;
                        if (len > maxLength) maxLength = len;
                    });
                    column.width = maxLength + 3;
                });
            });

            // --- WRITE FILE ---
            workbook.xlsx.writeBuffer().then((buffer: any) => {
                saveAs(new Blob([buffer], { type: 'application/octet-stream' }), fileName);
            });
        });   
      },
      error: (err) => console.error('Error loading comments:', err)
    });    
}

customizeTooltip(pointInfo) {
  return {
    text: `${pointInfo.argument}: ${pointInfo.value}` // shows status and count
  };
}
customizeBarTooltip(pointInfo) {
  return {
    text: `${pointInfo.seriesName}: ${pointInfo.value}` // Shows series name and value
  };
}
getTotalJobs(): number {
  return this.statusChartData.reduce((sum, item) => sum + item.count, 0);
}
// Convert "2025-07" -> "July 2025"
formatMonthYear(e: any) {
  const [year, month] = e.value.split("-");
  const date = new Date(+year, +month - 1);
  return date.toLocaleString("default", { month: "long", year: "numeric" });
}
// Show "Status: Count (XX%)"
customizeLabel(point: any) {
  const percent = (point.percent * 100).toFixed(1); // percent with 1 decimal
  return `${point.argumentText}: ${point.valueText} (${percent}%)`;
}
  prepareCharts(data: any[]) {
    // Status distribution
    const statusCounts: any = {};
    data.forEach(item => {
      statusCounts[item.status] = (statusCounts[item.status] || 0) + 1;
    });
    this.statusChartData = Object.keys(statusCounts).map(key => ({
      status: key,
      value: statusCounts[key]
    }));
  }
 customizeToolbar_old(e: any) {
  e.toolbarOptions.items.forEach((item: any) => {
    
    // Find the default export button
    if (item.name === 'exportButton') {
      item.options = {
        ...item.options,
            widget: 'dxButton',
        type: 'default', // button type
        stylingMode: 'contained', // makes it solid color
        elementAttr: {
          class: 'custom-excel-btn' // custom CSS class
        }
      };
    }
  });
} 
customizeToolbar(e: any) {
  e.toolbarOptions.items.unshift({
    location: 'after',
    widget: 'dxButton',
    options: {
      type: 'default',
      hint: 'Clear Filters',
      stylingMode: 'contained',
      icon: 'filter-icon-image',
      text: '',  // no text
      elementAttr: {
        class: 'clear-filter-btn' // Add Font Awesome class here
      },
      onClick: () => this.clearAllFilters()
    }
  });
}

  clearAllFilters() {
    this.gridContainer.instance.clearFilter();
  }

}
