import { DatePipe } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { JobmasterService } from 'src/app/jobconfiguration/jobmaster/jobmaster.service';
import { RecorderrorreportService } from './recorderrorreport.service';
import { saveAs } from "file-saver";
import { exportDataGrid } from "devextreme/exporter/exceljs/excelExporter";
import { Workbook } from "exceljs";import { error } from 'console';
import { environment } from "src/environments/environment";
import { HomelayoutComponent } from "src/app/Shared/homelayout/homelayout.component";
import { Color, RowComp } from "ag-grid-community";								  
@Component({
  selector: 'app-recorderrorreport',
  templateUrl: './recorderrorreport.component.html',
  styleUrls: ['./recorderrorreport.component.css']
})
export class RecorderrorreportComponent implements OnInit {

  recorderrorreportlst:any=[];
  selectedRows: any = [];
  //baseUrl: string = environment.serviceUrl;
  baseUrl: string = environment.serviceUrl_download;
  prodefid: string = localStorage.getItem("prdefid");
  recorderrlst = [];
  num_in: number = 1;
  num_out: number = 1;	
  startdate:any;
  enddate:any;	
  dateRange: any = [new Date(new Date().setDate(new Date().getDate() ))
    ,new Date(new Date().setDate(new Date().getDate()))];
     
  constructor(private datepipe :DatePipe,
    private jobmasterservice: JobmasterService,
    private toastr: ToastrService,
    private recorderrorservice: RecorderrorreportService,
    private router: Router,
    private route: ActivatedRoute,
    private SpinnerService: NgxSpinnerService) { }
  ngOnInit(): void {
    var todaydate=new Date();
    this.startdate = this.datepipe.transform(todaydate, 'dd-MMM-yyyy');
    this.enddate = this.datepipe.transform(todaydate, 'dd-MMM-yyyy');
    this.onload();
  }

