import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HyperService } from '../../core/services/http.service';
import { Router, NavigationEnd, RoutesRecognized } from "@angular/router";
import { LocalStorage } from '../../core/services/local_storage.service';
import * as moment from 'moment';
import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';
declare var $: any;
import { CONFIG } from '../../config';
import { filter, pairwise } from 'rxjs/operators';
@Component({
    selector: 'app-setsales-report',
    templateUrl: './setsales-report.component.html',
    styleUrls: ['./setsales-report.component.scss']
})
export class SetsalesReportComponent implements OnInit {
    @ViewChild('csv_file') fileInput: ElementRef;
    data_error:string='';
    upload_selected_title: any;
    error_msg: boolean=false;
    file_name: any;
    sub: any;
    type: any;
    user_id: any;
    userData: any = {};
    user_info: any;
    date_now: any;
    loader: boolean;
    report_data: any;
    sales_date: any;
    page_load: boolean;
    excel_load: boolean;
    export_url: any;
    location_selected: any;
    selected_title: any = '';
    mymodel: string = "";
    active_product: number;
    product_info: any = [];
    report_user: number;
    _url: any;
    selected_index: number;
    total_item: number;
    page_per_size: number = 10;
    current_page: number;
    total_page: number;
    activeItem: number = -1;
    activePage: number = 1;
    page_count: number;
    leader_type = [{
        title: "All",
        id: "0",
        is_selected: 0,
        sort_by: 0
    },
    {
        title: "Dealer",
        id: "1",
        is_selected: 0,
        sort_by: 1
    },
    {
        title: "Location",
        id: "2",
        is_selected: 0,
        sort_by: 2
    },
        //   {
        //       title: "AM",
        //       id: "3",
        //       is_selected: 0,
        //       sort_by: 3
        //   },
        //   {
        //       title: "RM",
        //       id: "4",
        //       is_selected: 0,
        //       sort_by: 4
        //   },
        //   {
        //       title: "ZM",
        //       id: "5",
        //       is_selected: 0,
        //       sort_by: 5
        //   }
    ]
    sort_by: any;
    user_role: number;
    amuser_list: any = [];
    rmuser_list: any = [];
    zmuser_list: any = [];
    am_email: string = '';
    rm_email: string = '';
    zm_email: string = '';
    zm_zone: string;
    zm_zonename: string;
    zmmail: string = '';
    rmmail: string = '';
    ammail: string = '';
    cont: boolean;
    am_cont: boolean;
    previousUrl: string;
    rmInactive: boolean;
    amInactive: boolean;
    zmEmail: any;
    zmData: any;
    rmData: any;
    amData: any;
    showdata: any;
    disablebtn: boolean=true;
    single_data_error: string;
    showopacity: boolean=false;
    constructor(private route: ActivatedRoute, private server: HyperService, private router: Router, private sanitizer: DomSanitizer) { }

    ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
            this.type = params['type'];
            this.user_id = params['id'];
            this.userData.emailid = params['email'];
            this.rmmail = params['rmmail'];
            this.ammail = params['ammail'];
            this.zmmail = params['zmmail'];
        });
        this.router.events
            .pipe(filter((e: any) => e instanceof RoutesRecognized),
                pairwise()
            ).subscribe((e: any) => {
                console.log(e[0].urlAfterRedirects);
                this.previousUrl = e[0].urlAfterRedirects// previous url
                LocalStorage.setValue('previous_Url', this.previousUrl)
            });
        if (LocalStorage.getValue('previous_Url') != '/dashboard') {
            CONFIG.page_change = false;
            CONFIG.am_page_change = false;
        }
        this.current_page = 0;
        this.activePage = 0;
       
        
        if (this.type == 'mobile') {
            this.sales_date = moment().format("MMM YYYY") //current month and year
            let m = moment(this.sales_date, "MMM YYYY").format("MM");
            let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
            LocalStorage.setValue('token', this.user_id)
            // LocalStorage.setValue('zmmail', this.zmmail)
            // LocalStorage.setValue('rmmail', this.rmmail)
            // LocalStorage.setValue('ammail', this.ammail)
            this.getuserdetails() //Get Authentication token 
        }
        else {
            if (LocalStorage.getValue('user_data') != undefined) {
                this.userData = LocalStorage.getValue('user_data');
                this.user_role = LocalStorage.getValue('user_data').role;
                if (this.user_role != undefined && this.user_role < 4) {
                    this.zm_email = "all";
                    this.rmmail = "all";
                    this.ammail = "all";
                    this.zmmail = "all";
                    this.getZm();
                } else if (this.user_role != undefined && this.user_role < 6) {
                    this.rm_email = "all";
                    this.am_email = "all";
                    this.cont = (CONFIG.page_change) ? false : true;
                    this.getRm();
                } else if (this.user_role != undefined && this.user_role < 7) {
                    this.am_email = "all";
                    this.am_cont = (CONFIG.am_page_change) ? false : true;
                    this.getAm();
                } else {
                    this.sales_date = moment().format("MMM YYYY")
                    console.log("aloow")
                    this.getDealerDetails()
                   
                    // this.salesTarget(y, m)
                }
            }

        }
        this.date_now = moment().format("MMM YYYY");
        this.sales_date = moment().format("MMM YYYY");
        // console.log(this.userData)
        this.location_selected = this.leader_type.filter(question => question.is_selected == 1);
       
    }
    //pagination
    public getServerData(event) {
        this.active_product = null;
        // console.log(event)
        this.page_count = (event - 1);
        // console.log('page', this.page_count)
        // console.log(this.sales_date)
        this.sales_date = moment().format("MMM YYYY") //current month and year
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
            this.salesTarget(y, m, this.page_count, "zm")
        } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
            this.salesTarget(y, m, this.page_count, "rm")
        } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
            this.salesTarget(y, m, this.page_count, "am")
        }
        this.onPageChange(event);
    }
    public onPageChange(event) {
        this.activeItem = -1;
        this.activePage = event;
        // console.log('pagech', this.activePage)
    }
    //HO LOGGED
    getZm() {
        this.server.post("manager/zone", {})
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                    // console.log(data.result.data)
                    this.zmuser_list = data.result.data;
                    this.zmChange("all")
                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });
    }
    zmChange(event) {
        this.rm_email = "all";
        this.am_email = "all";
        if (event == "all") {
            this.rmInactive = true;
            this.amInactive = true;
            this.zm_email = "all";
            // LocalStorage.setValue("zmmail", this.zm_email)
        } else {
            this.rmInactive = false;
            this.amInactive = true;
            this.zm_email = event;
            // LocalStorage.setValue("zmmail", this.zm_email)
            // this.cont = (CONFIG.page_change) ? false : true;
            this.zm_zone = event.zone;
            this.zm_zonename = event.email;
            this.getRm();

        }
        if (this.zm_email == 'all') {
            this.zmEmail = 'all';
        } else {
            this.zmEmail = this.zm_zonename;
        }
        this.current_page = 0;
        this.activePage = 0;
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this.salesTarget(y, m, this.page_count, "zm")
    }
    // ZM LOGGED
    getRm() {
        this.amInactive = true;
        this.server.post("manager/region", {
            zone: (this.user_role > 3 && this.user_role != 5) ? this.userData.emailid : this.zm_zonename,
            zonename: (this.user_role > 3 && this.user_role == 5) ? this.userData.zone : this.zm_zone
        })
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                    CONFIG.page_change = true;
                    // console.log(":::::::::", this.cont)
                    this.rmuser_list = data.result.data;
                    if (this.user_role != undefined && this.user_role==4 || this.user_role==5) {
                        this.zmEmail = this.userData.emailid;
                        this.rmChange("all")
                      }
                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });
    }
    rmChange(event) {
        this.am_email = "all"
        if (event == "all") {
            this.amInactive = true;

        } else {
            this.amInactive = false;
            this.rm_email = event;
            // LocalStorage.setValue("rmmail", this.rm_email)
            // this.am_cont = (CONFIG.am_page_change) ? false : true;
            this.getAm();
        }
        this.current_page = 0;
        this.activePage = 0;
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this.salesTarget(y, m, this.activePage, "rm")
    }

    // RM LOGGED
    getAm() {
        this.server.post("manager/area", {
            region: ((this.user_role < 7 || this.user_role == 14) && this.user_role != 6) ? this.rm_email : this.userData.emailid
        })
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                    // console.log(data.result.data)
                    CONFIG.am_page_change = true;
                    this.amuser_list = data.result.data;
                    if (this.user_role != undefined && this.user_role==6) {
                        this.rm_email = this.userData.emailid;
                        this.amChange("all")
                      }
                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });
    }
    amChange(event) {
        this.am_email = event;
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this.current_page = 0;
        this.activePage = 0;
        this.salesTarget(y, m, this.activePage, "am")
    }
    getuserdetails() {
        this.loader = true
        this.updateMobileView();
    }
    updateMobileView() {
        this.server.get("user/profile").then((data) => {
            if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                this.userData = data.result.data;
                LocalStorage.setValue('user_data', this.userData)
                this.user_role = this.userData.role;
                if (this.user_role != undefined && this.user_role < 4) {
                    this.getZm();
                } else if (this.user_role != undefined && this.user_role < 6) {
                    this.cont = (CONFIG.page_change) ? false : true;
                    this.getRm();
                } else if (this.user_role != undefined && this.user_role < 7) {
                    this.am_cont = (CONFIG.am_page_change) ? false : true;
                    this.getAm();
                } else {
                    // console.log(this.userData)
                    this.getDealerDetails()
                    this.sales_date = moment().format("MMM YYYY") //current month and year
                    let m = moment(this.sales_date, "MMM YYYY").format("MM");
                    let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
                    this.current_page = 0;
                    this.activePage = 0;
                    if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
                        this.salesTarget(y, m, this.activePage, "zm")
                    } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
                        this.salesTarget(y, m, this.activePage, "rm")
                    } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
                        this.salesTarget(y, m, this.activePage, "am")
                    }

                }
            }
            else if (data.result.status == 401 && data.result.response == 'failed') {
                this.router.navigateByUrl('');
            }
            else {
                alert("Oops something happened!");
            }
        })
    }
    increasMonth() {
        let now = moment(this.sales_date, "MMM YYYY").format("YYYY-MM-DD");
        let tdyDate = moment(new Date()).format('YYYY-MM-DD');
        if (moment(now).isSame(tdyDate, 'month') == false && moment(now).isSameOrBefore(tdyDate, 'year') == true) {
            this.sales_date = moment(this.sales_date, "MMM YYYY").add(1, 'months').format("MMM YYYY"); //+ one month
            this.loader = true
            let m = moment(this.sales_date, "MMM YYYY").format("MM");
            let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
            this.current_page = 0;
            this.activePage = 0;
            if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
                this.salesTarget(y, m, this.activePage, "zm")
            } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
                this.salesTarget(y, m, this.activePage, "rm")
            } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
                this.salesTarget(y, m, this.activePage, "am")
            }
        }
    }

    decreasMonth() {
        this.loader = true
        this.sales_date = moment(this.sales_date, "MMM YYYY").add(-1, 'months').format("MMM YYYY"); //- one month
        setTimeout(() => {
            let m = moment(this.sales_date, "MMM YYYY").format("MM");
            let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
            this.current_page = 0;
            this.activePage = 0;
            if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
                this.salesTarget(y, m, this.activePage, "zm")
            } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
                this.salesTarget(y, m, this.activePage, "rm")
            } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
                this.salesTarget(y, m, this.activePage, "am")
            }
        }, 1200);
    }
    salesTarget(year, month, page, role) {
        console.log(year)
        console.log(month)
        // this.activePage=page;
        this.loader = true;
        console.log(this.selected_title,this.activePage,page)
        if (this.selected_title == '') {
            this.sort_by = 0
        }
        // this._url = "manager/newsalestarget/" + year + "/" + month +"?page=0&limit=10&filter=sort:" + this.sort_by + "";
        this._url = "manager/newsalestarget/" + year + "/" + month + "/" + role + "?page=" + page + "&limit=10&filter=sort:" + this.sort_by + "";
        this.server.post(this._url, {
            search: this.mymodel,
            zmemail: this.zmEmail,
            rmemail: this.rm_email,
            amemail: (this.user_role < 7) ? this.am_email : (this.user_role == 14) ? this.userData.dealer.am_email : this.userData.emailid,
            dealer:this.selected_dealer_code
        })
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed') {
                    setTimeout(() => {
                        this.loader = false;
                        this.user_info = data.result.data;
                        this.total_item = Number(data.result.total);
                        console.log('UserData', this.user_info)
                    }, 500);
                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });
    }


    radioSelect(val) {
        for (let i = 0; i < this.leader_type.length; i++) {
            if (val == i) {
                this.leader_type[i].is_selected = 1;
                this.selected_title = this.leader_type[i].title
                this.sort_by = this.leader_type[i].sort_by
                console.log(this.selected_title)
            } else {
                this.leader_type[i].is_selected = 0;
            }
        }
        this.isLocationSelected()
        this.active_product = null;
    }

    isLocationSelected() {
        this.location_selected = this.leader_type.filter(question => question.is_selected == 1);
        console.log(this.location_selected)
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this.current_page = 0;
        this.activePage = 0;
        if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
            this.salesTarget(y, m, this.activePage, "zm")
        } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
            this.salesTarget(y, m, this.activePage, "rm")
        } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
            this.salesTarget(y, m, this.activePage, "am")
        }
    }
    clickExcelDownload() {
        // console.log(this.zm_email, this.zm_zonename)
        if (this.zm_email == 'all') {
            this.zmData = 'all';
            this.rmData = '';
            this.amData = '';
            this.roleBasedExcel("zm")
        } else if (this.zm_email != undefined && this.zm_email != '' && this.zm_email != 'all' && this.rm_email == 'all') {
            this.zmData = this.zm_zonename == undefined ? '' : this.zm_zonename;
            this.rmData = '';
            this.amData = '';
            this.roleBasedExcel("zm")
        } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
            this.zmData = this.zm_zonename == undefined ? '' : this.zm_zonename;
            this.rmData = this.rm_email;
            this.amData = '';
            this.roleBasedExcel("rm")
        } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
            this.zmData = '';
            this.rmData = this.rm_email;
            this.amData = (this.user_role < 7) ? this.am_email : (this.user_role == 14) ? this.userData.dealer.am_email : this.userData.emailid;
            this.roleBasedExcel("am")
        }

    }
    roleBasedExcel(role) {
        this.page_load = true;
        this.excel_load = true;
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this._url = "managerexport/newsalestargetreportexport/" + y + "/" + m + "/" + role + "?page=0&limit=10&filter=sort:" + this.sort_by;
        this.server.post(this._url, {
            zmemail: this.zmData,
            rmemail: this.rmData,
            amemail: this.amData
        }).then((data) => {
            if (data.status == 200) {
                this.page_load = false;
                this.export_url = (data.result.data);
                setTimeout(() => this.export_url = "", 1000);
                this.excelExport();
            } else {
                alert("error");
            }
        });
    }
    excelExport() {
        return this.sanitizer.bypassSecurityTrustResourceUrl(this.export_url);
    }
    export_url_sample: string = '';
    clickSampleExcelDownload() {
        this.page_load = true;
        this.excel_load = true;
        // console.log(this._url)
        // let month = moment(this.sales_date, "MMM YYYY").format("MM");
        // let year = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this.server.post("managerexport/managertargetsample", {
            area: (this.user_role < 7) ? this.am_email : (this.user_role == 14) ? this.userData.dealer.am_email : this.userData.emailid
        }).then((data) => {
            if (data.status == 200) {
                this.page_load = false;
                this.export_url_sample = (data.result.data);
                setTimeout(() => this.export_url_sample = "", 1000);
                this.excelSampleExport();
            } else {
                alert("error");
            }
        });
    }
    dealer_list:any=[];
    selected_title_dealer:string='';
    selected_dealer_code:string=''
    getDealerDetails() {
        this.page_load = true;
        this.server.get("manager/dealer" ).then((data) => {
            if (data.status == 200) {
                this.dealer_list=data.result.data;
                    if(this.user_role != undefined && this.user_role == 14){
                        this.selected_title_dealer = ''
                        this.selected_dealer_code=''
                    }else if(this.user_role != undefined && this.user_role == 7){
                        if(this.dealer_list.length>0){
                        this.selected_title_dealer = this.dealer_list[0].dealer_name
                        this.selected_dealer_code= this.dealer_list[0].dealer_code
                        }
                    }
                // console.log(this.selected_dealer_code,"this.selected_dealer_code")
                this.page_load = false;
                let m = moment(this.sales_date, "MMM YYYY").format("MM");
                let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
                console.log(this.selected_dealer_code,"this.selected_dealer_code")
                if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
                    this.salesTarget(y, m, this.activePage, "zm")
                } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
                    this.salesTarget(y, m, this.activePage, "rm")
                } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
                    this.salesTarget(y, m, this.activePage, "am")
                }
            } else {
                alert("error");
            }
        });
    }
    radioSelectDealer(val) {
        for (let i = 0; i < this.dealer_list.length; i++) {
            if (val == i) {
                this.dealer_list[i].is_selected = 1;
                this.selected_title_dealer = this.dealer_list[i].dealer_name
                this.selected_dealer_code=this.dealer_list[i].dealer_code
                console.log(this.selected_title_dealer)
            } else {
                this.dealer_list[i].is_selected = 0;
                this.dealer_list[i].selected_title_dealer = 0;
            }
        }
        this.isLocationSelected()
        this.active_product = null;
    }
    excelSampleExport() {
        return this.sanitizer.bypassSecurityTrustResourceUrl(this.export_url_sample);

    }

    onSearchChange(searchValue: string) {
        this.mymodel = searchValue;
        // console.log(this._url)
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this.current_page = 0;
        this.activePage = 0;
        if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
            this.salesTarget(y, m, this.activePage, "zm")
        } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
            this.salesTarget(y, m, this.activePage, "rm")
        } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
            this.salesTarget(y, m, this.activePage, "am")
        }

    }

    showDetails(val, list) {
        console.log(val)
        console.log(list)
        this.selected_index = val;
        if (this.active_product == val) {
            this.active_product = null;
        } else {
            this.active_product = val;
            this.product_info = list.model;
          //  this.greaterThan(this.product_info);
        }
    }
    close(event){
        $('#myModal').modal('hide'); 
    }

    targetMinus(val, i, parent) {
        console.log(val)
        var modal = document.getElementById('myModal');
        var btn = document.getElementById("myBtn");
        btn.onclick = function() {
            modal.style.display = "block";
        }
        window.onclick = function(event) {
            if (event.target == modal) {
            modal.style.display = "none";
            }
        }
        let count:number=0;
        for(let i=0;i<this.product_info.length;i++){
            count=count+Number(this.product_info[i].target);
        }
       // this.data_error="Target Setting of less than" +" "+parent.segment_min_target+" "+ "Vehicles per month not allowed."; 
        this.single_data_error="Target Setting of less than" +" "+val.min_target+" "+ "Vehicles per month not allowed."; 
        for(let index =0;index<this.product_info.length;index++){
            if(index == i){
                if(Number(val.min_target)<Number(val.target)){
                    val.target--;
                    parent.salestarget=Number(parent.salestarget)-1;
                }
                // else if(Number(val.min_target)==0){
                //     this.product_info = Object.assign(this.product_info[index],{'showopacity': true});
                //     // this.showopacity = true;
                // }
                else{
                    this.error_msg = true;
                   // $('#myModal').modal('show');
                }
            }
        }
        
        // this.product_info.forEach(function (item, index) {
        // //    if (index == i) {
        // //         if (count>parent.segment_min_target && val.target > 0) {
        // //             item.target--;
        // //             parent.salestarget=count-1;
        // //         }else {
        // //             $('#myModal').modal('show');
        // //         }
        // //     }
        // if(index == i){
        //     if(val.min_target<=val.target){
        //         item.target--;
        //         parent.salestarget=count-1;
        //     }else{
        //         this.error_msg = true;
        //         $('#myModal').modal('show');
        //     }
        // }
        // });
    }
    targetPlus(val, i, parent) {
        //  this.disablebtn = false;
        this.product_info.forEach(function (item, index) {
            if (index == i) {
                val.target++;
                parent.salestarget=Number(parent.salestarget)+1;
            }
        });
        // for(let index=0;index<this.product_info.length;index++){
        //     if(index == i){
        //         val.target++;
        //         parent.salestarget=Number(parent.salestarget)+1;
        //     }
        // }
        console.log(parent)
        // fulldata = Object.assign(data[i],{'equalto': false,'lessthan': false});
       // this.salesUpdate(val, parent);
    }
    lessthan(a,b){
        var result;
        result= (Number(a)>Number(b)) ? true : false;
        return result;
    }
    equalto(a,b){
        var result;
        result= (Number(a)==Number(b)) ? true : false;
        return result;
    }
    // public greaterThan(data) {
    //     console.log(data)
    //     var fulldata;
    //    for(let i=0;i<data.length;i++){
    //         if(Number(data[i].target) >= Number(data[i].min_target)){
    //             fulldata = Object.assign(data[i],{'lessthan': true,'equalto': false});
    //         }else{
    //             fulldata = Object.assign(data[i],{'lessthan': false,'equalto': false});
    //         }
    //         if(Number(data[i].target) == Number(data[i].min_target)){
    //             fulldata = Object.assign(data[i],{'equalto': true,'lessthan': false});
    //         }else{
    //             fulldata = Object.assign(data[i],{'equalto': false,'lessthan': false});
    //         }
    //    }
    //   }
    modelarr:any=[]
    salesUpdate(i,value) {
        console.log(i);
        console.log(value)
        this.modelarr=[]
        console.log(value,'val')
        var modal = document.getElementById('myModal');
        var btn = document.getElementById("myBtn_1");
        btn.onclick = function() {
            modal.style.display = "block";
        }
         window.onclick = function(event) {
        if (event.target == modal) {
         modal.style.display = "none";
        }
        }
        // if(value.segment_min_target>=value.salestarget){
            value.model.forEach((val,index) => {
                this.modelarr.push({ model_id: val.model_id, target: val.target,smpin:value.smpin  })
              });
         
          let month = moment(this.sales_date, "MMM YYYY").format("MM");
          let year = moment(this.sales_date, "MMM YYYY").format("YYYY");
          // modelarr = [{ model_id: sub.model_id, target: sub.target }]
          if(value.segment_min_target <= value.salestarget ){
            this.server.post("manager/newsalestargetupdate", {
                year: year,
                month: month,
                model_arr:JSON.stringify(this.modelarr)
            }).then((data) => {
                if (data.status == 200 && data.result.data != null) {
                    this.error_msg= false;
                    $('#myModal').modal('show');
                     this.modelarr =[];
                     this.user_info=data.result.data;
                     let m = moment(this.sales_date, "MMM YYYY").format("MM");
                     let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
                     let page:number;
                    if(this.activePage>1){
                        this.current_page=this.activePage-1
                     }else{
                        this.current_page=this.activePage
                     }
                     this.salesTarget(y, m, this.current_page, "am")
                     this.data_error= 'Target Updated Successfully';
                    // let updated_data: any = [];
                    // console.log(this.selected_index)
                    // updated_data = data.result.data[0];
                    // this.user_info.forEach(function (list, index) {
                    //     console.log(list)
                    //     console.log(updated_data)
                    //     if (list.smpin == updated_data.smpin) {
                    //         list.salestarget = updated_data.salestarget;
                    //     }
                    // });
                    // alert("success")
                    // $('#myModal').modal('hide');
                    
                    setTimeout(() => {
                        $('#myModal').modal('show');
                       
                    }, 500);
                   
                    // console.log(this.user_info)
                }  else if (data.status == 406 && data.result.response=='failed') {
                    this.error_msg= false;
                    //alert("erro")
                    // console.log(this.user_info)
                    this.data_error=data.result.message;
                    $('#myModal').modal('show');
                    // alert("erorr")
                    // alert(data.result.message);
                }else{
                        this.router.navigateByUrl('/login')
                }
            });
          }else{
            this.error_msg= false;
            if(value.segment==2){
                this.data_error="Kindly set minimum of" +" "+value.segment_min_target+" "+ "Scooters per month as target and click submit.";
            }else{
                this.data_error="Kindly set minimum of" +" "+value.segment_min_target+" "+ "Motorcycles per month as target and click submit.";
            }
            $('#myModal').modal('show');
        }
    }
    importData() {
        $('#import_data').modal({
            backdrop: 'static',
            keyboard: false
        })
        $("#import_data").modal('show');
        this.fileInput.nativeElement.value = '';
        this.file_name = '';
    }
    cancelEdit(event) {
        this.file_name = event.target.files[0];
        this.file_name = '';
        $("#import_data").modal('hide');
    }
    onFileUpload(event) {
        // console.log(event.target.files)

        this.file_name = event.target.files[0];
        let image: any = new Image();
        let reader = new FileReader();
        let that = this;
        // this.show_croper = true;
        // reader.onload = (e) => {
        //   let current_file: any = e.target;
        //   image.src = current_file.result;
        //   that.cropper.setImage(image);
        // }
        reader.readAsDataURL(this.file_name);
    }
    uploadData() {
        this.page_load = true;
        this.excel_load = true;
        let _url: string;
        _url = "manager/uploadtargetsale"
        let send_data: any = {};
        let fileuploadcomplete = true;
        if (this.file_name != undefined && this.file_name != null && this.file_name != '') {
            send_data.file = this.file_name;
            send_data.area = (this.user_role < 7) ? this.am_email : (this.user_role == 14) ? this.userData.dealer.am_email : this.userData.emailid
            $("#import_data").modal('hide');
            this.server.fileUpload(_url, send_data, true, (data) => {
                if (fileuploadcomplete) {
                    this.page_load = false;
                    this.excel_load = false;
                    this.file_name = '';
                    // alert(JSON.parse(data).message)
                    // console.log(JSON.parse(data).message)
                    fileuploadcomplete = false;


                    //   $("#validate_data").modal('show');

                } else {
                    this.page_load = false;
                    this.excel_load = false;
                    this.file_name = '';
                }
            })
        }

        //   }
    }
}
