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 { Bu6Model, MyBu6Model } from 'src/app/shared/model/bu6.model';
import { Bu7Model, MyBu7Model } from 'src/app/shared/model/bu7.model';
import { Bu6Service } from 'src/app/shared/services/bu6.service';
import { Bu7Service } from 'src/app/shared/services/bu7.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-sub-department-four',
  templateUrl: './sub-department-four.component.html',
  styleUrls: ['./sub-department-four.component.scss']
})
export class SubDepartmentFourComponent implements OnInit {
  bu7: { loading: boolean, select: Bu7Model, dataList: Bu7Model[] } = { loading: false, select: new MyBu7Model(), dataList: [] }

  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';

  bu6List: Bu6Model[] = []
  bu6: Bu6Model = new MyBu6Model()
  bu6Modal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }
  currentModal: 'add' | 'edit' | 'delete' = "add"

  columns: ColumnModel[] = [{
    field: "bu7id",
    headerText: "รหัสส่วนย่อย 4",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "รายละเอียดส่วนย่อย4 (ไทย)",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "รายละเอียดส่วนย่อย4 (อังกฤษ)",
    type: "string"
  }]
  searchSettings = {
    fields: ['bu7id', '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("subDepartmentFourModal") subDepartmentFourModal: any;
  @ViewChild("subDepartmentFourModalBu6") subDepartmentFourModalBu6: any;
  dialogRef: any
  dialogRefBu6: any
  constructor(private bu7Service: Bu7Service,
    private bu6Service: Bu6Service,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private dialog: MatDialog
  ) { }
  ngOnInit(): void {
    this.getBu7List()
    this.getBu6List()
  }

  openDialog() {
    this.dialogRef = this.dialog.open(this.subDepartmentFourModal, {
      width: '500px',
    })
  }
  openDialogBu6() {
    this.dialogRefBu6 = this.dialog.open(this.subDepartmentFourModalBu6, {
      width: '500px',
    })
  }
  closeDialog() {
    this.dialogRef.close()
  }
  closeDialogBu6() {
    this.dialogRefBu6.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.bu7.loading = true
    this.fileService.uploadExcel(formData, 'mbu7').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getBu7List()
        } else {
          this.showAlert(response.message, 'error')
          this.bu7.loading = false
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.bu7.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')
      }
    })

  }

  getBu7List() {
    this.bu7.loading = true
    this.bu7Service.getList().subscribe({
      next: response => {
        this.bu7.dataList = response.map(x => {
          this.selectedItems.data.set(x.bu7id, false)
          return new MyBu7Model(x)
        })
        this.selectedItems.key = 'bu7id'
        this.selectedItems.count = 0
        this.bu7.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.bu7.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  selectBu7(bu7?: Bu7Model) {
    if (bu7) {
      this.bu7.select = new MyBu7Model(bu7)
    } else if (this.currentModal == 'add') {
      this.bu7.select = new MyBu7Model()
    } else if (this.currentModal == 'edit') {
      this.bu7.select = new MyBu7Model({ bu7id: this.bu7.select.bu7id })
    }
    this.selectBu6()
    if (this.bu7.select.parent) {
      this.bu6Service.getById(this.bu7.select.parent).subscribe(response => {
        this.bu6 = new MyBu6Model(response)
        this.cdr.detectChanges()
      })
    }
  }

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

  getBu6List() {
    this.bu6Service.getList().subscribe(response => {
      this.bu6List = response.map(x => new MyBu6Model(x))
      this.onBu6ModalSearchChange()
    })
  }
  onBu6ModalSearchChange() {
    this.bu6Modal.currentPage = 1
    this.bu6Modal.page = Array.from({ length: Math.ceil(this.filterBu6Modal().length / 10) }, (_, i) => i + 1);
  }
  bu6idChange() {
    const bu6 = this.bu6List.find(x => x.bu6id == this.bu6.bu6id)
    this.selectBu6(bu6 || new MyBu6Model({ bu6id: this.bu6.bu6id }))
  }
  filterBu6Modal() {
    return this.bu6List.filter(x => x.bu6id.toLowerCase().includes(this.bu6Modal.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.bu6Modal.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.bu6Modal.search.toLowerCase()))
  }
  selectBu6(bu6?: Bu6Model) {
    this.bu6 = new MyBu6Model(bu6 || {})
  }

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



  checkPrimary() {
    return this.bu7.dataList.find(x => x.bu7id == this.bu7.select.bu7id)
  }

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

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


