import { Component, OnInit, TemplateRef, ViewChild, ViewContainerRef, OnDestroy, AfterViewInit } from '@angular/core';
import { SellPlanningService } from './sell-planning.service';
import { OverlayConfig, Overlay } from '@angular/cdk/overlay';
import { TemplatePortal } from '@angular/cdk/portal';
import { DatePipe } from '@angular/common';
import { AngPophelpComponent } from '../../ang-pophelp/ang-pophelp.component';
import { AppDateAdapter, APP_DATE_FORMATS } from '../../search-menu/date.adapter';
import { DateAdapter, MAT_DATE_FORMATS } from '@angular/material/core';
import { MatDialog } from '@angular/material/dialog';
import { ConfirmBoxComponent } from 'src/components/shared/confirm-box/confirm-box.component';
import { FormGroup, FormBuilder } from '@angular/forms';
import { changeThemeColor } from '../../../plugin/utils/theme-selector-util';

@Component({
  selector: 'sell-planning',
  templateUrl: './sell-planning.component.html',
  styleUrls: ['./sell-planning.component.css'],
  providers: [{
    provide: DateAdapter, useClass: AppDateAdapter
  },
  {
    provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
  },
    DatePipe
  ]
})
export class SellPlanningComponent implements OnInit, OnDestroy, AfterViewInit {
  spName = "";
  salesPers = "";
  posCode = "";
  posCodeDescr = "";
  stanCode = "";
  process: boolean = true;
  public prdCode = "";
  _ELEMENT_DATA: any[] = [];
  public rateWiseSumOfKeys = ["Sell-in(plan)", "Sell-out(plan)"];  //["Sell In", "Sell Out"]
  sideBarContainerHeight!: number;
  dashBoardData:any;
  isView: boolean = true;

  prdCodeDescr:any = "";
  objNameInput:any = 'sell_planning';
  dataSource:any = "";
  fieldValue:any = "";
  refId:any = "";
  filterName:any = "";
  isBrowser!: boolean;
  overlayRef:any;
  pophelpSelectedvalue:any = "";
  itemChangeData:any;
  itemDefaultData:any;
  jsonData:any;
  tempItemChangeData:any;
  public jsonResp: any;
  public action = "save";
  pophelpTitle:any;
  popelpArr:any = {
    'SP_NAME': 'Customer',
    'PRD_CODE_DESCR': 'Period',
    'POS_CODE_DESCR': 'Territory'
  }
  errorFlag: boolean = true;
  cnt:any = 0;
  warnCnt:any = 0;
  validateJSON: any;
  tempItmChg:any;
  validationData:any;
  forceSave = "N";
  finishButton = "Submit"
  cancelButton = "Previous"
  saveButton = "Save/Draft"

  @ViewChild('portal', { read: TemplateRef }) _templatePortal!: TemplateRef<any>;
  @ViewChild(AngPophelpComponent) Pophelp!: AngPophelpComponent;
  //By Sainath T. on 28-02-2020
  pophelpSelectedKey: string = "";
  /* Sainath T-start 10/04/2020 [for abm related changes]-Start */
  isSubmitDisable: boolean = false;
  isSubordinateCall: boolean = false;
  ELEMENT_DATA: any = [];//new 257
  subordinateData: any = [];
  isSubordinateSelected: boolean = false;
  isLoadDefault: boolean = false;
  oldJsonValues: any = {};
  isAllSelected: boolean = false;
  /* Sainath T-start 10/04/2020 [for abm related changes]-End */
  /* Pooja S-start 10/04/2020 [for abm related changes]-Start */
  //levelNo: number = 0;
  //loginUserLevelNo: number = 0;
  posCodeDescrLogin:any = "";
  stanCodeLogin:any = "";
  salesPersLogin:any = "";
  isMgr: boolean = false;
  isLoginUserMgr: boolean = false;
  isSubordinateMgr:boolean = false;
  isApprover: boolean = false;
  sentBackButton:any = "Send Back"
  terrObjStatus:any = "";
  loginStatus:any = "";
  statusFlag: boolean = false;
  removeSubmit: boolean = false;
  posCodeLogin:any = "";
  validDifferCall:any = "";
  /* Pooja S-start 10/04/2020 [for abm related changes]-End */
  //Added By Sainath T. on 23/04/2020 -Start
  confirmBox:any = null;
  selectionListForm!: FormGroup;
  //Added by Sainath T. on 29-09-2020
  isMobile : boolean = false;
  definedCellTotalUpdates :boolean = false;
  constructor(public _stockSellService: SellPlanningService, public overlay: Overlay, private viewContainerRef: ViewContainerRef, public datePipe: DatePipe, public dialog: MatDialog, private fb: FormBuilder) 
  {
    this.confirmBox = new ConfirmBoxComponent(dialog);
      //Added by Sainath T. on 29-09-2020 -start
      let index = window.location.pathname.indexOf('E12BROWSER');
      if(index == -1){
          this.isMobile = true;
      }
  }

