import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators, NgForm } from '@angular/forms';
import { ProjectdefinitionmasterService } from 'src/app/projectconfiguration/projectdefinitionmaster/projectdefinitionmaster.service';
import { ToastrService } from 'ngx-toastr';
import { JobmasterService } from 'src/app/jobconfiguration/jobmaster/jobmaster.service';
import { Router } from '@angular/router';
import { BsModalRef, BsModalService, ModalOptions } from 'ngx-bootstrap';
import { SupplementService } from './supplement.service';
import { Supplement, Batchdata } from './supplement';
import { NgxSpinnerService } from 'ngx-spinner';
import { PrintSupplementService } from 'src/app/masters/printsupplement/printsupplement.service';
import { PrintSupplement } from 'src/app/masters/printsupplement/printsupplement';
@Component({
  selector: 'app-supplement',
  templateUrl: './supplement.component.html',
  styleUrls: ['./supplement.component.css']
})
export class SupplementComponent implements OnInit {
  userid: number;
  projectdefinitions: any;
  searchText: string;
  jobLists: any[];
  projectdefinitionid: 0;
  projectid: number;
  jobid: number;
  operation: string;
  // sorting variables
  key = 'Role Name';
  reverse = false;
  // pagination variables
  p = 1;
  itemsPerPage = 10;

