import { Component, OnInit, ViewChild } from "@angular/core";
import { DatePipe } from "@angular/common";
import {DxDataGridModule,DxButtonModule,DxPieChartComponent} from "devextreme-angular";
import { exportDataGrid } from "devextreme/exporter/exceljs/excelExporter";
import { Workbook } from "exceljs";
import { saveAs } from "file-saver";
import { JobmasterService } from "src/app/jobconfiguration/jobmaster/jobmaster.service";
import { ToastrService } from "ngx-toastr";
import { DashboardService } from "src/app/dashboard/dashboard.service";
import { ProjectDefinition } from "src/app/projectconfiguration/projectconfiguration/projectdefinition";
import { ProcesswiseproductionreportserviceService } from "../processwiseproductionreport/processwiseproductionreportservice.service";

import { Router, NavigationExtras, ActivatedRoute } from "@angular/router";
import { getMarkup, exportFromMarkup } from "devextreme/viz/export";
import { DashboardreportService } from "./dashboardreport.service";
@Component({
  selector: "app-dashboardreport",
  templateUrl: "./dashboardreport.component.html",
  styleUrls: ["./dashboardreport.component.css"],
})
export class DashboardreportComponent implements OnInit {
  @ViewChild(DxPieChartComponent, { static: false })
  pieChart: DxPieChartComponent;
  p_mode = "report";
  //p_mode='landing';
  Originallst: any = [];
  Dashboardlst: any = [];
  totatcount: any = [];
  jobProductTypeList: any = [];
  _ddlProjecttypeSettings: {};
  _ddljobSettings: {};
  userid: string = localStorage.getItem("userid");
  _userselectedItems: any[] = [];
  metaall: any[] = [];
  startdate: any;
  enddate: any;
  projectdefinitionid: number;
  joblst: any;
  _jobselectedItems: any = [];
  jobid: any;
  total_source: any;
  invaild: any;
  total_project: any;
  duplicatecount: any;
  project_title: string;
  gettotalvalues: any;
  filterValue: any;
  job_title: any;
  pielst: any = [];

  intervalId
  auto_refresh: boolean = false;
  constructor(
    private datepipe: DatePipe,
    private jobmasterservice: JobmasterService,
    private toastr: ToastrService,
    private processwiseproductionreport: ProcesswiseproductionreportserviceService,
    private dashboardservice: DashboardreportService,
    private router: Router,
    private route: ActivatedRoute
  ) {}


  ngOnInit(): void {
    this.route.queryParams.subscribe((params) => {
      console.log(params);
      this.p_mode = params.mode_p;
      this.projectdefinitionid = params.prodefid;
    });
    //this.toastr.error(this.p_mode +', '+ this.projectdefinitionid)
    this._ddljobSettings = {
      singleSelection: true,
      idField: "jobid",
      textField: "title",
      // selectAllText: 'Select All',
      // unSelectAllText: 'UnSelect All',
      itemsShowLimit: 7,
      allowSearchFilter: true,
    };
    this.onload();
  }

  onload() {
    this._ddlProjecttypeSettings = {
      singleSelection: true,
      idField: "projectdefinitionid",
      textField: "project_subtitle",
      // selectAllText: 'Select All',
      // unSelectAllText: 'UnSelect All',
      itemsShowLimit: 7,
      allowSearchFilter: true,
    };
    this.jobmasterservice.getJobProductType(this.userid).subscribe((res) => {
      if (
        res !== undefined &&
        res !== null &&
        res[0] !== undefined &&
        res[0] !== null
      ) {
        if (JSON.parse(res[0]).length > 0) {
          this.jobProductTypeList = JSON.parse(res[0]);
          console.log(this.jobProductTypeList);
          this._userselectedItems = this.jobProductTypeList.filter(
            (x) =>
              x.projectdefinitionid ==
              this.jobProductTypeList[0].projectdefinitionid
          );
          this.projectdefinitionid =
            this.jobProductTypeList[0].projectdefinitionid;
          this.project_title = this.jobProductTypeList[0].project_subtitle;
        }
      }
    });
  }

  onrepdateValueChange(value: Date): void {
    this._jobselectedItems = [];
    this.Dashboardlst = [];
    this.startdate = this.datepipe.transform(value[0], "dd-MMM-yyyy");
    this.enddate = this.datepipe.transform(value[1], "dd-MMM-yyyy");
    if (
      this.projectdefinitionid != 0 &&
      this.startdate != null &&
      this.startdate != undefined &&
      this.startdate != "" &&
      this.enddate != null &&
      this.enddate != "" &&
      this.enddate != undefined &&
      this.jobid != null &&
      this.jobid != undefined
    ) {
      this.loadjob(this.projectdefinitionid);
    } else if (
      this.projectdefinitionid != 0 &&
      this.startdate != null &&
      this.startdate != undefined &&
      this.startdate != "" &&
      this.enddate != null &&
      this.enddate != "" &&
      this.enddate != undefined
    ) {

      this.loadjob(this.projectdefinitionid);
    }
  }