  ngOnInit() 
  {
    //Added by Sainath T -start
    var themeColor = localStorage.getItem('themeColor');
    if (themeColor) {
    changeThemeColor(themeColor);
    }
    //Added by Sainath T -end
    var img = document.getElementById('userImageHbId_initE12userInfo');
    if (img)
      img.style.display = "none";
    this._stockSellService.defaultSellPlan().subscribe(
      data => {
        if (data) 
        {
          try 
          {
            this.itemDefaultData = data;
            this.posCode = this.itemDefaultData['pos_code'];
            /* Pooja S-start 10/04/2020 [for abm related changes] */
            this.posCodeLogin = this.posCode;
            this.posCodeDescr = this.itemDefaultData['pos_code_descr'];
            this.posCodeDescrLogin = this.posCodeDescr;
            this.stanCode = this.itemDefaultData['stan_code'];
            this.stanCodeLogin = this.stanCode;
            this.prdCode = this.itemDefaultData['prd_code'];
            this.prdCodeDescr = this.itemDefaultData['prd_code_descr'];
            this.salesPers = this.itemDefaultData['sales_pers'];
            this.salesPersLogin = this.salesPers;
            this.spName = this.itemDefaultData['sp_name'];
            /* Pooja S-start 10/04/2020 [for abm related changes] Start */
            //this.levelNo = this.itemDefaultData['level_no'];
            //this.loginUserLevelNo = this.levelNo;
            this.isAllSelected = true;
            //Pooja S-start 11/04/2020
            this.statusFlag = this.itemDefaultData['status_flag'];
            console.log('this.statusFlag' + this.statusFlag);
            //console.log('this.levelNo' + this.levelNo);
            //if (this.levelNo <= 7) 
            //{
              this.isMgr = this.itemDefaultData['is_mgr'];
              this.isLoginUserMgr = this.isMgr;
            //}
            console.log('this.this.isMgr' + this.isMgr);
            this.isApprover = this.itemDefaultData['is_approver'];
            console.log(' this.isApprover ' + this.isApprover);
            /* Pooja S-start 10/04/2020 [for abm related changes] End */
            /* Sainath T-start 10/04/2020 [for abm related changes] End */
            if (this.itemDefaultData['subordinate_data'] && this.itemDefaultData['subordinate_data'] != undefined) 
            {
              this.subordinateData = this.itemDefaultData['subordinate_data'];
              console.log("login user status 1 time" + this.subordinateData[0]["planning_status"]);
              if (this.subordinateData[0]["planning_status"] == 'S') 
              {
                this.removeSubmit = true;
              }
              else 
              {
                this.removeSubmit = false;
              }
              //Adde by Sainath T. on 23/04/2020 [to set default selected option]
              this.selectionListForm = this.fb.group({
                selectionListControl: [this.subordinateData[0]]
              });
            }
            /* Sainath T-start 10/04/2020 [for abm related changes] End */
          }
          catch (error) 
          {
            console.log(' ##  Error  ## ', error);
          }
        }
      }
    );
  }

  ngOnDestroy() 
  {
    var img = document.getElementById('userImageHbId_initE12userInfo');
    if (img)
      img.style.display = "block";
  }

  getStockData(action?:any) 
  {
    console.log('<< inside getStockData >>', this.isLoadDefault, "isSubordinateCall>", this.isSubordinateCall, "isSubordinateSelected>", this.isSubordinateSelected);
    console.log("action", action);
    if (action == 'Next') 
    {
      this.isLoadDefault = false;
      this.isSubordinateCall = false;
    }
    this.validateJSON = {
      'pos_code_descr': this.posCodeDescr,
      'prd_code_descr': this.prdCodeDescr,
      'prd_code': this.prdCode,
      'stan_code': this.stanCode
    }
    /* Sainath T-start 10/04/2020 [for abm related changes] Start */
    if (!this.isSubordinateSelected) 
    {
      this.setOldValueJson();
    }
    /* Sainath T-start 10/04/2020 [for abm related changes] End */
    this.cnt = 0;
    this.onValidation('all_form_validation', JSON.stringify(this.validateJSON));
  }

  drawSellPlanTable() 
  {
    console.log('drawSellPlanTable>>' + this.posCode + "posCodeLogin >>" + this.posCodeLogin);
    //Added by Pooja S. on 11/04/2020 [For abm related chnges]-Start
    if (this.posCode == this.posCodeLogin) 
    {
      this.isAllSelected = true;
    }
    //Added by Pooja S. on 11/04/2020 [For abm related chnges]-End
    if (this.salesPers && this.prdCode) {
      var jsonData = {
        'pos_code': this.posCode,
        'stan_code': this.stanCode,
        'sales_pers': this.salesPers,
        'prd_code': this.prdCode,
        'force_save': this.forceSave,
        'is_mgr': this.isMgr
        //'level_no' : this.levelNo
      }
      this._stockSellService.setLoading(true);
      this._stockSellService.getSellsPlanDetails(jsonData).subscribe(
        data => {
          if (data) 
          {
            //Commented by Sainath T. for ang9
            // this.validationData = data = JSON.parse((<any>data)._body);
            this.validationData = data;
            console.log('getSellsPlanDetails resp   ', this.validationData);
             //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ]
             var trace = "", errorMsg = "", type = "",message="";
            try 
            {
              this.warnCnt = 0;
              for (var i = 0; i < this.validationData.length; i++) 
              {
                //console.log('Loop  '+i+'  ');
                if (this.validationData[i]["trace"] && this.validationData[i]["trace"] != '') 
                {
                  trace = this.validationData[i]["trace"];
                }
                if (this.validationData[i]["description"] && this.validationData[i]["description"] != '') 
                {
                  errorMsg = this.validationData[i]["description"];
                }
                 //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ] Start
                 if (this.validationData[i]["message"] && this.validationData[i]["message"] != '') 
                 {
                   message = this.validationData[i]["message"];
                 }
                 //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ] End
                if (this.validationData[i]["type"] && this.validationData[i]["type"] != '') 
                {
                  type = this.validationData[i]["type"];
                  if (type == "E" || type == "X") 
                  {
                    this.cnt++;
                  }
                  else if (type == "W") 
                  {
                    this.warnCnt++;
                  }
                }
              }
              //console.log('this.warnCnt     ',this.warnCnt,this.cnt);
              if (this.warnCnt > 0) 
              {
                this._stockSellService.setLoading(false);
                //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ]
                var errMsg = this._stockSellService.getValidPopupMsg("W",message,errorMsg);                
                this.confirmBox.confirm("confirm", errMsg ).subscribe((resp:any) => {
                  console.log('warningg response:' + resp);
                  if (resp == "YES") 
                  {
                    this._stockSellService.setLoading(true);
                    this.forceSave = "Y";
                    jsonData['force_save'] = this.forceSave;
                    this._stockSellService.getSellsPlanDetails(jsonData).subscribe(
                      data => {
                        if (data) 
                        {
                          this.getServiceData(data);
                          //data = JSON.parse((<any>data)._body);
                          //this.sellsPlanDetail(data);
                        }
                      });
                  }
                  else if (resp == "NO") 
                  {
                    this._stockSellService.setLoading(false);
                  }
                });
              }
              else if (this.cnt > 0) 
              {
                // alert(trace  + '\n'+ errorMsg);
                this._stockSellService.setLoading(false);
                //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ]
                var errMsg = this._stockSellService.getValidPopupMsg(type,message,errorMsg);
                this.confirmBox.alert("Error", errMsg);
              }
              else 
              {
                this.sellsPlanDetail(data);
              }
            }
            catch (error) 
            {
              console.log("Failed................", error);
            }
          }
        });
    }
  }