  onload(){
    this.SpinnerService.show();
    let inputdata = [];
    this.recorderrorreportlst=[];
    inputdata.push({
      p_projectdefinitionid: 0,
      p_startdate: this.startdate,
      p_enddate: this.enddate,
      p_jobid : 0,
    });
    this.recorderrorservice.GetRecordErrorReport(inputdata[0]).subscribe(res=>{
      if(res.body != undefined && res.body != null && res.body != ''){  
        console.log(JSON.stringify(JSON.parse(res.body)))     
          this.recorderrorreportlst = JSON.parse(res.body);
          this.SpinnerService.hide();
      }else{
        this.SpinnerService.hide();
      }
    },error=>{
      this.SpinnerService.hide();
      this.toastr.error('Error while getting the Report.');
    });
  }
  onrepdateValueChange(value: Date): void {
    this.startdate = this.datepipe.transform(value[0], 'dd-MMM-yyyy');
    this.enddate = this.datepipe.transform(value[1], 'dd-MMM-yyyy');
    if(this.startdate !=null && this.startdate !=undefined &&
      this.startdate !='' && this.enddate !=null && this.enddate !=''  && this.enddate !=undefined ){
        this.onload();
    }
  } 
download_files(item, mode) {
    debugger;
    console.log("files", item);
    // let data = [];
    let filename = item.filename;
    // data.push({
    //   projectid: +localStorage.getItem('prdefid'),
    //   filepath: item.path
    // });
    this.recorderrorservice
      .Recorderrorfile_Download(localStorage.getItem("prdefid"), item.path)
      .subscribe(
        (res) => {
          debugger;
          if (res.file_ != null && res.file_ != "" && res.file_ != undefined) {
            var content = res.file_;
            let objectURL = "data:application/octet-stream;base64," + res.file_;
            saveAs(objectURL, filename);
            //self.close();
          } else {
            this.toastr.error("File not Found.");
          }
        },
        (error) => {
          this.toastr.error("Error while getting data");
        }
      );
  }
   onExporting(e) {
    debugger;
    const workbook = new Workbook();
    const worksheet = workbook.addWorksheet("QA Error Report");

    exportDataGrid({
      component: e.component,
      worksheet,
      showBorders: true,
      autoFilterEnabled: true,
      rowAlternationEnabled: true,
      columnAutoWidth: true,
      customizeCell(options) {
        //   debugger;
        const { gridCell } = options;
        const { excelCell } = options;

        if (gridCell.rowType == "header") {
          if ((gridCell.column.dataField = "in_files")) {
          }
          if ((gridCell.column.dataField = "out_files")) {
          }
          excelCell.fill = {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "2b4c81" },
          };
          excelCell.font = { color: { argb: "FFFFFF" }, bold: true };
        }
        if (gridCell.rowType === "header" || gridCell.rowType === "data") {
          if (excelCell.fullAddress.row % 2 === 0) {
            excelCell.fill = {
              type: "pattern",
              pattern: "solid",
              fgColor: { argb: "dbedf2" },
            };
          }
        }
        excelCell.border = {
          top: { style: "thin" },
          left: { style: "thin" },
          bottom: { style: "thin" },
          right: { style: "thin" },
          color: { argb: "000000" },
        };
      },
    })
      .then((cellRange) => {
        debugger;
        //row 8
        const col = worksheet.getColumn("A");
        let record_count = 0;
        let col_index = 0;
        let header = worksheet.getRow(1);
        let input_header_count = 0;
        let output_header_count = 0;

        let export_record = [];
       col.eachCell((cell)=>{
          if(cell.address != 'A1'){
            let cell_index = this.recorderrorreportlst.findIndex(x=> x.sno == cell.value);
            export_record.push(this.recorderrorreportlst[cell_index]);
          }
        });

       /* if (this.recorderrorreportlst.length == record_count - 1) {
          export_record = this.recorderrorreportlst;
        } else if (this.selectedRows.length == record_count - 1) {
          export_record = this.selectedRows;
        }*/

        export_record.forEach((element) => {
          if (element.in_files != "" && element.in_files != null) {
            let temp = 0;
            element.in_files.forEach((item) => {
              temp = temp + 1;
            });
            if (temp > this.num_in) {
              this.num_in = temp;
            }
          }

          if (element.out_files != "" && element.out_files != null) {
            let temp = 0;
            element.out_files.forEach((item) => {
              temp = temp + 1;
            });
            if (temp > this.num_out) {
              this.num_out = temp;
            }
          }
        });
        input_header_count = this.num_in + 1;
        output_header_count = this.num_out + 1;
        for (let j = 15+ this.num_in - 1; 15 <= j; j--) {
          input_header_count = input_header_count - 1;
          header.getCell(j).value = "Input Files" + " " + input_header_count;
          // console.log('header',hearder.getCell(row_cell).value);
          header.getCell(j).fill = {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "2b4c81" },
          };
          header.getCell(j).border = {
            top: { style: "thin" },
            left: { style: "thin" },
            bottom: { style: "thin" },
            right: { style: "thin" },
          };
          header.getCell(j).font = { color: { argb: "FFFFFF" }, bold: true };
          header.getCell(j).alignment = { wrapText: true };
        }
        for (
          let h = 15 + this.num_in - 1 + this.num_out;
          15 + this.num_in - 1 < h;
          h--
        ) {
          output_header_count = output_header_count - 1;
          header.getCell(h).value = "Output Files" + " " + output_header_count;
          // console.log('header',hearder.getCell(row_cell).value);
          header.getCell(h).fill = {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "2b4c81" },
          };
          header.getCell(h).border = {
            top: { style: "thin" },
            left: { style: "thin" },
            bottom: { style: "thin" },
            right: { style: "thin" },
          };
          header.getCell(h).font = { color: { argb: "FFFFFF" }, bold: true };
          header.getCell(h).alignment = { wrapText: true };
        }

