import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, ViewChild, } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { ToastrService } from 'ngx-toastr';
import { Bu1Model, MyBu1Model } from 'src/app/shared/model/bu1.model';
import { Bu1Service } from 'src/app/shared/services/bu1.service';
import { FileService } from 'src/app/shared/services/file.service';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-department-register',
  templateUrl: './department-register.component.html',
  styleUrls: ['./department-register.component.scss']
})
export class DepartmentRegisterComponent implements OnInit {
  currentPage = 1
  pageSize = 10
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  search = ""
  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  currentModal: 'add' | 'edit' | 'delete' = "add"
  bu1: { loading: boolean, select: Bu1Model, dataList: Bu1Model[] } = { loading: false, select: new MyBu1Model(), dataList: [] }
  columns: ColumnModel[] = [{
    field: "bu1id",
    headerText: "CompanyCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "CompanyDescThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "CompanyDescEng",
    type: "string"
  }]
  searchSettings = {
    fields: ['bu1id', 'tdesc', 'edesc'],
    operator: 'contains',
    ignoreCase: false
  };
  @ViewChild("departmentRegisterModal") departmentRegisterModal: any;
  dialogRef: any
  constructor(private bu1Service: Bu1Service,
    private dialog: MatDialog,
    private cdr: ChangeDetectorRef,
    private fileService: FileService
  ) { }
  ngOnInit(): void {
    this.getBu1List()
  }
  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.bu1.loading = true
    this.fileService.uploadExcel(formData, 'mbu1').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getBu1List()
        } else {
          this.showAlert(response.message, 'error')
          this.bu1.loading = false
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.bu1.loading = false
      }
    })
  }

  downloadFile() {
    const fileName = 'IMPORT_BU.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')
      }
    })
  }

  getBu1List() {
    this.bu1.loading = true
    this.selectedItems.data.clear()
    this.bu1Service.getList().subscribe({
      next: response => {
        this.bu1.dataList = response.map(x => {
          this.selectedItems.data.set(x.bu1id, false)
          return new MyBu1Model(x)
        })
        this.selectedItems.key = 'bu1id'
        this.selectedItems.count = 0
        this.bu1.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.bu1.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  selectBu1(bu1?: Bu1Model) {
    if (bu1) {
      this.bu1.select = new MyBu1Model(bu1)
    } else if (this.currentModal == 'add') {
      this.bu1.select = new MyBu1Model()
    } else if (this.currentModal == 'edit') {
      this.bu1.select = new MyBu1Model({ bu1id: this.bu1.select.bu1id })
    }
  }

  showAlert(text: string, type: 'success' | 'error') {
    Swal.fire({
      title: 'แจ้งเตือน',
      text: text,
      icon: type,
      confirmButtonText: 'ตกลง',
    });
  }

  addBu1() {
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'บันทึกข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        this.bu1.loading = true
        this.bu1Service.post(this.bu1.select).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getBu1List()
              this.closeDialog()
            } else {
              this.showAlert(response.message, 'error')
              this.bu1.loading = false
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.bu1.loading = false
          }
        })
      }
    })
  }
  deleteBu1() {
    if (!this.numSelectItem()) {
      this.showAlert('กรุณาเลือกข้อมูลที่ต้องการลบ', 'error')
      return
    }
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการลบข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'ลบข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        this.bu1.loading = true
        const selectedKeys = Array.from(this.selectedItems.data.keys());
        const body = this.bu1.dataList.filter(x => selectedKeys.includes(x.bu1id) && this.selectedItems.data.get(x.bu1id)).map(x => new MyBu1Model(x))
        this.bu1Service.delete(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getBu1List()
              this.closeDialog()
            } else {
              this.showAlert(response.message, 'error')
              this.bu1.loading = false
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.bu1.loading = false
          }
        })
      }
    });
  }

  checkPrimary() {
    return this.bu1.dataList.find(x => x.bu1id == this.bu1.select.bu1id)
  }

  onSelectItemChange(arg: any) {
    this.selectedItems = arg
  }

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

  numSelectItem() {
    const selectedKeys = Array.from(this.selectedItems.data.keys());
    const num = this.bu1.dataList.filter(x => selectedKeys.includes(x.bu1id) && this.selectedItems.data.get(x.bu1id)).length
    return num
  }
}