  sellsPlanDetail(data:any) 
  {
    console.log('##  sellsPlanDetail    ', data);
    /* Sainath T- 10/04/2020 [Commented and changed for abm related changes] */
    //this._ELEMENT_DATA = data;
    this.ELEMENT_DATA = data;
    var jsonData = {
      'stan_code': this.stanCode,
      'prd_code': this.prdCode,
      'pos_code': this.posCode
    }
    this._stockSellService.getSellPerformanceDashboardData(jsonData).subscribe(
      dashData => {
        /* Sainath T- 10/04/2020 [for abm related changes] */
        if (!this.isSubordinateSelected) 
        {
          //Commented by Sainath T. for ang9
          // this.dashBoardData = JSON.parse((<any>dashData)._body);
          this.dashBoardData = dashData;
        }
        /* Sainath T-start 10/04/2020 [ for abm related changes] */
        setTimeout(() => {
          /* Sainath T- 10/04/2020 [Commented and changed for abm related changes] */
          //if( this._ELEMENT_DATA && this._ELEMENT_DATA.length > 0)
          if (this.ELEMENT_DATA && this.ELEMENT_DATA.length > 0) 
          {
            try 
            {
               //Added by Sainath T. on 29-09-2020
               this.definedCellTotalUpdates = true;
              /* Sainath T- 10/04/2020 [Commented and changed for abm related changes] */
              //var  status = this._ELEMENT_DATA[this._ELEMENT_DATA.length - 1].status;
              var status = this.ELEMENT_DATA[this.ELEMENT_DATA.length - 1].status;
              if (status && status == 'S') 
              {
                this.saveButton = '';
                this.finishButton = '';
                //Added by Sainath T. on 07-02-2020 [to remove status object from JsonArray to avoide extra row in table]
                //this._ELEMENT_DATA.pop();
                this.ELEMENT_DATA.pop();
                // Sainath T. on 07-04-2020 -End
              }
              else 
              {
                this.saveButton = 'Save/Draft';
                this.finishButton = 'Submit';
              }
              /* Pooja S- 10/04/2020 [ for abm related changes]-Strat */
              if (this.isMgr) 
              {
                if (this.removeSubmit) 
                {
                  this.finishButton = '';
                  this.sentBackButton = '';
                }
                else 
                {
                  if (this.isApprover) 
                  {
                    this.finishButton = 'Approve';
                  }
                  else 
                  {
                    this.finishButton = 'Submit';
                  }
                  this.sentBackButton = 'Send Back';
                }
                this.saveButton = '';
                //console.log('this.levelNo  sentBackButton > '+this.levelNo);
                //console.log('this.isAllSelected > '+this.isAllSelected+"this.statusFlag>>>"+this.statusFlag);
                if (this.isAllSelected && !this.statusFlag) 
                {
                  this.isSubmitDisable = false;
                }
                else 
                {
                  this.isSubmitDisable = true;
                }
              }
              else 
              {
                this.sentBackButton = '';
              }
            }
            /* Pooja S- 10/04/2020 [ for abm related changes]-Strat */
            catch (error) 
            {
              console.log('Exception status ..  ', error);
            }
            //Added by Sainath T. on 10-04-2020[for abm related changes] -Start
            this._ELEMENT_DATA = this.ELEMENT_DATA;
            console.log('this.isSubordinateSelected >>' + this.isSubordinateSelected, "this.isLoadDefault", this.isLoadDefault);
            if (this.isSubordinateSelected || this.isLoadDefault) 
            {
              this.isSubordinateCall = true;
            }
            console.log('this.isSubordinateCall >>' + this.isSubordinateCall);
            //Added by Sainath T. on 10-04-2020[for abm related changes] -End

            //console.log('>>  JSON DATA001   <<',this._ELEMENT_DATA,'dashBoardData>>'+this.dashBoardData);
            this._stockSellService.setLoading(false);
            this.process = false;
          }
          else 
          {
            //window.alert('No Data Found'); 
            this._stockSellService.setLoading(false);
            this.confirmBox.alert("Error", "No Data Found");
          }
        }, 200);
      }
    );
  }

