import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { Validators, FormGroup, FormBuilder, FormArray } from '@angular/forms';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
import { DialogService } from 'ng2-bootstrap-modal';
import { Router, NavigationExtras } from '@angular/router';
import { Jobmaster, LotMaster } from './jobmaster';
import { ToastrService } from 'ngx-toastr';
import { JobmasterService } from '../jobmaster/jobmaster.service';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { ProjectConfigurationService } from 'src/app/projectconfiguration/projectconfiguration/projectconfiguration.service';
import { ProjectdefinitionmasterService } from 'src/app/projectconfiguration/projectdefinitionmaster/projectdefinitionmaster.service';
import { Projectdefinitionmaster } from 'src/app/projectconfiguration/projectdefinitionmaster/projectdefinitionmaster';
import { ProjectDefinition } from 'src/app/projectconfiguration/projectconfiguration/projectdefinition';
import { JobdefinitionService } from '../jobdefinition/jobdefinition.service';
import { Options } from 'ng5-slider';
import { DatePipe } from '@angular/common';
import { saveAs } from 'file-saver';
import { NgxSpinnerService } from 'ngx-spinner';
import { environment } from 'src/environments/environment';

@Component({
    selector: 'app-jobmaster',
    templateUrl: './jobmaster.component.html',
    styleUrls: ['./jobmaster.component.css']
})
export class JobmasterComponent implements OnInit {
    @ViewChild('ErrorPopUpTemplate', {static : true}) errorPopUpTemplate :TemplateRef<any>;
    jobForm: FormGroup;
    joblotForm: FormGroup;
    searchText = '';
    confmsg: string;
    submitted = false;
    operation: string;
    key = 'jobname';
    reverse = false;
    readOnly = false; add = false; edit = false; delete = false;
    showall = true;
    p = 1;
    itemsPerPage = 10;
    actionRights: any;
    jobs: any = [];
    jobsall: any = [];
    showallstatus = false;
    jobModalRef: BsModalRef;
    lotModalRef: BsModalRef;
    configlot: ModalOptions = {
        backdrop: 'static',
        keyboard: false,
        animated: true,
        class: 'modal-dialog-centered modal-lg-full',
        ignoreBackdropClick: true
    };
    config: ModalOptions = {
        backdrop: 'static',
        keyboard: false,
        animated: true,
        class: 'modal-dialog-centered',
        ignoreBackdropClick: true
    };
    projects: any = [];
    producttypes: any = [];
    getjobno: any = [];
    userid: any;
    postresult: boolean;
    Errormsg:string;

    jobmasters: Jobmaster[] = [];
    jobmasteractive: Jobmaster[] = [];
    jobmaster: Jobmaster;
    projectdefinitions: ProjectDefinition[] = [];
    projectdefinitionid: number;
    projectid: number;
    selectedjobitem = {} as LotMaster;
    TablePagination: any;
    chaptertypelist = [];
    Selectedchaptertype: any;
    mappedchapter = [];
    Batchuploadlist = [];
    //ploadlist = [];
    uploadlist: any;
    errorPopUpModalRef: BsModalRef;

    value = 2;
    options: Options = {
        floor: 0,
        ceil: 10
    };

    textBoxTocuhed: boolean;
    _ddlProjecttypeSettings: {};
    jobProductTypeList: any[];
    _userselectedItems: any = [];
    _producttypeselected: any = [];
    job = {} as Jobmaster;
    projectsUnique = [];
    statecode =[];
    frequency =[];
    statecodeorg =[];
    frequencyorg =[];
    statecodeid:number;
    frequencyid:number;
    clickCount: number;
    exceltemplate : any = false;
    isarchive=1;
    projectid_not_unique:number=environment.projectid_notunique;
    constructor(
        private toastr: ToastrService,
        private formBuilder: FormBuilder,
        private dialogService: DialogService,
        private router: Router,
        private jobmasterservice: JobmasterService,
        private modalService: BsModalService,
        private projectConfigurationService: ProjectConfigurationService,
        private jobdefinitionservice: JobdefinitionService,
        public datepipe: DatePipe,
        private SpinnerService: NgxSpinnerService,
    ) {
        if (this.router.getCurrentNavigation().extras.state !== undefined) {
            localStorage.setItem('Jobmaster_menuid', this.router.getCurrentNavigation().extras.state.menuid);
            localStorage.setItem('Jobmaster_userRights', this.router.getCurrentNavigation().extras.state.action);
            this.actionRights = [];
            this.actionRights = this.router.getCurrentNavigation().extras.state.action;
        } else {
            this.actionRights = [];
            this.actionRights = localStorage.getItem('Jobmaster_userRights');
        }
    }

