import { Component, OnInit } from '@angular/core';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { ItemForSaleService } from '../services/service.service';
import { deepCopy } from '@angular-devkit/core/src/utils/object';
import * as moment from 'moment';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { AuthenticationService } from 'src/app/hmg-common/services/authentication/authentication.service';

@Component({
  selector: 'app-items',
  templateUrl: './items.component.html',
  styleUrls: ['./items.component.scss'],
})
export class ItemsComponent implements OnInit {
  segment: any = '1';
  items: any;
  categories: any = [];
  direction: string;
  activeClass: any;
  pageNo: number = 1;
  tempSearch: any = [];
  itemsByEmployee: any = [];
  allCategory = {
    categoryID: 0,
    content: '<svg xmlns="http://www.w3.org/2000/svg" width="33.925" height="25.841" viewBox="0 0 33.925 25.841"><g id="More_Select" data-name="More Select"><path d="m30 1h-24a1 1 0 0 0 -1 1v1h21a3 3 0 0 1 3 3v21h1a1 1 0 0 0 1-1v-24a1 1 0 0 0 -1-1z"/><path d="m26 5h-24a1 1 0 0 0 -1 1v24a1 1 0 0 0 1 1h24a1 1 0 0 0 1-1v-24a1 1 0 0 0 -1-1zm-4.747 9.344-8.728 8.726a1 1 0 0 1 -1.414 0l-4.364-4.363a1 1 0 0 1 1.414-1.414l3.657 3.656 8.021-8.019a1 1 0 0 1 1.414 1.414z"/></g></svg>',
    isActive: true,
    title: "All",
    title_Ar: "الجميع",
  }
  constructor(public ts: TranslatorService, public route: ActivatedRoute, private sanitizer: DomSanitizer, public cs: CommonService, private itemService: ItemForSaleService, private authService: AuthenticationService) {
    this.route
      .params.subscribe(val => {
        setTimeout(() => {
          this.cs.startLoading();
          var selectedFilter = this.cs.sharedService.getSharedData(ItemForSaleService.selected_filters);
          if (selectedFilter) {
            this.selectCategory(selectedFilter);
          }
          else {
            this.getItemsCategories();
            this.getItemsByEmployee();
          }


        }, 100);
      });

  }


  ngOnInit() {
    this.direction = TranslatorService.getCurrentDirection();

  }
  getItemsCategories() {

    this.itemService.getCategories({}, () => { }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      this.categories = this.itemService.parser(result);
      this.categories.unshift(this.allCategory);
      this.cs.sharedService.setSharedData(this.categories, ItemForSaleService.CATEGORIES);
    })
    this.itemService.getItems({ pageNo: this.pageNo }, () => { }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      this.items = [];
      this.items = this.itemService.parser(result);
      this.tempSearch = deepCopy(this.items);
      console.log(this.tempSearch);
      this.cs.stopLoading();
    })
  }
  openDetails(selected) {
    this.cs.sharedService.setSharedData(selected, ItemForSaleService.ITEMS_SELECTED);
    this.cs.navigateForward('/itemforsale/items-details');
  }
  segmentChanged(value) {
    this.segment = value.detail.value;
  }
  openSale() {
    this.cs.openCreateitems();
  }
  selectCategory(item) {
    this.cs.startLoading();
    this.activeClass = item.categoryID;
    this.pageNo = 1;
    this.itemService.getItems({ pageNo: this.pageNo, ItgCategoryID: item.categoryID }, () => { }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      this.items = [];
      this.items = this.itemService.parser(result);
      this.tempSearch = deepCopy(this.items);
      this.cs.stopLoading();
    })
  }
  getDotted(temp: string, valueCount: number) {
    temp = this.stripHtml(temp);
    return temp.substring(0, valueCount) + " ...";
  }
  stripHtml(html) {
    var temporalDivElement = document.createElement("div");

    temporalDivElement.innerHTML = html;

    return temporalDivElement.textContent || temporalDivElement.innerText || "";
  }
  loadData(event) {
    this.pageNo = this.pageNo + 1;
    this.itemService.getItems({ pageNo: this.pageNo, categoryID: this.activeClass }, () => { }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      this.items.concat(this.itemService.parser(result));
      this.tempSearch = deepCopy(this.items);
      event.target.complete();

    })
  }
  search(t) {
    if (t === '') {
      this.items = this.tempSearch;
    } else {
      this.items = this.tempSearch.filter((post) => {
        if (this.direction == 'ltr')
          return (post.title.toLowerCase().indexOf(t.toLowerCase()) > -1);
        else
          return (post.title_Ar.indexOf(t) > -1);
      });
    }

  }
  getItemsByEmployee() {

    this.cs.startLoading();
    this.itemService.getItemsByEmployee({}, () => { }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      this.itemsByEmployee = this.itemService.parser(result);

      this.cs.stopLoading();
      console.log(this.itemsByEmployee);
    })
  }

  getDate(date) {
    return moment(date, "YYYY-MM-DD HH:mm:ss").format("DD-MMM-YYYY");
  }

  getImgContent(imgFile): SafeUrl {
    return this.sanitizer.bypassSecurityTrustUrl(imgFile);
  }
  editItems(items) {
    this.cs.sharedService.setSharedData(items, ItemForSaleService.EDIT_ITEMS);
    this.cs.openCreateitems();
  }
  deleteItems(item) {
    var authUser = this.authService.getAuthenticatedRequest();
    this.cs.startLoading();
    var request = new FormData();
    request.append('itemSaleID', item.itemSaleID);
    request.append('isActive', 'false');
    request.append('Channel', authUser.Channel.toString());
    request.append('LogInToken', authUser.LogInTokenID);
    request.append('Token', authUser.TokenID);
    request.append('EmployeeNumber', authUser.P_USER_NAME);
    request.append('MobileNo', authUser.MobileNumber);
    request.append('employeeNumber', authUser.P_USER_NAME);
    this.itemService.updateItemForSale(request, () => { }, this.ts.trPK('general', 'retry')).subscribe((result: any) => {
      if (this.cs.validResponse(result)) {
        this.cs.greenToastPK('itemforsale', 'item-deleted');
        this.getItemsByEmployee();

      }
    })
  }
  openModel() {
    this.cs.filterItemforSale();
  }
}