  onCancel() 
  {
    //Added by Sainath T. on 29-09-2020
    this.definedCellTotalUpdates = false;
    this.forceSave = "N";
    this.process = true;
    console.log('ss isSubordinateSelected>>'+this.isSubordinateSelected+' subordinateData>>'
    +JSON.stringify(this.subordinateData)+ '  oldJsonValues'+this.oldJsonValues)
    //Added by Sainath T. on 10-04-2020[for abm related changes] -Start
    if (this.isSubordinateSelected) 
    {
      this.isSubordinateSelected = false;
      this.isSubordinateCall = false;
      this.posCodeDescr = this.oldJsonValues['pos_code_descr'];
      this.stanCode = this.oldJsonValues['stan_code'];
      this.posCode = this.oldJsonValues['pos_code'];
      this.salesPers = this.oldJsonValues['sales_pers'];
      this.spName = this.oldJsonValues['sp_name'];
      //Added by Saianth T. on 23/04/2020
      this.selectionListForm = this.fb.group({
        selectionListControl: [this.subordinateData[0]]
      });
    }
    //Added by Sainath T. on 10-04-2020[for abm related changes] -End
  }

  onHeaderClick() 
  {
    this.isView = !this.isView;
  }

  onItemChange(columnName:any, columnValue:any, paraValue?:any) 
  {
    //console.log('inside onItemChange',columnName,columnValue);
    if (columnValue != '' && this.tempItemChangeData != columnName) 
    {
      this.itemChangeData = columnValue;
      try 
      {
        this._stockSellService.itemChange(columnName, columnValue, paraValue).subscribe(
          data => {
            if (data) 
            {
              this.jsonData = data;
              //Commented by Sainath T. for ang9
              //this.itemChangeData = JSON.parse(JSON.stringify(data));
              this.itemChangeData = data;

              //console.log('>>>>>>>>>>>itemChangeData >>>>>>>>>>>',this.itemChangeData);

              if (columnName === 'prd_code_descr') 
              {
                for (var i = 0; i < this.itemChangeData.length; i++) 
                {
                  if (this.itemChangeData[i]["prd_code"] && this.itemChangeData[i]["prd_code"] != '') 
                  {
                    this.prdCode = this.itemChangeData[i]["prd_code"];
                    this.statusFlag = this.itemChangeData[i]["status_flag"];
                    this.subordinateData = this.itemChangeData[i]["subordinate_data"];
                    //console.log("login user status 2nd time"+this.subordinateData[0]["planning_status"]);
                    if (this.subordinateData[0]["planning_status"] == 'S') //|| this.subordinateData[0]["planning_status"] == ''
                    {
                      this.removeSubmit = true;
                    }
                    else 
                    {
                      this.removeSubmit = false;
                    }
                    this.selectionListForm = this.fb.group({
                      selectionListControl: [this.subordinateData[0]]
                    });
                  }
                  else 
                  {
                    this.prdCode = '';
                  }
                }
              }
              else if (columnName === 'sp_name') 
              {
                for (var i = 0; i < this.itemChangeData.length; i++) 
                {
                  if (this.itemChangeData[i]["sales_pers"] && this.itemChangeData[i]["sales_pers"] != '') 
                  {
                    this.salesPers = this.itemChangeData[i]["sales_pers"];
                  }
                  else 
                  {
                    this.salesPers = '';
                  }
                }
              }
              else if (columnName === 'pos_code_descr') 
              {
                this.posCodeDescrLogin = columnValue;
                this.isMgr = false;
                for (var i = 0; i < this.itemChangeData.length; i++) 
                {
                  if (this.itemChangeData[i]["stan_code_hq"] && this.itemChangeData[i]["stan_code_hq"] != '') 
                  {
                    this.stanCode = this.itemChangeData[i]["stan_code_hq"];
                    this.stanCodeLogin = this.stanCode;
                  }
                  else 
                  {
                    this.stanCode = '';
                  }

                  if (this.itemChangeData[i]["pos_code"] && this.itemChangeData[i]["pos_code"] != '') 
                  {
                    this.posCode = this.itemChangeData[i]["pos_code"];
                    this.posCodeLogin = this.posCode;
                  }
                  else 
                  {
                    this.posCode = '';
                  }
                  //if (this.itemChangeData[i]["level_no"]) 
                  //{
                  //  this.levelNo = this.itemChangeData[i]["level_no"];
                  //  if (this.levelNo <= 7) 
                  //  {
                      this.isMgr = this.itemChangeData[i]["is_mgr"];
                  //  }
                    this.isLoginUserMgr = this.isMgr;
                  //}
                  this.statusFlag = this.itemChangeData[i]["status_flag"];
                  if (!this.statusFlag) 
                  {
                    this.isSubmitDisable = false;
                  }
                  this.salesPers = this.itemDefaultData['sales_pers'];
                  this.salesPersLogin = this.salesPers;

                  this.spName = this.itemDefaultData['sp_name'];

                  this.isApprover = this.itemChangeData[i]['is_approver'];
                  console.log('isApprover>>>>>>' + this.isApprover);

                  this.subordinateData = this.itemChangeData[i]["subordinate_data"];
                  if (this.subordinateData[0]["planning_status"] == 'S') 
                  {
                    this.removeSubmit = true;
                  }
                  else 
                  {
                    this.removeSubmit = false;
                  }
                  this.selectionListForm = this.fb.group({
                    selectionListControl: [this.subordinateData[0]]
                  });
                  this.isAllSelected = true;
                }
              }
            }
          }
        );
      }
      catch (error) 
      {
        console.log('Error while calling Service....', error);
      }
    }
    else 
    {
      console.log('itemChanged not get called as fields are blank!!');
      if (columnName == 'prd_code_descr') 
      {
        this.prdCode = '';
      }
      if (columnName == 'sp_name') 
      {
        this.salesPers = '';
      }
    }
  }

