import { ChangeDetectorRef, Component } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { CompanyModel, MyCompanyModel } from 'src/app/shared/model/company.model';
import { CompanyService } from 'src/app/shared/services/company.service';
import { FileService } from 'src/app/shared/services/file.service';
export interface DataModel {
  code: string
  tdesc: string
  edesc: string
  address: string
  contact: string
}
@Component({
  selector: 'app-company-registration-page',
  templateUrl: './company-registration-page.component.html',
  styleUrls: ['./company-registration-page.component.scss']
})
export class CompanyRegistrationPageComponent {
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  search = ""
  modalStatus = 'add'
  dataList: { check: boolean, data: DataModel }[] = []
  dataLoading = false
  dataSelect: DataModel = { code: "", tdesc: "", edesc: "", address: "", contact: "" }

  numDataListChecked = 0
  isDataListChecked = false
  isDataListCheckedAll = false

  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';
  constructor(private toastr: ToastrService,
    private companyService: CompanyService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService) { }
  ngOnInit(): void {
    this.getCompanyList()
  }

  getCompanyList() {
    this.dataLoading = true
    this.companyService.getList().subscribe({
      next: response => {
        this.dataList = response.map(x => ({ check: false, data: { code: x.companyId, tdesc: x.tdesc, edesc: x.edesc, address: x.addressText, contact: x.contactText } }))
        this.dataLoading = false
        this.isDataListCheckedAll = false
        this.dataListCheckAll()
        this.searchChange()
        this.cdr.detectChanges()
      }, error: error => {
        this.dataLoading = false
        this.cdr.detectChanges()
      }
    })
  }

  searchChange() {
    this.currentPage = 1
    this.page = Array.from({ length: Math.ceil(this.dataListFilter().length / 10) }, (_, i) => i + 1);
    this.dataListCheck()
  }
  dataListFilter() {
    return this.dataList.filter(x => {
      const data = x.data
      const match = data.code.toLowerCase().includes(this.search.toLowerCase()) || data.tdesc.toLowerCase().includes(this.search.toLowerCase()) || data.edesc.toLowerCase().includes(this.search.toLowerCase());
      return match;
    });
  }
  setData(data?: DataModel) {
    this.dataSelect = JSON.parse(JSON.stringify(data || { code: "", tdesc: "", edesc: "", address: "", contact: "" }));
  }

  addCompany() {
    const body = new MyCompanyModel({ companyId: this.dataSelect.code, tdesc: this.dataSelect.tdesc, edesc: this.dataSelect.edesc, addressText: this.dataSelect.address, contactText: this.dataSelect.contact })
    this.dataLoading = true
    this.companyService.post(body).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getCompanyList()
        } else {
          this.showAlert(response.message, 'error')
          this.dataLoading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.cdr.detectChanges()
        this.dataLoading = false
      }
    })
  }
  deleteCompany() {
    let body: CompanyModel | CompanyModel[] = []
    if (this.dataSelect.code) {
      body = new MyCompanyModel({ companyId: this.dataSelect.code, tdesc: this.dataSelect.tdesc, edesc: this.dataSelect.edesc, addressText: this.dataSelect.address, contactText: this.dataSelect.contact })
    } else {
      body = this.dataList.filter(x => x.check && x.data.code != '100').map(x => new MyCompanyModel({ companyId: x.data.code, tdesc: x.data.tdesc, edesc: x.data.edesc, addressText: x.data.address, contactText: x.data.contact }))
    }
    this.dataLoading = true
    this.companyService.delete(body).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getCompanyList()
        } else {
          this.showAlert(response.message, 'error')
          this.dataLoading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.cdr.detectChanges()
        this.dataLoading = false
      }
    })
  }

  showAlert(text: string, type: 'success' | 'error') {
    this.toastr[type](text, 'แจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    });
  }

  dataListCheckAll() {
    const selectAll = this.isDataListCheckedAll;
    this.dataList.filter(x => {
      const data = x.data
      const match = data.code.toLowerCase().includes(this.search.toLowerCase()) || data.tdesc.toLowerCase().includes(this.search.toLowerCase()) || data.edesc.toLowerCase().includes(this.search.toLowerCase());
      return match;
    }).forEach(x => x.check = selectAll);
    this.dataListCheck();
  }
  dataListCheck() {
    const dataCheck = this.dataListFilter();
    this.isDataListCheckedAll = dataCheck.length ? dataCheck.filter(x => x.data.code != '100').every(x => x.check) : false;
    if (dataCheck.length == 1 && dataCheck.find(x => x.data.code == '100')) {
      this.isDataListCheckedAll = false
    }
    this.numDataListChecked = this.dataList.filter(x => x.check).length;
    if (this.dataList.some(x => x.check && x.data.code == '100')) {
      this.numDataListChecked = this.numDataListChecked - 1
    }
    this.isDataListChecked = Boolean(this.numDataListChecked)
  }

  onFileSelected(event: any) {
    this.selectedFile = event.target.files.length > 0 ? event.target.files[0] : null;
    this.selectedFileName = this.selectedFile?.name || "กรุณาเลือกไฟล์"
  }
  uploadFile() {
    if (!this.selectedFile) {
      alert('กรุณาเลือกไฟล์ก่อนอัปโหลด')
      return
    }
    const formData = new FormData();
    formData.append('file', this.selectedFile);
    this.dataLoading = true
    this.fileService.uploadExcel(formData, 'mcompany').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getCompanyList()
        } else {
          this.showAlert(response.message, 'error')
          this.dataLoading = false
          this.cdr.detectChanges();
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.dataLoading = false
        this.cdr.detectChanges();
      }
    })
  }
  downloadFile() {
    const fileName = 'IMPORT_COMPANY.xlsx'
    this.fileService.downloadTemplate(fileName).subscribe({
      next: response => {
        const url = window.URL.createObjectURL(response);
        const a = document.createElement("a");
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      }, error: error => {
        this.showAlert(error.message, 'error')
      }
    })
  }
  clearData() {
    if (this.modalStatus == 'add') {
      this.setData()
    } else {
      this.setData({ code: this.dataSelect.code, tdesc: "", edesc: "", address: "", contact: "" })
    }
  }
}