  onItemSelect(item: any, mode) {
    if (mode === "prodefid") {
      this.projectdefinitionid = item.projectdefinitionid;
      this.project_title = item.project_subtitle;

      if (
        this.projectdefinitionid != 0 &&
        this.startdate != null &&
        this.startdate != undefined &&
        this.startdate != "" &&
        this.enddate != null &&
        this.enddate != "" &&
        this.enddate != undefined &&
        this.jobid != null &&
        this.jobid != undefined
      ) {
        this.loadjob(this.projectdefinitionid);
      } else if (
        this.projectdefinitionid != 0 &&
        this.startdate != null &&
        this.startdate != undefined &&
        this.startdate != "" &&
        this.enddate != null &&
        this.enddate != "" &&
        this.enddate != undefined
      ) {

        this.loadjob(this.projectdefinitionid);
      }
      this.totatcount = [];
    } else if (mode === "job") {
      this.totatcount = [];
      this.job_title = item.title;
      this.jobid = item.jobid;
      if (
        this.projectdefinitionid != 0 &&
        this.startdate != null &&
        this.startdate != undefined &&
        this.startdate != "" &&
        this.enddate != null &&
        this.enddate != "" &&
        this.enddate != undefined &&
        this.jobid != null &&
        this.jobid != undefined
      ) {

        this.getproductionreport(this.projectdefinitionid);
      }
    }
  }

  onItemDeSelect(item: any, mode) {
    //console.log(item);
    if (mode === "job") {
      this.Dashboardlst = [];
      this.p_mode = "report";
      this.totatcount = [];

    }
  }

  getproductionreport(prodefid) {
    const inputdata = [];
    inputdata.push({
      p_projectdefinitionid: prodefid,
      p_startdate: this.startdate,
      p_enddate: this.enddate,
      p_jobid: this.jobid,
      mode_report: "dashboard_old",
      multipleprojectid_p:prodefid.toString()
    });
    this.dashboardservice.GetDashboardReport(inputdata[0]).subscribe((res) => {
      debugger;
      if (res.body != null && res.body != undefined) {
        let resarr = [];
        this.Dashboardlst = [];
        this.Originallst = [];
        this.totatcount = [];
        resarr = res.body.totalcout;
        resarr.forEach((val) => {
          this.totatcount.push(JSON.parse(val));
        });
        this.total_source =
          this.totatcount[0].ToatalLots === undefined
            ? 0
            : this.totatcount[0].ToatalLots;
        this.total_project =
          this.totatcount[0].DispatchComplete === null
            ? 0
            : this.totatcount[0].DispatchComplete;
        this.invaild =
          this.totatcount[0].InvalidLots === null
            ? 0
            : this.totatcount[0].InvalidLots;
        this.duplicatecount =
          this.totatcount[0].duplicatelot === null
            ? 0
            : this.totatcount[0].duplicatelot;
        this.pielst = [
          {
            title: "Total Source",
            value: this.total_source,
          },
          {
            title: "Total Project",
            value: this.total_project,
          },
          {
            title: "Invaild",
            value: this.invaild,
          },
          {
            title: "Duplicate Count",
            value: this.duplicatecount,
          },
        ];
        resarr = [];
        resarr = res.body.reportlst;
        resarr.forEach((val) => {
          this.Originallst.push(JSON.parse(val));
        });
        this.Dashboardlst = this.Originallst;
       
      }
    });
  }