  onValidation(columnName:any, columnValue:any) 
  {
    console.log('Inside OnValidation !!');
    var trace = '';
    var type = '';
    //Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ]
    var message='';
    var errorMsg = '';
    if (columnValue != '' && this.tempItmChg != columnValue || columnName == 'all_form_validation') 
    {
      this.tempItmChg = columnValue;
      this._stockSellService.onValidation(columnName, columnValue).subscribe(
        data => {
          if (data) 
          {
            try 
            {
              this.validationData = data;
              for (var i = 0; i < this.validationData.length; i++) 
              {
                if (this.validationData[i]["trace"] && this.validationData[i]["trace"] != '') 
                {
                  trace = this.validationData[i]["trace"];
                }
                if (this.validationData[i]["description"] && this.validationData[i]["description"] != '') 
                {
                  errorMsg = this.validationData[i]["description"];
                }
                 //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ] Start
                 if (this.validationData[i]["message"] && this.validationData[i]["message"] != '') 
                 {
                   message = this.validationData[i]["message"];
                 }
                 //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ] End
                if (this.validationData[i]["type"] && this.validationData[i]["type"] != '') 
                {
                  type = this.validationData[i]["type"];
                  if (type == "E" || type == "X") 
                  {
                    this.cnt++;
                  }
                  else if (type == "W") 
                  {
                    this.warnCnt++;
                  }
                }
              }
              //changed by Pooja S on 10-AUGUST-2020 [ Display the error message on validation of type X ]
              if (trace != '' && errorMsg != '' && (type == 'E' || type == 'X')) 
              {
                this._stockSellService.setLoading(false);
                //changed by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ]
                var errMsg = this._stockSellService.getValidPopupMsg(type,message,errorMsg);    
                this.confirmBox.alert("Error", errMsg );
              }
              if (trace != '' && errorMsg != '' && type == 'W') 
              {
                //changed by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ]
                var errMsg = this._stockSellService.getValidPopupMsg(type,message,errorMsg);
                 this.confirmBox.confirm("Warning", errMsg);
                //var yesNo =  confirm(trace +  '. <br>' + errorMsg);
              }

              if (this.cnt > 0) 
              {
                this.errorFlag = true;
              }
              else 
              {
                this.errorFlag = false;
              }

              if (!this.errorFlag && columnName == 'all_form_validation') 
              {
                this.drawSellPlanTable();
              }

              trace = '';
              errorMsg = '';
            }
            catch (error) 
            {
              console.log('Exception in Validation Form', error);
            }
          }
        }
      );
    }
  }

  openSuggest(id:any) 
  {
    console.log('openSuggest...............', id);
    this.pophelpTitle = this.popelpArr[id];
    //console.log('pophelpTitle            ',this.pophelpTitle);
    var paramMap:any = {};
    var paramString = "";
    this.refId = id;

    paramMap["OBJ_NAME"] = "sell_planning";
    paramMap["ACTION"] = "AUTO_SEARCH_POPHELP";
    paramMap["FIELD_NAME"] = this.refId;
    if (id == "SP_NAME") 
    {
      //paramMap["SQL_INPUT"] = ":chg_user";
    }
    paramMap["EDITOR_ID"] = "";
    paramMap["FORM_NO"] = "";
    paramMap["PARAMXML"] = this.buildParamXML();
    paramMap["PKVLAUE"] = "";
    paramMap["EDIT_FLAG"] = "";
    paramMap[this.refId] = this.objNameInput;
    paramString = this._stockSellService.getEncodedParamString(paramMap);
    this.dataSource = "/ibase/RIAWizardHandlerServlet?" + paramString;
    this.fieldValue = this.objNameInput;
    this.filterName = this.refId + '_' + this.objNameInput;
    setTimeout(() => this.createOverlay(), 200);
  }

  createOverlay() 
  {
    var config = new OverlayConfig();
    var width = '500px';
    var top = this.isBrowser ? '0px' : '40px';
    var height = 'auto';
    var left = " calc(100% - 360px)";
    console.log('SetTimeOut start 2');

    config.hasBackdrop = true;
    config.positionStrategy = this.overlay.position()
      .global()
      .centerHorizontally()
      .width(width)
      .left(left)
      .top(top)
      .height(height);
    const templatePortal = new TemplatePortal(
      this._templatePortal,
      this.viewContainerRef
    );
    console.log('SetTimeOut start 4');

    this.overlayRef = this.overlay.create(config);
    this.overlayRef.attach(templatePortal);
  }

  onSelectionChange(event:any) 
  {
    console.log('on change selection event', event, event.value);
    this.pophelpSelectedvalue = event.value;
    this.pophelpSelectedKey = event.display;
    console.log('pophelpSelectedKey>>' + this.pophelpSelectedKey);
  }

