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

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


  bu5List: Bu5Model[] = []
  bu5: Bu5Model = new MyBu5Model()
  bu5Modal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }
  currentModal: 'add' | 'edit' | 'detele' = "add"

  columns: ColumnModel[] = [{
    field: "bu6id",
    headerText: "SubSection3Code",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "SubSection3DescThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "SubSection3DescEng",
    type: "string"
  }]
  searchSettings = {
    fields: ['bu6id', '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("subDepartmentThreeModal") subDepartmentThreeModal: any;
  @ViewChild("subDepartmentThreeModalBu5") subDepartmentThreeModalBu5: any;
  dialogRef: any
  dialogRefBu5: any
  constructor(private bu6Service: Bu6Service,
    private bu5Service: Bu5Service,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private dialog: MatDialog
  ) { }
  ngOnInit(): void {
    this.getBu6List()
    this.getBu5List()
  }

  openDialog() {
    this.dialogRef = this.dialog.open(this.subDepartmentThreeModal, {
      width: '500px',
    })
  }
  openDialogBu5() {
    this.dialogRefBu5 = this.dialog.open(this.subDepartmentThreeModalBu5, {
      width: '800px',
    })
  }
  closeDialog() {
    this.dialogRef.close()
  }
  closeDialogBu5() {
    this.dialogRefBu5.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.bu6.loading = true
    this.fileService.uploadExcel(formData, 'mbu6').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getBu6List()
        } else {
          this.showAlert(response.message, 'error')
          this.bu6.loading = false
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.bu6.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')
      }
    })

  }

  getBu6List() {
    this.bu6.loading = true
    this.selectedItems.data.clear()
    this.bu6Service.getList().subscribe({
      next: response => {
        this.bu6.dataList = response.map(x => {
          this.selectedItems.data.set(x.bu6id, false)
          return new MyBu6Model(x)
        })
        this.selectedItems.key = 'bu6id'
        this.selectedItems.count = 0
        this.bu6.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.bu6.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  selectBu6(bu6?: Bu6Model) {
    if (bu6) {
      this.bu6.select = new MyBu6Model(bu6)
    } else if (this.currentModal == 'add') {
      this.bu6.select = new MyBu6Model()
    } else if (this.currentModal == 'edit') {
      this.bu6.select = new MyBu6Model({ bu6id: this.bu6.select.bu6id })
    }
    this.selectBu5()
    if (this.bu6.select.parent) {
      this.bu5Service.getById(this.bu6.select.parent).subscribe(response => {
        this.bu5 = new MyBu5Model(response)
        this.cdr.detectChanges()
      })
    }
  }

  addBu6() {
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'ยืนยัน',
    }).then((result) => {
      if (result.isConfirmed) {
        this.bu6.loading = true
        this.bu6Service.post({ ...this.bu6.select, parent: this.bu5.bu5id }).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getBu6List()
              this.closeDialog()
            } else {
              this.showAlert(response.message, 'error')
              this.bu6.loading = false
              this.closeDialog()
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.bu6.loading = false
            this.closeDialog()
          }
        })
      }
    })


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

  getBu5List() {
    this.bu5Service.getList().subscribe(response => {
      this.bu5List = response.map(x => new MyBu5Model(x))
      this.onBu5ModalSearchChange()
    })
  }
  onBu5ModalSearchChange() {
    this.bu5Modal.currentPage = 1
    this.bu5Modal.page = Array.from({ length: Math.ceil(this.filterBu5Modal().length / 10) }, (_, i) => i + 1);
  }
  bu5idChange() {
    const bu5 = this.bu5List.find(x => x.bu5id == this.bu5.bu5id)
    this.selectBu5(bu5 || new MyBu5Model({ bu5id: this.bu5.bu5id }))
  }
  filterBu5Modal() {
    return this.bu5List.filter(x => x.bu5id.toLowerCase().includes(this.bu5Modal.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.bu5Modal.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.bu5Modal.search.toLowerCase()))
  }
  selectBu5(bu5?: Bu5Model) {
    this.bu5 = new MyBu5Model(bu5)
  }

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

  checkPrimary() {
    return this.bu6.dataList.find(x => x.bu6id == this.bu6.select.bu6id)
  }

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

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