    ngOnInit() {
        this.jobForm = this.formBuilder.group({
            jobid: [''],
            projectid: ['', [Validators.required]],
            projectdefinitionid: ['', [Validators.required]],
            isdaterequired: [false],
            selectedDaterange: [],
            jobno: [''],
            title: [''],
            isbn: [],
            totallots: [''],
            startdate: [''],
            enddate: [''],
            jobstatus: [''],
            frequency:[],
            statecode:[],
        });
       
        this.joblotForm = this.formBuilder.group({
            lotid: [],
            jobid: [],
            title: [],
            sequence: [],
            instructions: [],
            isbatch: [false],
            basedonfile: [false],
            autoinc: [0],
            fileList: this.formBuilder.array([]),
        });

        this.userid = +localStorage.getItem('userid');
        this.getUserRights();

        this.getAll();
        this.getProjects();
        this.getstatefrequency();
        this.loadProductType();

    }

    initCaseRows() {
        return this.formBuilder.group({
            instruction: [''],
            log: [''],
            title: [''],
            Fileslist: [],
            chaptype: []
        });
    }

    get g() { return this.jobForm.controls; }
    get fileList(): FormArray {
        return this.joblotForm.get('fileList') as FormArray
    }

    addfile() {
        this.fileList.push(this.initCaseRows());
    }


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

    getAll() {
        this.jobs = [];
        const user = new Object({
            userid: this.userid,
            isarchive: this.isarchive 
        });
        this.jobdefinitionservice.GetAllByUserId(user).subscribe(res => {
            if (res.body[0] != null && res.body[0] !== undefined) {
                this.jobs = JSON.parse(res.body[0]);
                this.jobsall = JSON.parse(res.body[0]);
                if (this.showallstatus === true) {
                    this.jobs = this.jobs.filter(y => y.active === 1);
                }
            }
        }, error => { this.toastr.error('Error while getting data'); });
    }

    getProjects() {
        this.projects = [];
        const user = new Object({
            userid: this.userid
        });
        this.projectConfigurationService.getByUserId(user).subscribe(res => {
            if (res.body[0] != null && res.body[0] !== undefined) {
                this.projects = JSON.parse(res.body[0]);
                this.projectsUnique = this.projects.filter(
                    (project, i, arr) => arr.findIndex(p => p.projectid === project.projectid) === i
                );
            }
        }, error => { this.toastr.error('Error while getting data'); });
    }
    getstatefrequency() {
      
        this.jobmasterservice.GetActiveState().subscribe(res => {
            if (res[0] !== undefined && res[0] !== null && JSON.parse(res[0]).length > 0) {
                this.statecodeorg =JSON.parse(res[0]);      
            }                 
        }, error => { this.toastr.error('Error while getting data'); });

        this.jobmasterservice.GetActiveFrequency().subscribe(res => {
            if (res[0] !== undefined && res[0] !== null && JSON.parse(res[0]).length > 0) {
                this.frequencyorg =JSON.parse(res[0]);
            }        
        }, error => { this.toastr.error('Error while getting data'); });
    }
    
    getactiveinactive(showallp) {

    }
    onchangeproject() {
        this.projectid = +this.jobForm.controls['projectid'].value;
        this.projectdefinitions = this.projects.filter(p => p.projectid === this.projectid);
        this.show_exceltemplatebtn();
    }