  onDone() 
  {
    try 
    {
      //console.log('on done pophelpSelectedvalu [' + this.pophelpSelectedvalue + ']   refId ['+this.refId+']');
      if (this.refId == 'PRD_CODE_DESCR') 
      {
        this.prdCodeDescr = this.pophelpSelectedvalue;
        //console.log(' On Done prdCodeDescr Code  ',this.prdCodeDescr);
        this.onItemChange('prd_code_descr', this.prdCodeDescr, this.posCode);
      }
      if (this.refId == 'SP_NAME') 
      {
        this.spName = this.pophelpSelectedvalue;
        //console.log(' On Done spName Code  ',this.spName);
        this.onItemChange('sp_name', this.spName, "null");
      }
      if (this.refId == 'POS_CODE_DESCR') 
      {
        this.posCodeDescr = this.pophelpSelectedvalue;
        var rawStr = this.pophelpSelectedKey.substring(this.pophelpSelectedKey.indexOf('(') + 1, this.pophelpSelectedKey.length - 1);
        console.log('pophelpSelectedKey prdCode>>' + this.prdCode);

        var rawArr = rawStr.split(',');
        console.log('rawArr001>>' + rawArr);
        this.stanCode = rawArr[0];
        this.posCode = rawArr[1];
        this.onItemChange('pos_code_descr', this.posCodeDescr, this.prdCode);
      }
    }
    catch (error) 
    {
      console.log('Error in onDone', error);
    }
    this.objNameInput = this.pophelpSelectedvalue;
    this.overlayRef.dispose();
    this.pophelpSelectedvalue = "";
  }

  onPophelpCancel() 
  {
    //console.log('on onCancel', this.objNameInput);
    this.pophelpSelectedvalue = "";
    this.overlayRef.dispose();
  }

  submitSellsPlan(data:any) 
  {
    var msg = '', errorMsg = '';
    try 
    {
      if (this.isApprover) 
      {
        msg = "Are you sure you want to Approve sales plan?";
        errorMsg = "Can not Approve the plan.";
      }
      else 
      {
        msg = "Are you sure you want to Submit sales plan?";
        errorMsg = "Can not Submit the plan.";
      }
      //Added by Pooja S. on 11/04/2020 [For abm related changes]-Start
      if (this.statusFlag && (this.isMgr || this.isApprover)) 
      {
        //window.alert('Can not submit the plan.');
        this.confirmBox.alert("Error", errorMsg);
      }
      //Added by Pooja S. on 11/04/2020 [For abm related changes]-End
      else 
      {
        var errMsg = this._stockSellService.getValidPopupMsg("W","",msg);
        this.confirmBox.confirm("Confirm", errMsg).subscribe((resp:any) => {
          if (resp == "YES") 
          {
            if (this.isApprover) 
            {
              this.action = "approve";
            }
            else 
            {
              this.action = "submit";
            }
            this.saveSellsPlan(data);
          }
        });
        this.action = "save";
      }
    }
    catch (error:any) 
    {
      console.log('Exception  in submitSellsPlan ', error);
    }
  }

  //Added by Pooja S. on 10-04-2020[for abm related changes] -Start
  resetSellsPlan(data:any) 
  {
    try 
    {
      this.confirmBox.confirm("Warning!!", "Are you sure you want to Send back sales plan?").subscribe((resp:any) => {
        console.log('warningg response:' + resp);
        if (resp == "YES") 
        {
          this.action = "sentBack";
          this.sentBackSellsPlan(data, "send_back");
        }
      });
      this.action = "reset";
    }
    catch (error:any) 
    {
      console.log('Exception  in resetSellsPlan ', error);
    }
  }
  //Added by Pooja S. on 10-04-2020[for abm related changes] -End

  saveSellsPlan(data:any) 
  {
    //console.log('OnSubmit Called For Sales Planning.................',this.action );
    var jsonData = {
      'stan_code': this.stanCode,
      'pos_code': this.posCode,
      'sales_pers': this.salesPers,
      'sales_pers_name': this.spName,
      'prd_code': this.prdCode,
      'descr': this.prdCodeDescr,
      'is_mgr': this.isMgr,
      'flag': this.action
    }

    var requestJsonData = {
      'headerFormData': jsonData,
      'detailFormData': data
    }
    this._stockSellService.setLoading(true);
    //console.log('requestJsonData....................',requestJsonData);
    this._stockSellService.onFinishSellPlanning(requestJsonData).subscribe(
      data => {
        if (data) 
        {
          //console.log('onFinishSellPlanning Response data  ....  ',data);
          this._stockSellService.setLoading(false);
          //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ]
          var tranId = '', descr = '', errorMsg = '', trace = '',message='';
          var successMsg:any = {};
          //Commented by Sainath T. for ang9
          //this.jsonResp = (<any>data)._body;
          //this.jsonResp = JSON.parse(this.jsonResp);
          this.jsonResp = data;
          //console.log('Sell Planning   ',this.jsonResp,this.jsonResp.length,this.jsonResp[0],this.jsonResp[0]['tran_id']);
          for (var i = 0; i < this.jsonResp.length; i++) 
          {
            if (this.jsonResp[i]["tran_id"] && this.jsonResp[i]["tran_id"] != '') 
            {
              tranId = this.jsonResp[i]["tran_id"];
            }
            if (this.jsonResp[i]["success_msg"] && this.jsonResp[i]["success_msg"] != '') 
            {
              successMsg = this.jsonResp[i]["success_msg"];
            }
            if (this.jsonResp[i]["trace"] && this.jsonResp[i]["trace"] != '') 
            {
              trace = this.jsonResp[i]["trace"];
            }
            if (this.jsonResp[i]["description"] && this.jsonResp[i]["description"] != '') 
            {
              errorMsg = this.jsonResp[i]["description"];
            }
            // Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ] Start
            if (this.jsonResp[i]["message"] && this.jsonResp[i]["message"] != '') 
            {
              message = this.jsonResp[i]["message"];
            }
            //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ] End
            //console.log('Sell Planning errorMsg  ',errorMsg+"trace>>>>>"+trace);
          }
          descr = successMsg['description'];
          console.log('Sell Planning Desc  ', descr);
          if (tranId && descr != 'undefined') 
          {
            //this.confirmBox.alert("Success",descr);
            var validDesc = this._stockSellService.getValidPopupMsg("","","",descr);
            this.confirmBox.alert("Success", validDesc).subscribe((resp:any) => {
              descr = '';
              this.action = "save";
              this.process = true;
            });
          }
          else 
          {
            console.log('in onsubmit else part>>')
            //this.confirmBox.alert("Error",descr);
            //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ]
            var errMsg = this._stockSellService.getValidPopupMsg("E",message,errorMsg);
            this.confirmBox.alert("Error", errMsg );
          }
        }
      }
    );
  }

