import { ChangeDetectorRef, Component, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ColumnModel } from '@syncfusion/ej2-grids';
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';
import Swal from 'sweetalert2';
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 {
  @ViewChild("registrationModal") registrationModal: any;
  pageSize = 10
  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  search = ""
  currentModal: 'add' | 'edit' | 'delete' = 'add'
  dataList: DataModel[] = []
  dataLoading = false
  dataSelect: DataModel = { code: "", tdesc: "", edesc: "", address: "", contact: "" }
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  searchSettings = {
    fields: ['code', 'tdesc', 'edesc'],
    operator: 'contains',
    ignoreCase: false
  };
  columns: ColumnModel[] = [{
    field: "code",
    headerText: "CompanyCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "CompanyDescThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "CompanyDescEng",
    type: "string"
  }]

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

  getCompanyList() {
    this.dataLoading = true
    this.selectedItems.data.clear()
    this.companyService.getList().subscribe({
      next: response => {
        this.dataList = response.map(x => {
          this.selectedItems.data.set(x.companyId, false)
          return { code: x.companyId, tdesc: x.tdesc, edesc: x.edesc, address: x.addressText, contact: x.contactText }
        })
        this.selectedItems.key = 'code'
        this.selectedItems.count = 0
        this.dataLoading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.dataLoading = false
        this.cdr.detectChanges()
      }
    })
  }

  setData(data?: DataModel) {
    this.dataSelect = JSON.parse(JSON.stringify(data || { code: "", tdesc: "", edesc: "", address: "", contact: "" }));
  }

  addCompany() {
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'บันทึกข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        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()
              this.closeDialog();
            } else {
              this.showAlert(response.message, 'error')
              this.dataLoading = false
              this.closeDialog();
              this.cdr.detectChanges()
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.cdr.detectChanges()
            this.closeDialog();
            this.dataLoading = false
          }
        })
      }
    });

  }
  deleteCompany() {
    if (!this.numSelectItem()) {
      this.showAlert('กรุณาเลือกข้อมูลที่ต้องการลบ', 'error')
      return
    }
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการลบข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'ลบข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        const selectedKeys = Array.from(this.selectedItems.data.keys());
        const body = this.dataList.filter(x => x.code != '100').filter(x => selectedKeys.includes(x.code) && this.selectedItems.data.get(x.code)).map(x => new MyCompanyModel({ companyId: x.code, tdesc: x.tdesc, edesc: x.edesc, addressText: x.address, contactText: x.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') {
    Swal.fire({
      title: 'แจ้งเตือน',
      text: text,
      icon: type,
      confirmButtonText: 'ตกลง',
    });
  }


  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.currentModal == 'add') {
      this.setData()
    } else {
      this.setData({ code: this.dataSelect.code, tdesc: "", edesc: "", address: "", contact: "" })
    }
  }

  checkPrimary() {
    return this.dataList.find(x => x.code == this.dataSelect.code)
  }

  openDialog() {
    this.dialogRef = this.dialog.open(this.registrationModal, {
      width: '500px',
      disableClose: false,
    });
  }
  closeDialog() {
    this.dialogRef.close()
  }

  onSelectItemChange(arg: any) {
    this.selectedItems = arg
  }
  numSelectItem() {
    const selectedKeys = Array.from(this.selectedItems.data.keys());
    const num = this.dataList.filter(x => selectedKeys.includes(x.code) && this.selectedItems.data.get(x.code)).length
    return num
  }
}
