import { Component, OnInit, ViewChild } 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';
import { FeedbackPopupComponent } from '../feedback-popup/feedback-popup.component';
import { send } from 'q';
import { CONFIG } from '../../config';
import { filter, pairwise } from 'rxjs/operators';

@Component({
    selector: 'app-feedback-report',
    templateUrl: './feedback-report.component.html',
    styleUrls: ['./feedback-report.component.scss']
})
export class FeedbackReportComponent implements OnInit {
    sub: any;
    type: any;
    user_id: any;
    userData: any = {};
    user_info: any;
    feedbackList: any = [];
    loader: boolean;
    report_data: any;
    sales_date: any;
    page_load: boolean;
    excel_load: boolean;
    export_url: any;
    location_selected: any;
    row_selected: any;
    selected_title: any = '';
    selected_feedback: any = '';
    mymodel: any = [];
    searchText: any = [];
    assessmentid: string = '';
    assessmentname: string = '';
    selected_feedbackid: string = "";
    active_product: number;
    product_info: any = [];
    report_user: number;
    _url: any;
    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;
    total_item: number;
    page_per_size: number = 10;
    current_page: number;
    total_page: number;
    activeItem: number = -1;
    activePage: number = 1;
    page_count: number = 0;
    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;
    @ViewChild(FeedbackPopupComponent) feedback_modal: FeedbackPopupComponent;
    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.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') {
            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.getFeedbackList()
                }
            }

        }
        console.log(this.userData)
        this.location_selected = this.leader_type.filter(question => question.is_selected == 1);
        this.row_selected = this.feedbackList.filter(question => question.is_selected == 1);
    }
    //pagination
    public getServerData(event) {
        console.log(event)
        this.page_count = (event - 1);
        if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
            // this.zmReport(this.activePage)
            this.getDseReport(this.assessmentid, this.page_count, "zm")
        } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
            // this.rmReport(this.activePage)
            this.getDseReport(this.assessmentid, this.page_count, "rm")
        } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
            // this.amReport(this.activePage)
            this.getDseReport(this.assessmentid, this.page_count, "am")
        }
        console.log('page', this.page_count)
        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) {
        console.log(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;
        this.getFeedbackList()
    }
    // 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;
                    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;
        this.getFeedbackList()
    }

    // 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;
        // LocalStorage.setValue("ammail", this.am_email)
        this.current_page = 0;
        this.activePage = 0;
        this.getFeedbackList()
    }
    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 {
                    this.getFeedbackList()
                    // this.getDseReport()
                }
            }
            else if (data.result.status == 401 && data.result.response == 'failed') {
                this.router.navigateByUrl('');
            }
            else {
                alert("Oops something happened!");
            }
        })
    }
    getFeedbackList() {
        this.loader = true
        this._url = "manager/surveylist"
        this.server.get(this._url)
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed') {
                    setTimeout(() => {
                        this.loader = false
                        this.feedbackList = data.result.data;
                        if (this.feedbackList.length > 0) {
                            this.mymodel = this.feedbackList[0];
                            this.assessmentid = this.feedbackList[0].assessmentid;
                            this.assessmentname = this.feedbackList[0].assessmentname;
                            console.log('pageeee', this.page_count)
                            if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
                                this.getDseReport(this.assessmentid, this.page_count, "zm")
                            } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
                                this.getDseReport(this.assessmentid, this.page_count, "rm")
                            } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
                                this.getDseReport(this.assessmentid, this.page_count, "am")
                            }
                        }
                    }, 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;
    }
    dropSelect(val) {
        console.log(val)
        this.assessmentid = val.assessmentid;
        this.assessmentname = val.assessmentname;
        console.log(this.assessmentname)
        this.current_page = 0;
        this.activePage = 0;
        if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
            this.getDseReport(this.assessmentid, this.activePage, "zm")
        } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
            this.getDseReport(this.assessmentid, this.activePage, "rm")
        } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
            this.getDseReport(this.assessmentid, this.activePage, "am")
        }
    }

    isLocationSelected() {
        this.location_selected = this.leader_type.filter(question => question.is_selected == 1);
        this.current_page = 0;
        this.activePage = 0;
        if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
            this.getDseReport(this.assessmentid, this.activePage, "zm")
        } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
            this.getDseReport(this.assessmentid, this.activePage, "rm")
        } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
            this.getDseReport(this.assessmentid, this.activePage, "am")
        }
    }
    getDseReport(id, page, role) {
        this.loader = true
        console.log(this.selected_title)
        if (this.selected_title == '') {
            this.sort_by = 0
        }
        if (this.searchText == "") {
            this.searchText = '';
        }
        this._url = "manager/newsurveyreport/"+role+"?page=" + page + "&limit=10&filter=sort:" + this.sort_by + "";
        this.server.post(this._url, {
            search: this.searchText,
            assessmentid: id,
            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
            // 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 && 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('');
                }
            });
    }
    showDetails(val, list) {
        if (this.active_product == val) {
            this.active_product = null;
        } else {
            this.active_product = val
            this.getDseReportDetails(list)
        }
    }
    getDseReportDetails(list) {
        console.log(list.userid)
        let sendData: any = {};
        sendData.userid = list.userid
        sendData.username = list.fname + ' ' + list.lname
        sendData.dealer_name = list.dealer_name
        sendData.assessment_date = list.assessment_date
        sendData.assessmentid = this.assessmentid
        sendData.assessmentname = this.assessmentname
        console.log(sendData)
        this.feedback_modal.showcontentrModal('Result', { sendData }, (data) => {
        })

    }
    onSearchChange(searchValue: string) {
        this.searchText = searchValue;
        console.log(this._url)
        this.current_page = 0;
        this.activePage = 0;
        if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
            // this.zmReport(this.activePage)
            this.getDseReport(this.assessmentid,this.activePage,"zm")
          } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
            // this.rmReport(this.activePage)
            this.getDseReport(this.assessmentid,this.activePage,"rm")
          } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
            // this.amReport(this.activePage)
            this.getDseReport(this.assessmentid,this.activePage,"am")
          }

    }
}