  buildParamXML() 
  {
    console.log("<<in build xml001>>")

    var jsonData:any =
    {
      'pos_code': this.posCode,
      'stan_code': this.stanCode,
      'prd_code': this.prdCode,
      'pos_code_descr': this.posCodeDescr,
      'sp_name': this.spName,
    }
    var paramXML = `<Detail1>`;
    for (var prop in jsonData) {
      paramXML = paramXML + `<` + prop + `><![CDATA[` + jsonData[prop] + `]]></` + prop + `>`
    }
    paramXML = paramXML + `</Detail1>`;
    console.log("paramxml 001>>" + paramXML);
    return paramXML;
  }

  /* Sainath T-start 10/04/2020 [for abm related changes]-Start */
  getAbmSelectedterr(terrObj: any) 
  {
    console.log('getAbmSelectedterr terrObj>>' + terrObj);
    this.isAllSelected = false;
    console.log('getAbmSelectedterr terrObj>>' + JSON.stringify(terrObj));
    this.posCodeDescr = terrObj['pos_code_descr'];
    this.stanCode = terrObj['stan_code'];
    this.posCode = terrObj['pos_code'];
    this.isSubordinateMgr = terrObj['is_mgr'];
    this.salesPers = terrObj['sales_pers'];
    this.spName = terrObj['sp_name'];
    this.terrObjStatus = terrObj['planning_status'];
    if (this.isSubordinateMgr && this.posCodeDescr == this.posCodeDescrLogin) 
    {
      this.isAllSelected = true;
    }
    console.log('this.terrObjStatus >>' + this.terrObjStatus + 'this.posCodeDescr >>' + this.posCodeDescr + 'this.posCodeDescrLogin >' + this.posCodeDescrLogin);
    if (this.terrObjStatus != 'S' && this.posCodeDescr != this.posCodeDescrLogin) 
    {
      //window.alert('Plan Not Submitted.');
      this.confirmBox.alert("Error", 'Plan not Submitted.');
      /*if ( this.subordinateData != null && this.fb != null )
      {
        this.selectionListForm = this.fb.group({
          selectionListControl: [this.subordinateData[0]]
        });
        this.isAllSelected = true;
      }*/
    }
    else 
    {
      this.isSubordinateSelected = true;
      this.getStockData();
    }
  }

  setOldValueJson() 
  {
    this.oldJsonValues['pos_code_descr'] = this.posCodeDescr;
    this.oldJsonValues['stan_code'] = this.stanCode;
    this.oldJsonValues['pos_code'] = this.posCode;
    this.oldJsonValues['sales_pers'] = this.salesPers;
    this.oldJsonValues['sp_name'] = this.spName;//prd_code
  }
  //Sainath T. on 08-04-2020-End

  //Added by Pooja S. on 10-04-2020[for abm related changes] -Start
  sentBackSellsPlan(data:any, action?:any) 
  {
    console.log('sentBackSellsPlan Called For Sales Planning.................', this.action);
    var jsonData = {
      'stan_code': this.stanCode,
      'pos_code': this.posCode,
      'sales_pers': this.salesPers,
      'sales_pers_name': this.spName,
      'prd_code': this.prdCode,
      'descr': this.prdCodeDescr,
      'flag': this.action
    }

    var requestJsonData = {
      'headerFormData': jsonData,
      'detailFormData': data
    }
    this._stockSellService.setLoading(true);
    console.log('requestJsonData....................', requestJsonData);
    this._stockSellService.onSentBackSellPlanning(requestJsonData).subscribe(
      data => {
        if (data) 
        {
          // console.log('onSentBackSellPlanning Response data  ....  ',data);
          this._stockSellService.setLoading(false);
          //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ]
          var tranId = '', descr = '', trace = '', errorMsg = '',message='';
          var successMsg:any = {};
          //Commented by Sainath T. for ang9
          //this.jsonResp = (<any>data)._body;
          // this.jsonResp = JSON.parse(this.jsonResp);
          this.jsonResp = data;

          // console.log('Sell Planning   ',this.jsonResp,this.jsonResp.length,this.jsonResp[0],this.jsonResp[0]['tran_id']);
          for (var i = 0; i < this.jsonResp.length; i++) 
          {
            if (this.jsonResp[i]["tran_id"] && this.jsonResp[i]["tran_id"] != '') 
            {
              tranId = this.jsonResp[i]["tran_id"];
            }
            if (this.jsonResp[i]["success_msg"] && this.jsonResp[i]["success_msg"] != '') 
            {
              successMsg = this.jsonResp[i]["success_msg"];
            }
            if (this.jsonResp[i]["subordinate_data"] && this.jsonResp[i]["subordinate_data"] != '') 
            {
              this.subordinateData = this.jsonResp[i]["subordinate_data"];
              if (this.subordinateData[0]["planning_status"] == 'S') 
              {
                this.removeSubmit = true;
              }
              else 
              {
                this.removeSubmit = false;
              }
              this.statusFlag = this.jsonResp[i]["status_flag"];
            }
            if (this.jsonResp[i]["trace"] && this.jsonResp[i]["trace"] != '') 
            {
              trace = this.jsonResp[i]["trace"];
            }
            if (this.jsonResp[i]["description"] && this.jsonResp[i]["description"] != '') 
            {
              errorMsg = this.jsonResp[i]["description"];
            }
            //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ] Start
            if (this.jsonResp[i]["message"] && this.jsonResp[i]["message"] != '') 
            {
              message = this.jsonResp[i]["message"];
            }
            //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ] End
            console.log('Sell Planning errorMsg  ', errorMsg + "trace>>>>>" + trace);
          }
          descr = successMsg['description'];
          console.log('Sell Planning Desc  ', descr);
          if ((tranId || action == "send_back") && descr != 'undefined') 
          {
            var validDesc = this._stockSellService.getValidPopupMsg("","","",descr);
            this.confirmBox.alert("Success", validDesc).subscribe((resp:any) => {
              console.log('warningg response:' + resp);
              if (resp) 
              {
                descr = '';
                this.action = "reset";
                console.log('Sell Planning Desc posCode ', this.posCode + " posCodeLogin >>" + this.posCodeLogin);
                if (this.posCode == this.posCodeLogin) 
                {
                  this.process = true;
                }
                else 
                {
                  this.posCode = this.posCodeLogin;
                  this.stanCode = this.stanCodeLogin;
                  this.posCodeDescr = this.posCodeDescrLogin;
                  this.salesPers = this.salesPersLogin;
                  this.isSubordinateSelected = false;
                  this.isLoadDefault = true;
                  this.getStockData();
                }
                //Added by Saianth T. on 23/04/2020
                this.selectionListForm = this.fb.group({
                  selectionListControl: [this.subordinateData[0]]
                });
              }
            });
          }
          else 
          {
            //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ]
            var errMsg = this._stockSellService.getValidPopupMsg("E",message,errorMsg);
            this.confirmBox.alert("Error",errMsg);
          }
        }
      }
    );
  }
  //Added by Pooja S. on 10-04-2020[for abm related changes] -End