  loadjob(prodefid) {
    let  multiple_prodefid :string = "";
    this._userselectedItems.forEach(element => {
      if(multiple_prodefid == ""){
        multiple_prodefid = element.projectdefinitionid.toString();
      }else{
        multiple_prodefid =multiple_prodefid + ','+element.projectdefinitionid.toString();
      }
    });	
    const input = [];
    input.push({
      p_projectdefinitionid: prodefid,
      p_startdate: this.startdate,
      p_enddate: this.enddate,
      multipleprojectid_p:multiple_prodefid,
      isnormaluser:false,
      p_userid:this.userid
    });

    this.processwiseproductionreport.GetJobTitle(input[0]).subscribe((res) => {
      debugger;
      if (res.body != null && res.body != undefined) {
        this.joblst = [];
        this._jobselectedItems = [];
        this.Dashboardlst = [];
        this.joblst = JSON.parse(res.body);
      }
    });
  }
  onexport(e) {
    //this.dataGrid.instance.getDataSource().items();
    const workbook = new Workbook();
    const worksheet = workbook.addWorksheet("Dashboard Report");
    console.log(this.project_title);
    var projecttitle = this.project_title;
    var totallots = this.total_source;
    var totalproj = this.total_project;
    var invalid = this.invaild;
    var duplicate = this.duplicatecount;
    exportDataGrid({
      component: e.instance,
      worksheet,
      showBorders: true,
      autoFilterEnabled: true,
      rowAlternationEnabled: true,
      columnAutoWidth: true,
      topLeftCell: { row: 9, column: 1 },
      customizeCell(options) {
        debugger;
        const { gridCell } = options;
        const { excelCell } = options;
        if (gridCell.rowType == "header") {
          debugger;
          excelCell.fill = {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "2b4c81" },
          };
          excelCell.font = { color: { argb: "FFFFFF" }, bold: true };
        }
        if (gridCell.rowType === "data") {
          debugger;
          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) => {
        // header
        const headerRow = worksheet.getRow(2);
        headerRow.height = 30;
        worksheet.mergeCells(2, 1, 2, 7);

        headerRow.getCell(1).value = projecttitle;
        headerRow.getCell(1).font = {
          name: "Segoe UI Light",
          size: 22,
          bold: true,
        };
        headerRow.getCell(1).alignment = {
          horizontal: "center",
          wrapText: true,
        };

        var rowstart = 4;
        for (var i = 0; i < 4; i++) {
          const row = worksheet.getRow(rowstart);
          if (i == 0) {
            row.getCell(1).value = "Total No. of Sources Created";
            row.getCell(1).alignment = { wrapText: true };
            row.getCell(2).value = totallots;
          } else if (i == 1) {
            row.getCell(1).value = "Total No. of Projects Collected";
            row.getCell(1).alignment = { wrapText: true };
            row.getCell(2).value = totalproj;
          } else if (i == 2) {
            row.getCell(1).value = "Invalid Record Count";
            row.getCell(1).alignment = { wrapText: true };
            row.getCell(2).value = invalid;
          } else if (i == 3) {
            row.getCell(1).value = "Duplicate Count";
            row.getCell(1).alignment = { wrapText: true };
            row.getCell(2).value = duplicate;
          }
          row.getCell(1).border = {
            top: { style: "thin" },
            left: { style: "thin" },
            bottom: { style: "thin" },
            right: { style: "thin" },
          };
          row.getCell(2).border = {
            top: { style: "thin" },
            left: { style: "thin" },
            bottom: { style: "thin" },
            right: { style: "thin" },
          };
          rowstart++;
        }
      })
      .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" }),
            "Dashboardreport_" + datetime + ".xlsx"
          );
        });
      });
    e.instance.cancel = true;
  }

  onExporting(e) {
    const workbook = new Workbook();
    const worksheet = workbook.addWorksheet("Dashboard Report");

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

        if (gridCell.rowType == "header") {
          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(() => {
      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" }),
          "Dashboardreport_" + datetime + ".xlsx"
        );
      });
    });
    e.cancel = true;
  }
  reportclick(data) {
    const queryParams = {};
    const navigationExtras: NavigationExtras = {
      queryParams,
      state: {
        workflowid: this.projectdefinitionid,
        fromdate: this.startdate,
        todate: this.enddate,
        jobid: this.jobid,
        mode: "dashboard",
        job_title: this.job_title,
      },
    };
    if (data == "1") {
      this.router.navigate(
        ["/reports/productiondashboardstagewisereport"],
        navigationExtras
      );
    } else if (data == "2") {
      this.router.navigate(
        ["/reports/userwiseproductionlogreport"],
        navigationExtras
      );
    } else if (data == "3") {
      this.router.navigate(
        ["/reports/processwiseproductionreport"],
        navigationExtras
      );
    } else if (data == "4") {
      this.router.navigate(
        ["/reports/userwiseproductionreport"],
        navigationExtras
      );
    }
  }
  pointClickHandler(e) {
    this.toggleVisibility(e.target);
  }
  legendClickHandler(e) {
    const arg = e.target;
    const item = e.component.getAllSeries()[0].getPointsByArg(arg)[0];
    this.toggleVisibility(item);
  }
  toggleVisibility(item) {
    if (item.isVisible()) {
      item.hide();
    } else {
      item.show();
    }
  }
  exportChart(e) {
    this.pieChart.instance.exportTo("Exported Chart", "PNG");
    let sample: any;
    sample = this.pieChart.onExporting;
  }

  // gokul 06-07-23
// auto refresh

}