        //const hearder = worksheet.getRow(1);
        for (let i = 2; i < export_record.length + 2; i++) {
          debugger;
          let row_cell = 15;
          const files_row = worksheet.getRow(i);

          let sno_row = worksheet.getRow(i);
          let sno_value = sno_row.getCell(1).value;

          let index = export_record.findIndex(x=>x.sno == sno_value);

          let input = export_record[index].in_files;
          let output = export_record[index].out_files;

          let input_header = worksheet.getRow(1);					 
          if (
            input != "" &&
            input != null &&
            input != undefined &&
            input.length != 0
          ) {
            input.forEach((element) => {
              if (
                element.filename != "" &&
                element.filename != null &&
                element.filename != undefined &&
                element.path != "" &&
                element.path != null &&
                element.path != undefined
              ) {
                files_row.getCell(row_cell).value = {
                  text: element.filename,
                  hyperlink:
                    this.baseUrl +
                    "api/ReportApi/Image_download?projecdefid=" +
                    this.prodefid +
                    "&path=" +
                    element.path +
                    "&filename=" +
                    element.filename,
                };
              }else{
                files_row.getCell(row_cell).value ="";
              }

              if (i % 2 == 0) {
                files_row.getCell(row_cell).fill = {
                  type: "pattern",
                  pattern: "solid",
                  fgColor: { argb: "dbedf2" },
                };
              }

              files_row.getCell(row_cell).alignment = { wrapText: true };
              files_row.getCell(row_cell).border = {
                top: { style: "thin" },
                left: { style: "thin" },
                bottom: { style: "thin" },
                right: { style: "thin" },
              };

              files_row.getCell(row_cell).font = {
                color: { argb: "3437eb" },
                bold: true,
              };
              row_cell = row_cell + 1;
            });
          }
 let temp_head = input_header.getCell(row_cell).value;
          for(let t = row_cell ;temp_head.toString().toLocaleLowerCase().includes('input');t++){
            if (i % 2 == 0) {
              files_row.getCell(row_cell).fill = {
                type: "pattern",
                pattern: "solid",
                fgColor: { argb: "dbedf2" },
              };
            }
            files_row.getCell(row_cell).value ="";
            files_row.getCell(row_cell).alignment = { wrapText: true };
            files_row.getCell(row_cell).border = {
              top: { style: "thin" },
              left: { style: "thin" },
              bottom: { style: "thin" },
              right: { style: "thin" },
            };

            files_row.getCell(row_cell).font = {
              color: { argb: "3437eb" },
              bold: true,
            };
            row_cell = row_cell + 1;
            temp_head = input_header.getCell(row_cell).value;
          }
          if (
            output != "" &&
            output != null &&
            output != undefined &&
            output.length != 0
          ) {
            output.forEach((element) => {
              if (
                element.filename != "" &&
                element.filename != null &&
                element.filename != undefined &&
                element.path != "" &&
                element.path != null &&
                element.path != undefined
              ) {
                files_row.getCell(row_cell).value = {
                  text: element.filename,
                  hyperlink:
                    this.baseUrl +
                    "api/ReportApi/Image_download?projecdefid=" +
                    this.prodefid +
                    "&path=" +
                    element.path +
                    "&filename=" +
                    element.filename,
                };
              }else{
                files_row.getCell(row_cell).value = "";
              }

              if (i % 2 == 0) {
                files_row.getCell(row_cell).fill = {
                  type: "pattern",
                  pattern: "solid",
                  fgColor: { argb: "dbedf2" },
                };
              }
              files_row.getCell(row_cell).alignment = { wrapText: true };
              files_row.getCell(row_cell).border = {
                top: { style: "thin" },
                left: { style: "thin" },
                bottom: { style: "thin" },
                right: { style: "thin" },
              };
              files_row.getCell(row_cell).font = {
                color: { argb: "3437eb" },
                bold: true,
              };
              row_cell = row_cell + 1;
            });
          }

          for (
            let t = row_cell;
            row_cell <= 15 + this.num_in + this.num_out - 1;
            row_cell++
          ) {
            files_row.getCell(row_cell).value = "";
            if (i % 2 == 0) {
              files_row.getCell(row_cell).fill = {
                type: "pattern",
                pattern: "solid",
                fgColor: { argb: "dbedf2" },
              };
            }
            files_row.getCell(row_cell).alignment = { wrapText: true };
            files_row.getCell(row_cell).border = {
              top: { style: "thin" },
              left: { style: "thin" },
              bottom: { style: "thin" },
              right: { style: "thin" },
            };
          }

          col_index = col_index + 1;
        }
      })

      .then(() => {
        var currentdate = new Date();
        var datetime =
          currentdate.getDate() +
          "-" +
          (currentdate.getMonth() + 1) +
          "-" +
          currentdate.getFullYear() +
          "_" +
          currentdate.getHours() +
          "_" +
          currentdate.getMinutes() +
          "" +
          currentdate.getSeconds();
        workbook.xlsx.writeBuffer().then((buffer) => {
          saveAs(
            new Blob([buffer], { type: "application/octet-stream" }),
            "QAErrorReport_" + datetime + ".xlsx"
          );
        });
      });
	   
    e.cancel = true;
  }

  selectionChangedHandler() {
    console.log("select row", this.selectedRows);
  }
}