    onChangeProjectDefinition() {
        this.projectdefinitionid = +this.jobForm.controls['projectdefinitionid'].value;
        if(this.projectid_not_unique == this.projectdefinitionid){
        this.jobForm.addControl('nooflots', this.formBuilder.control('', [Validators.required, Validators.min(1)]));
        if (this.jobForm.get('jobinputfile')) {
        this.jobForm.removeControl('jobinputfile');   
        }
        }else{
            this.jobForm.addControl('jobinputfile', this.formBuilder.control('', [Validators.required]));  
            if (this.jobForm.get('nooflots')) {
            this.jobForm.removeControl('nooflots'); 
            }
        }
        this.statecode=this.statecodeorg;
        this.show_exceltemplatebtn();
    }

    onChangestatecode(){
       this.statecodeid= +this.jobForm.controls['statecode'].value; 
       this.frequency = this.frequencyorg;
    }
    onChangefrequency(){ 
        this.frequencyid= +this.jobForm.controls['frequency'].value;
        const projectdefiniondata = this.projectdefinitions.filter(pd => pd.projectdefinitionid === this.projectdefinitionid);
        const length = this.jobs.filter(j => j.projectid === this.projectid && j.projectdefinitionid === this.projectdefinitionid).length + 1;
        const State_Code = this.statecode.filter(pd => pd.statecodeid === this.statecodeid);
        const Freq_Code = this.frequency.filter(pd => pd.frequencyid === this.frequencyid);
        const s1 = State_Code[0].stateabbreviation;
        const s2 = Freq_Code[0].frequencyabbreviation;
        const s3 = length.toString().padStart(projectdefiniondata[0].jobno_length, '0');
        const s4 = s1+"-"+s2+"-"+s3;
        var date=new Date();
        let current_date =this.datepipe.transform(date, 'dd-MMM-yyyy');
        const s5=s4+"_"+current_date;
        this.jobForm.controls['jobno'].setValue(s4);
        this.jobForm.controls['title'].setValue(s5);
    }

