import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, ViewChild } from '@angular/core';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { MatDialog } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr';
import { Bu3Model, MyBu3Model } from 'src/app/shared/model/bu3.model';
import { Bu4Model, MyBu4Model } from 'src/app/shared/model/bu4.model';
import { Bu3Service } from 'src/app/shared/services/bu3.service';
import { Bu4Service } from 'src/app/shared/services/bu4.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-one',
  templateUrl: './sub-department-one.component.html',
  styleUrls: ['./sub-department-one.component.scss']
})
export class SubDepartmentOneComponent implements OnInit {
  bu4: { loading: boolean, select: Bu4Model, dataList: Bu4Model[] } = { loading: false, select: new MyBu4Model(), dataList: [] }

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

  bu4Modal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }
  bu3List: Bu3Model[] = []
  bu3: Bu3Model = new MyBu3Model()
  bu3Modal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }
  currentModal: 'add' | 'edit' | 'delete' = "add"


  columns: ColumnModel[] = [{
    field: "bu4id",
    headerText: "รหัสส่วนย่อย 1",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "รายละเอียดย่อย1 (ไทย)",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "รายละเอียดย่อย1 (อังกฤษ)",
    type: "string"
  }]
  searchSettings = {
    fields: ['bu4id', '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("subDepartmentOneModal") subDepartmentOneModal: any;
  @ViewChild("subDepartmentOneBu3TableModal") subDepartmentOneBu3TableModal: any;
  dialogRef: any
  dialogRefBu3: any
  constructor(private bu4Service: Bu4Service,
    private bu3Service: Bu3Service,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private dialog: MatDialog
  ) { }

  ngOnInit(): void {
    this.getBu4List()
    this.getBu3List()
    }

  openDialog() {
    this.dialogRef = this.dialog.open(this.subDepartmentOneModal, {
      width: '500px',
    })
  }
  openDialogBu3() {
    this.dialogRefBu3 = this.dialog.open(this.subDepartmentOneBu3TableModal, {
      width: '800px',
    })
  }
  closeDialog() {
    this.dialogRef.close()
  }
  closeDialogBu3() {
    this.dialogRefBu3.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.bu4.loading = true
    this.fileService.uploadExcel(formData, 'mbu4').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getBu4List()
        } else {
          this.showAlert(response.message, 'error')
          this.bu4.loading = false
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.bu4.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')
      }
    })

  }
  getBu4List() {
    this.bu4.loading = true
    this.selectedItems.data.clear()
    this.bu4Service.getList().subscribe({
      next: response => {
        this.bu4.dataList = response.map(x => {
          this.selectedItems.data.set(x.bu4id, false)
          return new MyBu4Model(x)
        })
        this.selectedItems.key = 'bu4id'
        this.selectedItems.count = 0
        this.bu4.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.bu4.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  selectBu4(bu4?: Bu4Model) {
    if (bu4) {
      this.bu4.select = new MyBu4Model(bu4)
    } else if (this.currentModal == 'add') {
      this.bu4.select = new MyBu4Model()
    } else if (this.currentModal == 'edit') {
      this.bu4.select = new MyBu4Model({ bu4id: this.bu4.select.bu4id })
    }
    this.selectBu3()
    if (this.bu4.select.parent) {
      this.bu3Service.getById(this.bu4.select.parent).subscribe(response => {
        this.bu3 = new MyBu3Model(response)
        this.cdr.detectChanges()
      })
    }
  }

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

  getBu3List() {
    this.bu3Service.getList().subscribe(response => {
      this.bu3List = response.map(x => new MyBu3Model(x))
      this.onBu3ModalSearchChange()
    })
  }
  onBu3ModalSearchChange() {
    this.bu3Modal.currentPage = 1
    this.bu3Modal.page = Array.from({ length: Math.ceil(this.filterBu3Modal().length / 10) }, (_, i) => i + 1);
  }
  bu3idChange() {
    const bu3 = this.bu3List.find(x => x.bu3id == this.bu3.bu3id)
    this.selectBu3(bu3 || new MyBu3Model({ bu3id: this.bu3.bu3id }))
  }
  filterBu3Modal() {
    return this.bu3List.filter(x => x.bu3id.toLowerCase().includes(this.bu3Modal.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.bu3Modal.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.bu3Modal.search.toLowerCase()))
  }
  selectBu3(bu3?: Bu3Model) {
    this.bu3 = new MyBu3Model(bu3 || {})
  }

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


  checkPrimary() {
    return this.bu4.dataList.find(x => x.bu4id == this.bu4.select.bu4id)
  }

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

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