  //Added by Sainath T. on 23/04/2020
  compareFn(c1: any, c2: any): boolean 
  {
    return c1 && c2 ? c1.pos_code === c2.pos_code : c1 === c2;
  }

  public getServiceData(data:any) 
  {
    var jsonData =
    {
      'pos_code': this.posCode,
      'stan_code': this.stanCode,
      'sales_pers': this.salesPers,
      'prd_code': this.prdCode,
      'force_save': this.forceSave,
      'is_mgr': this.isLoginUserMgr
      //'level_no' : this.levelNo
    }
    //Commented by Sainath T. for ang9
    // this.validationData = data = JSON.parse((<any>data)._body);
    this.validationData = data;

    console.log('getSellsPlanDetails resp   ', this.validationData);
    //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ]
    var trace, errorMsg, type, message;    
    try 
    {
      this.warnCnt = 0;
      for (var i = 0; i < this.validationData.length; i++) 
      {
        //console.log('Loop  '+i+'  ');
        if (this.validationData[i]["trace"] && this.validationData[i]["trace"] != '') 
        {
          trace = this.validationData[i]["trace"];
        }
        if (this.validationData[i]["description"] && this.validationData[i]["description"] != '') 
        {
          errorMsg = this.validationData[i]["description"];
        }
        //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ] Start
        if (this.validationData[i]["message"] && this.validationData[i]["message"] != '') 
        {
          message = this.validationData[i]["message"];
        }
        //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ] End
        if (this.validationData[i]["type"] && this.validationData[i]["type"] != '') 
        {
          type = this.validationData[i]["type"];
          if (type == "E" || type == "X") 
          {
            this.cnt++;
          }
          else if (type == "W") 
          {
            this.warnCnt++;
          }
        }
      }
      //console.log('this.warnCnt     ',this.warnCnt,this.cnt);
      if (this.warnCnt > 0) 
      {
        this._stockSellService.setLoading(false);
        //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ]
        var errMsg = this._stockSellService.getValidPopupMsg("W",message,errorMsg);
         this.confirmBox.confirm("confirm",errMsg).subscribe((resp:any) => {
          console.log('warningg response:' + resp);
          if (resp == "YES") 
          {
            this._stockSellService.setLoading(true);
            this.forceSave = "Y";
            jsonData['force_save'] = this.forceSave;
            this._stockSellService.getSellsPlanDetails(jsonData).subscribe(
              data => {
                if (data) 
                {
                  this.getServiceData(data);
                  //data = JSON.parse((<any>data)._body) ;
                  //this.sellsPlanDetail(data);
                }
              });
          }
          else if (resp == "NO") 
          {
            this._stockSellService.setLoading(false);
          }
        });
      }
      else if (this.cnt > 0) 
      {
        // alert(trace  + '\n'+ errorMsg);
        this._stockSellService.setLoading(false);
        //changed and Added by Pooja S on 20-JUNE-2020 [Negative stock validation in Sell In Out ]
        var errMsg = this._stockSellService.getValidPopupMsg("E",message,errorMsg);
        this.confirmBox.alert("Error", errMsg );
      }
      else 
      {
        this.sellsPlanDetail(data);
      }
    }
    catch (error) 
    {
      console.log("Failed................", error);
    }
  }
//Added by sainath t. on 29-09-2020-start
   ngAfterViewInit()
  {
    var mobileContents = document.getElementById('MobileContents');
        
    if( mobileContents ) //window.innerHeight < window.innerWidth for landscape  ---&& bbTableContainer 
    {
        let contentHeight =  document.getElementById('MobileContents')!.offsetHeight - 129;
        document.getElementById('MobileContents')!.style.height = contentHeight +'px';//105
    }
  }
//Added by sainath t. on 29-09-2020-end

}