  // Page permission
  actionRights: any;
  readOnly = false; add = false; edit = true; delete = true;
  lotstatus: string;
  chaplist: any = [];
  totallots: number;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered modal-lg',
    ignoreBackdropClick: true
  };
  SupplementForm: FormGroup;
  ChapterForm: FormGroup;
  supplementModelRef: BsModalRef;
  supplementeditModelRef: BsModalRef;
  selectedChapter: any = [];
  selectedlots = 0;
  batchlist: any = [];
  Orginalfiletypelist: any = [];
  callType: any = {};
  msg1: string;
  ButtonType: string;
  projectname: string;
  jobname: string;
  detaildate: any = [];
  detaildate1: any = [];
  statustext: string;
  project_subtitle: string;
  jobno: number;
  batchname: string;
  mergeproof: number;
  supplementcreated = false;
  productionWorkFlowData: any = [];
  supplementtypeid: number = 0;
  supplementTypes: any = [];
  model: any = {
    batchname: '',
    supplementtypeid: 0,
    mergedproof: false
  };
  printsupplements: PrintSupplement[] = [];
  printsupplementsactive: PrintSupplement[] = [];
  supplementnumber: string;
  year: string;
  printsupplementid: number;
  publicationid: string;
  constructor(
    private formBuilder: FormBuilder,
    private toastr: ToastrService,
    private router: Router,
    private projectdefinitionservice: ProjectdefinitionmasterService,
    private jobmasterservice: JobmasterService,
    private modalService: BsModalService,
    private supplementService: SupplementService,
    private SpinnerService: NgxSpinnerService,
    private printsupplementservice: PrintSupplementService,
    // private formBuilder: FormBuilder
  ) {
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      sessionStorage.setItem('Supplement_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      sessionStorage.setItem('Supplement_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = sessionStorage.getItem('Supplement_userRights');
    }
  }

  ngOnInit(): void {
    this.SupplementForm = this.formBuilder.group({
      batchname: ['', [Validators.required]],
      supplementtypeid: [0],
      jobno: ['', [Validators.required]],
      mergedproof: [false, [Validators.required]],
      active: [1],
      producttype: [],
    });

    this.ChapterForm = this.formBuilder.group({
      batchid: [0],
      lotid: [0],
      chaptertype: [''],
      tabcardtitle: [''],
      istabcard: [0],
      isprocessed: [0],
      sequence: [0],
      selected: []
    });

    this.getUserRights();
    this.userid = +localStorage.getItem('userid');
    this.getAllProjectDefinition();
    this.LoadBatch();
    this.getProdctionWorkFlow();
    this.GetAllSupplementType();
    this.getAllPrintSupplement();
  }
  getProdctionWorkFlow() {
    this.supplementService.GetProductionWorkflow().subscribe(res => {
      if (res.status === 200) {
        if (res.body.length > 0) {
          this.productionWorkFlowData = JSON.parse(res.body[0])
        }
      }
      //this.productionWorkFlowData = res;
    }, err => {
      this.toastr.error('Errro in getting ProductionWorkFlow')
    })
  }
  LoadBatch() {
    this.SpinnerService.show();
    this.supplementService.GetByIssupplement(1).subscribe(res => {
      if (res.body[0] != null && res.body[0] !== undefined) {
        console.log('batchlist=', JSON.parse(res.body[0]));
        this.batchlist = JSON.parse(res.body[0]);
        this.Orginalfiletypelist = JSON.parse(res.body[0]);
        this.SpinnerService.hide();
      }
    }, error => {
      this.SpinnerService.hide();
      this.toastr.error('Error while getting data');
    });
  }

  modeled() {
    this.ButtonType = this.callType.stype;
    if (this.ButtonType === 'Update') {
      this.SpinnerService.show();
      // this.LoadDetails=function(this.data, this.data1) {
      this.supplementService.Getsuppview(this.callType.deta1, this.callType.deta).subscribe(res => {
        const checkedItems = [];

        if (res.body[0] != null && res.body[0] !== undefined) {
          console.log('batchlist=', JSON.parse(res.body[0]));
          this.detaildate1 = JSON.parse(res.body[0]);
          // this.detaildate = res.body;
          this.statustext = 'Supplement Processed.';

          // All the lots are added in Supplement add/update button will be disabled. on 4/21/2020
          // this.supplementcreated = d.data.iSupplement;

          this.project_subtitle = this.detaildate1[0].project_subtitle;
          this.jobno = this.detaildate1[0].jobno;
          this.batchname = this.detaildate1[0].batchname;
          this.supplementtypeid = +this.detaildate1[0].supplementtypeid;
          this.mergeproof = this.detaildate1[0].mergedproof;
          // this.mergeproof = this.detaildate1[0].mergedproof===1?true:false;
          //  angular.forEach(this.detaildate, function (ischeck) {
          this.detaildate1.forEach(ischeck => {
            if (ischeck.ischeck === 1) {
              ischeck.ischeck = true;
              ischeck.ishide = true;
            } else {
              ischeck.ischeck = false;
              ischeck.ishide = false;
              this.supplementcreated = false;
            }
          });
          this.detaildate = this.detaildate1;

          this.supplementService.GetisProcessing(this.jobid).subscribe(res2 => {
            console.log(res2[0]);
            const isprocessing = JSON.parse(res2[0]);

            // Commented
            // if (isprocessing[0].count !== 0) {
            //   this.supplementcreated = true;
            //   this.toastr.error('Job In-Progress cannot modify the Supplement');
            // } else {

            //   this.supplementService.GetisProcessing2(this.jobid).subscribe(res3 => {
            //     console.log(res3[0]);
            //     const isprocessing1 = JSON.parse(res3[0]);
            //     if (isprocessing1[0].count !== 0) {
            //       this.supplementcreated = true;
            //       this.toastr.error('Job In-Progress cannot modify the Supplement');
            //     } else {

            //     }
            //   }, error => {
            //     this.SpinnerService.hide();
            //     this.toastr.error('Error in getting Project Meta-data Records');
            //   });
            // }

          }, error => {
            this.SpinnerService.hide();
            this.toastr.error('Error in getting Project Meta-data Records');
          });


          //  if (res.data.isProcessing !== '0') {
          //    this.supplementcreated = true;
          //    this.statustext = 'Job In-Progress cannot modify the Supplement.';
          //  }
        }
      }, error => {
        this.SpinnerService.hide();
        this.toastr.error('Error in getting Project Meta-data Records');
      });

      this.SpinnerService.hide();
    } else if (this.ButtonType === 'Add') {
      if (this.jobid) {
        this.LoadChapter(this.jobid);
      }
      this.SpinnerService.hide();
    }
  }

  // function to get user rights
  getUserRights() {
    const btnToEnable = JSON.parse(this.actionRights);
    if (btnToEnable.length > 0) {
      this.readOnly = true;
      btnToEnable.forEach(d => {
        if (d !== undefined) {
          if (d === 2) {
            this.add = true;
          } else if (d === 3) {
            this.edit = true;
          } else if (d === 4) {
            this.delete = true;
          }
        }
      });
    }
  }

  getAllProjectDefinition() {
    const input = [];
    input.push({ userid: this.userid });
    this.projectdefinitions = [];
    let projectDefinitionsTmp = [];
    this.projectdefinitionservice.GetAllForSupplement(input[0]).subscribe(res => {
      if (res.body[0] !== null && res.body[0] !== undefined) {
        projectDefinitionsTmp = JSON.parse(res.body[0]);
        // this.projectdefinitions = projectDefinitionsTmp.map(k => ({
        //   projectdefinitionid: k.projectdefinitionid,
        //   project_subtitle: k.project_subtitle,
        //   projectname: k.projectname,
        //   active: k.active
        // }));
        this.projectdefinitions = JSON.parse(res.body[0]);
        this.projectid = this.projectdefinitions[0].projectid;
        this.projectname = this.projectdefinitions[0].projectname;
        this.changeProject(this.projectid);
        console.log('this.projectdefinitions=', this.projectdefinitions);
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  changeProject(projectid) {
    if (+projectid) {
      this.projectname = this.projectdefinitions.find(b => b.projectid === +projectid).projectname;
      console.log('projectdefinitionid=', projectid);
      this.getJobList(projectid);
    }
  }

  getJobList(projectid) {
    this.SpinnerService.show();
    this.jobmasterservice.getJobByProjectDefinitionid(projectid).subscribe(res => {
      if (res !== undefined && res !== null && res[0] !== undefined && res[0] !== null) {
        if (JSON.parse(res[0]).length > 0) {
          let list: any[];
          list = JSON.parse(res[0]);
          this.jobLists = list;
          this.jobid = this.jobLists[0].jobid;
          this.jobname = this.jobLists[0].title;
          this.batchlist = this.Orginalfiletypelist.filter(y => y.jobid === this.jobid);
        }
      }
      this.SpinnerService.hide();
    }, error => { this.toastr.error('Error while getting data'); });
  }

  changeJob1(jobid) {
    this.LoadChapter(jobid);
  }

  changeJob(jobid) {
    this.SpinnerService.show();
    this.jobid = + jobid;
    this.jobname = this.jobLists.find(b => b.jobid === +jobid).title;
    this.batchlist = this.Orginalfiletypelist.filter(b => b.jobid === +jobid);
    this.SpinnerService.hide();
  }

  LoadChapter(jobid) {
    this.supplementService.Getjobstatecount(jobid).subscribe(res => {
      const isprocessing = JSON.parse(res[0]);
      //  Commented
      // if (isprocessing[0].count !== 0) {
      // if (JSON.parse(res[0]).length > 0) {
      //   console.log('Getjobstatecount=', JSON.parse(res[0]));
      //   this.lotstatus = 'Chapters are in progress for this job, Please complete the processing files and create the Supplement';
      //   return;
      // } else {
      this.supplementService.GetChapterDetailsbyJobid(jobid).subscribe(res2 => {
        if (res2 !== undefined && res2 !== null && res2[0] !== undefined && res2[0] !== null) {
          if (JSON.parse(res2[0]).length > 0) {
            this.chaplist = JSON.parse(res2[0]);
            console.log('chaplist=', this.chaplist);
            this.lotstatus = '';
          }
          this.totallots = this.chaplist.length;
          if (this.chaplist.length === 0) {
            this.lotstatus = 'No Lots available for mapping';
          }
        }
      }, error => { this.toastr.error('Error while getting data'); });
      // }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }

  Getdetailview(template: TemplateRef<any>, batchdata?: Batchdata) {
    this.callType.stype = 'Update';
    this.callType.deta = batchdata.batchid;
    this.callType.deta1 = batchdata.jobid;

    this.modeled();
    this.supplementeditModelRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
    // this.LoadBatch();
  }

  Opensupplemnt(template: TemplateRef<any>, type, supplement?: Supplement) {
    // Validation For Already EXIST Supplement
    const batchavailable = this.batchlist.filter(x => x.jobid === this.jobid).length;
    if (batchavailable === 0) {
      this.supplementService.GetisProcessing(this.jobid).subscribe(res => {
        console.log(res[0]);
        const isprocessing = JSON.parse(res[0]);
        // if (isprocessing[0].count !== 0) {
        //  this.toastr.error('Job In-Progress cannot modify the Supplement');
        // } else {
        this.supplementService.Finalsubmission(this.jobid).subscribe(res2 => {
          const finalsubmission = JSON.parse(res2[0]);
          if (finalsubmission[0].lotid !== 0) {
            this.callType.stype = 'Add';
            this.selectedlots = 0;
            // var result = $filter('filter')(this.batchlist, { batchid: -1 })[0];
            const result = this.batchlist.filter(x => x.batchid === -1)[0];
            this.callType.supplement = result;
            this.jobid = this.jobid;
            this.selectedChapter = [];
            this.model.batchname = '';
            // this.model.supplementtypeid = 0;
            const projectname = this.projectdefinitions.filter(d => d.projectid === + this.projectid);
            const porintsup = this.printsupplements.filter(p => p.supplementacronym === projectname[0].project_subtitle);
            if (porintsup.length) {
              this.model.supplementtypeid = porintsup[0].supplementtypeid;
              this.supplementnumber = porintsup[0].supplementnumber;
              this.year = porintsup[0].year;
              this.printsupplementid = porintsup[0].printsupplementid;
              this.supplementnumber = porintsup[0].supplementnumber;
              this.publicationid = porintsup[0].publicationid;
            } else {
              this.toastr.error('No print supplement master available. Please add and try again');
              return;
              this.model.supplementtypeid = 0;
              this.supplementnumber = '';
              this.year = '';
              this.printsupplementid = 0;
              this.supplementnumber = '';
              this.publicationid = '';
            }
            this.model.mergedproof = 0;
            this.supplementModelRef = this.modalService.show(template, this.config);
            const aa = document.getElementsByClassName('modal-content');
            aa[0].classList.remove('modal-content');
            // this.LoadBatch();
            const timer = setInterval(() => {
              clearTimeout(timer);
              this.changeJob1(this.jobid);
            }, 1500);
          } else {
            this.toastr.error('Author has not done Final Submission, cannot create supplement now');
          }
        }, error => { this.toastr.error('Error while getting data'); });
        //}
      }, error => {
        this.toastr.error('Error in getting ProjectMaster records');
      });
    } else {
      this.toastr.error('Already Supplement created for this job');
    }
  }

  getcheckedsupplement(chapter, event) {
    /// this.chaplist[index].istabcard = chapter.istabcard === true ? 1 : 0;
    if (event.target.checked) {
      this.selectedChapter.push(chapter);
    } else if (chapter.selected) {
      this.selectedChapter.push(chapter);
    } else {
      const index = this.selectedChapter.findIndex(record => record.lotid === chapter.lotid);
      this.selectedChapter.splice(index, 1);
    }
    this.selectedlots = this.selectedChapter.length;
  }

  PostSupplement(supplement) {
    this.SpinnerService.show();
    if ((this.model.batchname === undefined) || (this.model.batchname.trim() === '')) {
      this.SpinnerService.hide();
      this.toastr.error('Mandatory fields should not be empty');
      return;
    }

    if (this.selectedChapter.length === 0) {
      this.SpinnerService.hide();
      this.toastr.warning('Please choose atleast one file for Update Process');
      return;
    }

    const selcahp = this.chaplist.filter(c => c.selected === true);
    const isprocessed = this.chaplist.filter(c => c.isprocessed === true);
    if (isprocessed.length === this.chaplist.length) {
      this.SpinnerService.hide();
      this.toastr.error('All lots should not be Pick-Up Chapters');
      return;
    }

    // console.log(selcahp);
    const obj = {
      batchid: +this.model.batchid ? +this.model.batchid : 0,
      jobid: +this.jobid,
      batchname: this.model.batchname,
      supplementtypeid: +this.model.supplementtypeid,
      batchstatus: 'R',
      volume: '1',
      issue: '1',
      metadata: this.model.metadata,
      active: 1,
      createdby: this.userid,
      updatedby: this.userid,
      issupplement: 1,
      printsupplementid: this.printsupplementid,
      publicationid: this.publicationid,
      supplementnumber: this.supplementnumber,
      mergedproof: this.model.mergedproof ? 1 : 0,
    };
    this.supplementService.PostBatch(obj).subscribe(res => {
      console.log('batchlist=', JSON.parse(res.body));
      const batchid = JSON.parse(res.body);
      if (batchid !== 0) {
        console.log('selectedChapter=', this.selectedChapter);
        this.selectedChapter.map(x => {
          x.istabcard = x.istabcard ? 1 : 0,
            x.batchid = batchid,
            x.userid = this.userid,
            x.createdby = this.userid,
            x.jobid = + this.jobid;
        });
        this.supplementService.PostBatchDetails(this.selectedChapter).subscribe(res2 => {
          this.supplementService.MovetoPagination(this.selectedChapter).subscribe(res3 => {
            this.LoadBatch();
            const timer = setInterval(() => {
              clearTimeout(timer);
              this.changeJob(this.jobid);
            }, 1500);
          }, error => { this.toastr.error('Error while getting data'); });
          // const lotdetails = res2.data;
          this.SpinnerService.hide();
          // triggerapp(lotdetails);
          this.toastr.success('Successfully Added the Supplement');
          this.supplementModelRef.hide();
        }, error => { this.toastr.error('Error while getting data'); });

      } else {
        this.SpinnerService.hide();
        this.toastr.warning('Suplement Already Exist');
        this.supplementModelRef.hide();
      }
    }, error => { this.toastr.error('Error while getting data'); });
    // console.log(obj);
    if (this.callType.stype === 'Add') {
      //  this.SpinnerService.show();
      if (this.selectedChapter.length === 0) {
        this.SpinnerService.hide();
        this.toastr.warning('Please choose atleast one file for Update Process');
        return;
      }
      // var postMenuData = SupplementService.postsupplement(obj, selcahp);
      // postMenuData.then(function (d) {

      // this.projectdefinitionservice.postsupplement(obj, selcahp).subscribe(d => {
      //   this.msg1 = d.data;
      //   if (this.msg1.Message === 'Warning') {
      //     this.SpinnerService.hide();
      //     this.toastr.warning('Suplement Already Exist');
      //     this.supplementModelRef.hide();

      //   } else {
      //     const lotdetails = d.data;
      //     this.SpinnerService.hide();
      //     // triggerapp(lotdetails);
      //     this.toastr.success('Successfully Added the Supplement');
      //     this.supplementModelRef.hide();
      //   }
      // }, error => { this.toastr.error('Error while getting data'); });
    }
  }
  // method to change the active status of the project
  ChangeActive(e) {
    if (e.currentTarget.checked) {
      this.SupplementForm.controls['active'].setValue(1);
    } else {
      this.SupplementForm.controls['active'].setValue(0);
    }
  }

  Editsupp() {
    this.SpinnerService.show();

    // var isprocessed = $filter('filter')(this.detaildate, { editisprocessed: true });
    const isprocessed1 = this.detaildate.filter(d => d.editisprocessed === true);

    if (this.statustext === 'Job In-Progress cannot modify the Supplement.') {
      this.SpinnerService.hide();
      this.toastr.warning('Job In-Progress cannot modify the Supplement');
      return;
    }
    if (this.selectedChapter.length === 0 && isprocessed1.length === 0) {
      this.SpinnerService.hide();
      this.toastr.warning('Please choose atleast one file for Update Process');
      return;
    }

    // var isprocessed = $filter('filter')(this.detaildate, { isprocessed: true });
    const isprocessed = this.detaildate.filter(d => d.isprocessed === true);
    if (isprocessed.length === this.detaildate.length) {
      this.toastr.error('All lots should not be Pick-Up Chapters');
      this.SpinnerService.hide();
      return;
    }

    // var editisprocessed = $filter('filter')(this.detaildate, { editisprocessed: true });
    const editisprocessed = this.detaildate.filter(d => d.editisprocessed === true);
    if (editisprocessed.length === this.detaildate.length) {
      this.toastr.warning('All lots should not be Pick-Up Chapters');
      this.SpinnerService.hide();
      return;
    }

    this.detaildate.forEach(ischeck => {
      ischeck.istabcard = ischeck.istabcard ? 1 : 0;
      ischeck.ischeck = ischeck.ischeck ? 1 : 0;
      ischeck.ishide = ischeck.ishide ? 1 : 0;
      ischeck.userid = this.userid;
      ischeck.createdby = this.userid;
      if (ischeck.editisprocessed === true) {
        ischeck.ischeck = 1;
        ischeck.ishide = 0;
      }
    });

    this.supplementService.Updatesupp(this.detaildate).subscribe(res => {
      // Need to ask
      // if (isprocessed.length != 0) {
      //     //triggerappfirsttran(JSON.parse(d)[0]);
      //     var turl = triggerappurl.replace("$$tranid$$", d.data[0].Transid);
      //     turl = turl.replace("$$userid$$", d.data[0].userid);
      //     turl = turl.replace("&amp;", "&");
      //     $http.post(turl);
      // }
      const supplement = this.detaildate.filter(x => x.ishide === 0 && x.ischeck === 1);
      this.supplementService.MovetoPagination(supplement).subscribe(res3 => {
        this.LoadBatch();
        const timer = setInterval(() => {
          clearTimeout(timer);
          this.changeJob(this.jobid);
        }, 1500);
      }, error => { this.toastr.error('Error while getting data'); });

      this.LoadBatch();
      const timer = setInterval(() => {
        clearTimeout(timer);
        this.changeJob(this.jobid);
      }, 1500);
      this.supplementeditModelRef.hide();
      this.SpinnerService.hide();
      this.toastr.success('Successfully Updated the Supplement');
    }, error => {
      this.SpinnerService.hide();
      this.toastr.error('Error in updateing supplement');
    });
  }

  GetAllSupplementType() {
    this.supplementTypes = [];
    this.supplementService.GetAllSupplementType().subscribe(res => {
      if (res.body[0] != null && res.body[0] !== undefined) {
        console.log('GetAllSupplementType=', JSON.parse(res.body[0]));
        this.supplementTypes = JSON.parse(res.body[0]);
        this.supplementTypes = this.supplementTypes.filter(y => y.active === 1);
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  ChangeProductionWorkFlow(ind, type, data) {
    if (type === 'Add') {
      this.selectedChapter[ind].productionworkflowid = +data;
    }
    if (type === 'Edit') {
      this.detaildate[ind].productionworkflowid = +data;
    }
  }

  getAllPrintSupplement() {
    this.printsupplements = [];
    this.printsupplementsactive = [];
    this.printsupplementservice.Get().subscribe(res => {
      this.printsupplements = JSON.parse(res[0]);
      console.log('this.printsupplements=', this.printsupplements);
      this.printsupplements = this.printsupplements.filter(p => p.active === 1);
      this.printsupplements = this.printsupplements.sort
        ((a, b) => new Date(b.scheduledate).valueOf() - new Date(a.scheduledate).valueOf());
      // this.model.supplementtypeid = this.printsupplements[0].supplementtypeid;

    }, error => { this.toastr.error('Error while getting data'); });
  }

}
