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 { Bu2Model, MyBu2Model } from 'src/app/shared/model/bu2.model';
import { Bu3Model, MyBu3Model } from 'src/app/shared/model/bu3.model';
import { Bu2Service } from 'src/app/shared/services/bu2.service';
import { Bu3Service } from 'src/app/shared/services/bu3.service';
import { FileService } from 'src/app/shared/services/file.service';
import Swal from 'sweetalert2';
interface table {
  currentPage: number,
  page: number[],
  search: string,
  pageSize: number
}
@Component({
  selector: 'app-section-registration',
  templateUrl: './section-registration.component.html',
  styleUrls: ['./section-registration.component.scss']
})
export class SectionRegistrationComponent implements OnInit {
  bu3: { loading: boolean, select: Bu3Model, dataList: Bu3Model[] } = { loading: false, select: new MyBu3Model(), dataList: [] }
  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';

  bu2List: Bu2Model[] = []
  bu2: Bu2Model = new MyBu2Model()
  bu2Modal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }
  currentModal: 'add' | 'edit' | 'delete' = "add"


  columns: ColumnModel[] = [{
    field: "bu3id",
    headerText: "SectionCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "SectionDescThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "SectionDescEng",
    type: "string"
  }]
  searchSettings = {
    fields: ['bu3id', 'tdesc', 'edesc'],
    operator: 'contains',
    ignoreCase: false
  };
  search = ''
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
  @ViewChild("sectionRegistrationModal") sectionRegistrationModal: any;
  @ViewChild("sectionRegistrationModalBu2") sectionRegistrationModalBu2: any;
  dialogRef: any
  dialogRefBu2: any
  constructor(private bu3Service: Bu3Service,
    private bu2Service: Bu2Service,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private dialog: MatDialog
  ) { }

  ngOnInit(): void {
    this.getBu3List()
    this.getBu2List()
  }
  openDialog() {
    this.dialogRef = this.dialog.open(this.sectionRegistrationModal, {
      width: '500px',
    })
  }
  openDialogBu2() {
    this.dialogRefBu2 = this.dialog.open(this.sectionRegistrationModalBu2, {
      width: '800px',
    })
  }
  closeDialog() {
    this.dialogRef.close()
  }
  closeDialogBu2() {
    this.dialogRefBu2.close()
  }

  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.bu3.loading = true
    this.fileService.uploadExcel(formData, 'mbu3').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getBu3List()
        } else {
          this.showAlert(response.message, 'error')
          this.bu3.loading = false
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.bu3.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')
      }
    })

  }

  getBu3List() {
    this.bu3.loading = true
    this.selectedItems.data.clear()
    this.bu3Service.getList().subscribe({
      next: response => {
        this.bu3.dataList = response.map(x => {
          this.selectedItems.data.set(x.bu3id, false)
          return new MyBu3Model(x)
        })
        this.selectedItems.key = 'bu3id'
        this.selectedItems.count = 0
        this.bu3.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.bu3.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  selectBu3(bu3?: Bu3Model) {
    if (bu3) {
      this.bu3.select = new MyBu3Model(bu3)
    } else if (this.currentModal == 'add') {
      this.bu3.select = new MyBu3Model()
    } else if (this.currentModal == 'edit') {
      this.bu3.select = new MyBu3Model({ bu3id: this.bu3.select.bu3id })
    }
    this.selectBu2()
    if (this.bu3.select.parent) {
      this.bu2Service.getById(this.bu3.select.parent).subscribe(response => {
        this.bu2 = new MyBu2Model(response)
        this.cdr.detectChanges()
      })
    }
  }

  addBu3() {
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'บันทึกข้อมูล',
    }).then((result) => {
      if (result.isConfirmed) {
        this.bu3.loading = true
        this.bu3Service.post({ ...this.bu3.select, parent: this.bu2.bu2id }).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getBu3List()
              this.closeDialog()
            } else {
              this.showAlert(response.message, 'error')
              this.bu3.loading = false
              this.closeDialog()
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.bu3.loading = false
            this.closeDialog()
          }
        })
      }
    })
  }
  deleteBu3() {
    if (this.numSelectItem() == 0) {
      this.showAlert('กรุณาเลือกข้อมูลที่จะลบ', 'error')
      return
    }
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการลบข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'ลบข้อมูล',
    }).then((result) => {
      if (result.isConfirmed) {
        this.bu3.loading = true
        const selectedKeys = Array.from(this.selectedItems.data.keys());
        const body = this.bu3.dataList.filter(x => selectedKeys.includes(x.bu3id) && this.selectedItems.data.get(x.bu3id)).map(x => new MyBu3Model(x))
        this.bu3Service.delete(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getBu3List()
            } else {
              this.showAlert(response.message, 'error')
              this.bu3.loading = false
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.bu3.loading = false
          }
        })
      }
    })
  }

  getBu2List() {
    this.bu2Service.getList().subscribe(response => {
      this.bu2List = response.map(x => new MyBu2Model(x))
      this.onBu2ModalSearchChange()
    })
  }
  onBu2ModalSearchChange() {
    this.bu2Modal.currentPage = 1
    this.bu2Modal.page = Array.from({ length: Math.ceil(this.filterBu2Modal().length / 10) }, (_, i) => i + 1);
  }
  bu2idChange() {
    const bu2 = this.bu2List.find(x => x.bu2id == this.bu2.bu2id)
    this.selectBu2(bu2 || new MyBu2Model({ bu2id: this.bu2.bu2id }))
  }
  filterBu2Modal() {
    return this.bu2List.filter(x => x.bu2id.toLowerCase().includes(this.bu2Modal.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.bu2Modal.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.bu2Modal.search.toLowerCase()))
  }
  selectBu2(bu2?: Bu2Model) {
    this.bu2 = new MyBu2Model(bu2)
  }

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

  checkPrimary() {
    return this.bu3.dataList.find(x => x.bu3id == this.bu3.select.bu3id)
  }


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

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

}