    // 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;
                    }
                }
            });
        }
    }

    openjobModal(template: TemplateRef<any>, type, job?: Jobmaster) {
        this.operation = type;
        if (type === 'add') {
            this.projectdefinitionid=0;
            this.jobForm.reset();
            this.jobForm.controls['jobid'].setValue(0);
            this.jobForm.controls['jobno'].setValue('');
            this.jobForm.controls['projectid'].setValue(0);
            this.jobForm.controls['projectdefinitionid'].setValue(0);
            this.jobForm.controls['statecode'].setValue(0);
            this.jobForm.controls['frequency'].setValue(0);
            this.jobForm.controls['title'].setValue('');
            this.jobForm.controls['isdaterequired'].setValue(false);
            this.jobForm.controls['selectedDaterange'].setValue([new Date(), new Date()]);
        }
        this.jobModalRef = this.modalService.show(template, this.config);
        const aa = document.getElementsByClassName('modal-content');
        aa[0].classList.remove('modal-content');
    }

    clearForm() {
        this.jobModalRef.hide();
    }

    guid() {
        return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' + this.s4() + this.s4() + this.s4();
    }

    s4() {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    }

    Post(jobmaster: Jobmaster) {
        debugger;
        this.SpinnerService.show();
        this.submitted = true;
        jobmaster.jobstatus = 'R';
        jobmaster.isreadyforpurge = 0;
        jobmaster.totallots = 1;
        jobmaster.total_rec_count = 1;
        jobmaster.jobkey = this.guid();
        jobmaster.startdate = this.jobForm.value.selectedDaterange[0];
        jobmaster.enddate = this.jobForm.value.selectedDaterange[1];
        jobmaster.projectdefinitionid = +jobmaster.projectdefinitionid;
        jobmaster.projectid = +jobmaster.projectid;
        if (jobmaster.projectid === 0) {
            this.toastr.error('Project should not be empty');
            return;
        }
        if (jobmaster.projectdefinitionid === 0) {
            this.toastr.error('Project definition should not be empty');
            return;
        }
        let msg = null;
        if (this.operation === 'add') {
            jobmaster.createdby = this.userid;
            msg = 'Record Added Successfully';
           //Revathi.t
           const formData = new FormData();
           if(this.projectid_not_unique != this.projectdefinitionid){
            jobmaster.oluaworkflow=false;
           
           if (this.uploadlist !='' && this.uploadlist !=undefined) {
            for (let i = 0; i < this.uploadlist.length; i++) {
                const val = this.uploadlist[i];
                if (val !== undefined) {
                      formData.append('file', val,
                      val.name);
                    }
                }
           } else{
            this.toastr.error('Kindly upload file');
            return;
           }                   
        }else{
            jobmaster.oluaworkflow=true;
            jobmaster.totallots = this.jobForm.value.nooflots;
        }
           const projectdefiniondata = this.projectdefinitions.filter(pd => pd.projectdefinitionid === this.projectdefinitionid);
           const length = this.jobs.filter(j => j.projectid === this.projectid && j.projectdefinitionid === this.projectdefinitionid).length + 1;
           const s3 = length.toString().padStart(projectdefiniondata[0].jobno_length, '0');
           formData.append('jobstatus', 'R');
           formData.append('isreadyforpurge', '0');
           formData.append('totallots',  jobmaster.totallots.toString());
           formData.append('total_rec_count', '1');
           formData.append('jobkey', this.guid());
           formData.append('startdate', this.jobForm.value.selectedDaterange[0]);
           formData.append('enddate', this.jobForm.value.selectedDaterange[1]);
           formData.append('projectdefinitionid',jobmaster.projectdefinitionid.toString());
           formData.append('projectid', jobmaster.projectid.toString());
           formData.append('jobno',s3.toString());
           formData.append('createdby',this.userid);
           formData.append('oluaworkflow',jobmaster.oluaworkflow.toString());
           this.jobmasterservice.UploadJobInfoExcelFile(formData).subscribe(res => {
        this.SpinnerService.hide();
            //this.jobmasterservice.Post(jobmaster).subscribe(res => {
                if (res.status === 200) {
                    if (res !== undefined) {
                        if (res.body !== 0) {
                            this.jobModalRef.hide();
                            const user = new Object({
                                userid: this.userid
                            });
                            /* this.jobdefinitionservice.GetAllByUserId(user).subscribe(jobres => {
                                if (jobres.body !== undefined && jobres.body !== null && jobres.body[0] !== undefined &&
                                    jobres.body[0] !== null && (JSON.parse(jobres.body[0]).length > 0)) {
                                    let projectflow = JSON.parse(jobres.body[0]);
                                    projectflow = projectflow.filter(p => p.jobid === res.body);
                                    this.moveToJobDefinition(projectflow[0]);
                                } 
                            }, err => { this.toastr.error(err); });*/
                            this.toastr.success(res.body.length + ' New Job(s) added successfully with uploaded Excel info.');
                            var date=new Date();
                            this.searchText=this.datepipe.transform(date, 'ddMMyy');
                            this.getAll();
                            //window.location.reload();
                            // this.clearForm();
                        } else { this.toastr.warning('Record already exists.'); }
                    }
                }
            },
                error => {
                    this.SpinnerService.hide();
                    this.jobModalRef.hide();
                    //this.toastr.error('Error while doing the operation ' + error.error.message);
                    this.Errormsg=error.error.message;
                    if(this.Errormsg == undefined)this.Errormsg=error.message;
                    this.errorPopUpModalRef = this.modalService.show(this.errorPopUpTemplate, this.config);
                    const aa = document.getElementsByClassName('modal-content');
                    aa[0].classList.remove('modal-content');
                    this.postresult = false;
                });
        } else if (this.operation = 'update') {

            if ((jobmaster.projectdefinitionid === 0) || (jobmaster.projectdefinitionid == null)) {
                this.toastr.error('Product Type should not be empty');
                return;
            }

            jobmaster.updatedby = this.userid;
            msg = 'Record updated successfully';
            this.jobmasterservice.Put(jobmaster).subscribe(res => {
                this.SpinnerService.hide();
                if (res.status === 200) {
                    if (res !== undefined) {
                        if (res.body !== 0) {
                            this.jobModalRef.hide();
                            this.getAll();
                            this.toastr.success('Data updated successfully');
                            this.clearForm();
                        } else { this.toastr.warning('Record already exists.'); }
                    }
                }
            },
                error => {
                    this.SpinnerService.hide();
                    this.jobModalRef.hide();
                    //this.toastr.error('Error while doing the operation '+error.error.message);
                    this.Errormsg=error.error.message;
                    if(this.Errormsg == undefined)this.Errormsg=error.message;
                    this.errorPopUpModalRef = this.modalService.show(this.errorPopUpTemplate, this.config);
                    const aa = document.getElementsByClassName('modal-content');
                    aa[0].classList.remove('modal-content');
                    this.postresult = false;
                });
        }

    }



    moveToJobDefinition(item) {
        console.log(item);
        const queryParams = {};
        const navigationExtras: NavigationExtras = {
            queryParams, state: {
                projectid: item.projectid,
                projectdefinitionid: item.projectdefinitionid,
                jobno: item.jobno,
                jobid: item.jobid,
                title: item.title,
                startdate: item.startdate,
                enddate: item.enddate,
                projectname: item.projectname,
                project_subtitle: item.project_subtitle,
                totallots: item.totallots,
                isdaterequired: item.isdaterequired,
                // jobmetadata: item.jobmetadata
                validjobmeta: item.validjobmeta
            }
        };
        this.router.navigate(['/jobconfiguration/jobdefinition'], navigationExtras);
    }


    onValueChange(value: Date): void {
        this.jobForm.value.startdate = value[0];
        this.jobForm.value.enddate = value[1];
    }
    openlotModal(template: TemplateRef<any>, item) {
        this.clickCount++;
        setTimeout(() => {
            if (this.clickCount === 1) {
                const jobObject = new Object({
                    jobid: item.jobid
                });
                this.jobdefinitionservice.GetJobWorkFlowDefCount(jobObject).subscribe(res => {
                    if (res.body[0] != null) {
                        this.LoadChaptertypes();
                        this.TablePagination = {
                            itemsPerPage: 10,
                            maxPages: 5,
                            fillLastPage: false
                        };
                        this.job = item;
                        this.lotModalRef = this.modalService.show(template, this.configlot);
                        const aa = document.getElementsByClassName('modal-content');
                        console.log(aa);
                        aa[0].classList.remove('modal-content');
                    } else {
                        this.moveToJobDefinition(item);
                        this.toastr.warning('Please complete job configuration, then proceed');
        
                    }
                });
            }else if(this.clickCount==2){
                const jobObject = new Object({
                    jobid: item.jobid
                });
                this.jobdefinitionservice.GetJobWorkFlowDefCount(jobObject).subscribe(res => {
                    if (res.body[0] != null) {
                        this.LoadChaptertypes();
                        this.TablePagination = {
                            itemsPerPage: 10,
                            maxPages: 5,
                            fillLastPage: false
                        };
                        this.job = item;
                        this.lotModalRef = this.modalService.show(template, this.configlot);
                        const aa = document.getElementsByClassName('modal-content');
                        console.log(aa);
                        aa[0].classList.remove('modal-content');
                    } else {
                        this.moveToJobDefinition(item);
                        this.toastr.warning('Please complete job configuration, then proceed');
        
                    }
                });
            } 
            this.clickCount = 0;
        }, 250)
     }

    LoadChaptertypes() {
        this.jobmasterservice.getChapterType().subscribe(res => {
            if (res.status === 200) {
                if (res !== undefined) {
                    if (res.body !== 0) {
                        this.chaptertypelist = JSON.parse(res.body[0]);
                        if (res.body.length > 0) {
                            this.Selectedchaptertype = JSON.parse(res.body[0]);
                        }
                    }
                }
            }
        },
            error => {
                this.toastr.error('Error while getting chapter list');
                this.chaptertypelist = [];
            });
    }
    loadProductType() {
        this._ddlProjecttypeSettings = {
            singleSelection: false,
            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) {
                    let list: any[];
                    list = JSON.parse(res[0]);
                    this.jobProductTypeList = list;
                }
            }
        }
        );
    }


    onItemSelect(item: any) {
        this.textBoxTocuhed = true;
        console.log(item);

        this._producttypeselected.push(item.project_subtitle);

        this.jobs = [];
        this.jobs = this.jobsall.filter(f => this._producttypeselected.includes(f.project_subtitle));
        console.log(this.jobs);
    }

    onItemDeSelect(item: any) {
        this.textBoxTocuhed = true;
        let res;
        res = this._producttypeselected.findIndex(d => d === item.project_subtitle);
        let splic = [];
        splic = this._producttypeselected.splice(res, 1);
        console.log(this._producttypeselected);

        if (this._producttypeselected.length > 0) {
            this.jobs = [];
            this.jobs = this.jobsall.filter(f => this._producttypeselected.includes(f.project_subtitle));
        } else if (this._producttypeselected.length === 0) {
            this.jobs = [];
            this.jobs = this.jobsall;
        }

    }

    onSelectAll(item: any) {
        this._producttypeselected = [];

        item.forEach(element => {
            this._producttypeselected.push(element.project_subtitle);
        });
        this.jobs = [];
        this.jobs = this.jobsall.filter(f => this._producttypeselected.includes(f.project_subtitle));
    }

    onDeSelectAll(item: any) {
        this.jobs = [];
        this.jobs = this.jobsall;
        this._producttypeselected = [];
    }

    fileuploadchange(ix, fileInput: any) {
        debugger;
        this.uploadlist=fileInput.target.files;
        /* for (let i = 0; i < fileInput.target.files.length; i++) {
          const v = fileInput.target.files[i];
          this.uploadlist[i]=fileInput.target.files[i];
        } */
    }
    test(){ 
        console.log(this.jobForm);
    }
    closeerrorpopup(){
        this.errorPopUpModalRef.hide();
        this.jobModalRef.hide();
    }
    show_exceltemplatebtn(){
        if(+this.projectid != 0 && +this.projectdefinitionid != 0 && this.projectdefinitionid != undefined && this.projectid != undefined){
            this.exceltemplate = true;
        }else{
            this.exceltemplate = false;
        }
    }
    downloadexcel_template(){
        if(+this.projectid != 0 && +this.projectdefinitionid != 0 && this.projectdefinitionid != undefined && this.projectid != undefined){
            this.jobmasterservice.GetExcelTemplate(this.projectid,this.projectdefinitionid).subscribe(res =>{
                var content = res.file_;
                let objectURL = 'data:application/octet-stream;base64,' + res.file_;
                saveAs(objectURL, 'ExcelTemplate.xlsx');
                self.close();
                //this.jobModalRef.hide();
                this.exceltemplate = false;      
            }, error => { this.toastr.error('Error while getting data'); });

        }else{
            this.toastr.error('Please select Project Code/Project Type');
        }  
    }
    jobdeteleModal(item){
        this.dialogService.addDialog(CommondialogComponent,
            {
              title: 'Please Confirm',
              message: 'Do you want to delete the job?',
              hclass: 'modelsuccess',
              oktext: 'Yes',
              canceltext: 'No',
              okshow: true,
              cancelshow: true
            }).subscribe((isConfirmed) => {           
              if (isConfirmed) {       
                     this.jobdelete(item.jobid);
              }else{
                return;
              }           
            });
    }
   
    jobdelete(jobid){
        this.jobmasterservice.DeleteJob(jobid).subscribe(res=>{
            if(res.message === 'success'){
                this.toastr.success('Job Deleted Successfully.');
                this.getAll();
            }
        },error => {
            this.toastr.error('Error while deleting the job');
        });
    }
    selectarchivejob(event){
        if(event.target.checked == true){
            this.isarchive = 0;
        }else{
            this.isarchive = 1;
        }
        this.getAll();
    }
}
