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

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

  bu4List: Bu4Model[] = []
  bu4: Bu4Model = new MyBu4Model()
  bu4Modal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }
  currentModal: 'add' | 'edit' | 'delete' = "add"

  columns: ColumnModel[] = [{
    field: "bu5id",
     headerText: "SubSection2Code",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "SubSection2DescThai",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "SubSection2DescEng",
    type: "string"
  }]
  searchSettings = {
    fields: ['bu5id', '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("subDepartmentTwoModal") subDepartmentTwoModal: any;
  @ViewChild("subDepartmentTwoModalBu4") subDepartmentTwoModalBu4: any;
  dialogRef: any
  dialogRefBu4: any
  constructor(private bu5Service: Bu5Service,
    private bu4Service: Bu4Service,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private dialog: MatDialog
  ) { }
  ngOnInit(): void {
    this.getBu5List()
    this.getBu4List()
  }

  openDialog() {
    this.dialogRef = this.dialog.open(this.subDepartmentTwoModal, {
      width: '500px',
    })
  }
  openDialogBu4() {
    this.dialogRefBu4 = this.dialog.open(this.subDepartmentTwoModalBu4, {
      width: '800px',
    })
  }
  closeDialog() {
    this.dialogRef.close()
  }
  closeDialogBu4() {
    this.dialogRefBu4.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.bu5.loading = true
    this.fileService.uploadExcel(formData, 'mbu5').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getBu5List()
        } else {
          this.showAlert(response.message, 'error')
          this.bu5.loading = false
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.bu5.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')
      }
    })

  }

  getBu5List() {
    this.bu5.loading = true
    this.selectedItems.data.clear()
    this.bu5Service.getList().subscribe({
      next: response => {
        this.bu5.dataList = response.map(x => {
          this.selectedItems.data.set(x.bu5id, false)
          return new MyBu5Model(x)
        })
        this.selectedItems.key = 'bu5id'
        this.selectedItems.count = 0
        this.bu5.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.bu5.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  selectBu5(bu5?: Bu5Model) {
    if (bu5) {
      this.bu5.select = new MyBu5Model(bu5)
    } else if (this.currentModal == 'add') {
      this.bu5.select = new MyBu5Model()
    } else if (this.currentModal == 'edit') {
      this.bu5.select = new MyBu5Model({ bu5id: this.bu5.select.bu5id })
    }
    this.selectBu4()
    if (this.bu5.select.parent) {
      this.bu4Service.getById(this.bu5.select.parent).subscribe(response => {
        this.bu4 = new MyBu4Model(response)
        this.cdr.detectChanges()
      })
    }
  }

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

  getBu4List() {
    this.bu4Service.getList().subscribe(response => {
      this.bu4List = response.map(x => new MyBu4Model(x))
      this.onBu4ModalSearchChange()
    })
  }
  onBu4ModalSearchChange() {
    this.bu4Modal.currentPage = 1
    this.bu4Modal.page = Array.from({ length: Math.ceil(this.filterBu4Modal().length / 10) }, (_, i) => i + 1);
  }
  bu4idChange() {
    const bu4 = this.bu4List.find(x => x.bu4id == this.bu4.bu4id)
    this.selectBu4(bu4 || new MyBu4Model({ bu4id: this.bu4.bu4id }))
  }
  filterBu4Modal() {
    return this.bu4List.filter(x => x.bu4id.toLowerCase().includes(this.bu4Modal.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.bu4Modal.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.bu4Modal.search.toLowerCase()))
  }
  selectBu4(bu4?: Bu4Model) {
    this.bu4 = new MyBu4Model(bu4 || {})
  }

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

  checkPrimary() {
    return this.bu5.dataList.find(x => x.bu5id == this.bu5.select.bu5id)
  }

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

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

