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 { Bu1Model, MyBu1Model } from 'src/app/shared/model/bu1.model';
import { Bu2Model, MyBu2Model } from 'src/app/shared/model/bu2.model';
import { Bu1Service } from 'src/app/shared/services/bu1.service';
import { Bu2Service } from 'src/app/shared/services/bu2.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-department-list',
  templateUrl: './department-list.component.html',
  styleUrls: ['./department-list.component.scss']
})
export class DepartmentListComponent implements OnInit {
  columns: ColumnModel[] = [{
    field: "bu2id",
    headerText: "ทะเบียนแผนก",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "ทะเบียนแผนก (ไทย)",
    type: "string"
  },
  {
    field: "edesc",
    headerText: "ทะเบียนแผนก (อังกฤษ)",
    type: "string"
  }]
  searchSettings = {
    fields: ['bu2id', 'tdesc', 'edesc'],
    operator: 'contains',
    ignoreCase: false
  };
  search = ""
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };

  bu2List: Bu2Model[] = []
  bu2ListLoading = false
  bu2: Bu2Model = new MyBu2Model()
  bu2Table: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }

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

  bu2Modal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }
  bu1List: Bu1Model[] = []
  bu1: Bu1Model = new MyBu1Model()
  bu1Modal: table = {
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1),
    search: "",
    pageSize: 10
  }
  currentModal: 'add' | 'edit' | 'delete' = "add"
  @ViewChild("departmentListModal") departmentListModal: any;
  @ViewChild("departmentListBu1Modal") departmentListBu1Modal: any;
  dialogRef: any
  dialogRefBu1: any
  constructor(private bu2Service: Bu2Service,
    private bu1Service: Bu1Service,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private fileService: FileService,
    private dialog: MatDialog
  ) { }

  ngOnInit(): void {
    this.getBu2List()
    this.getBu1List()
  }
  openDialog() {
    this.dialogRef = this.dialog.open(this.departmentListModal, {
      width: '500px',
    })
  }
  openBu1Dialog() {
    this.dialogRefBu1 = this.dialog.open(this.departmentListBu1Modal, {
      width: '800px',
    })
  }
  closeDialog() {
    this.dialogRef.close()
  }
  closeBu1Dialog() {
    this.dialogRefBu1.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.bu2ListLoading = true
    this.fileService.uploadExcel(formData, 'mbu2').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getBu2List()
        } else {
          this.showAlert(response.message, 'error')
          this.bu2ListLoading = false
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.bu2ListLoading = 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')
      }
    })

  }

  getBu2List() {
    this.bu2ListLoading = true
    this.selectedItems.data.clear()
    this.bu2Service.getList().subscribe({
      next: response => {
        this.bu2List = response.map(x => {
          this.selectedItems.data.set(x.bu2id, false)
          return new MyBu2Model(x)
        })
        this.selectedItems.key = 'bu2id'
        this.selectedItems.count = 0
        this.bu2ListLoading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.bu2ListLoading = false
        this.cdr.detectChanges()
      }
    })
  }

  selectBu2(bu2?: Bu2Model) {
    this.bu2 = new MyBu2Model(bu2)
    this.selectBu1()
    if (this.bu2.parent) {
      this.bu1Service.getById(this.bu2.parent).subscribe(response => {
        this.bu1 = new MyBu1Model(response)
        this.cdr.detectChanges()
      })
    }
  }

  getBu1List() {
    this.bu1Service.getList().subscribe(response => {
      this.bu1List = response.map(x => new MyBu1Model(x))
      this.onBu1ModalSearchChange()
    })
  }
  onBu1ModalSearchChange() {
    this.bu1Modal.currentPage = 1
    this.bu1Modal.page = Array.from({ length: Math.ceil(this.filterBu1Modal().length / 10) }, (_, i) => i + 1);
  }
  bu1idChange() {
    const bu1 = this.bu1List.find(x => x.bu1id == this.bu1.bu1id)
    this.selectBu1(bu1 || new MyBu1Model({ bu1id: this.bu1.bu1id }))
  }
  filterBu1Modal() {
    return this.bu1List.filter(x => x.bu1id.toLowerCase().includes(this.bu1Modal.search.toLowerCase()) ||
      x.tdesc.toLowerCase().includes(this.bu1Modal.search.toLowerCase()) ||
      x.edesc.toLowerCase().includes(this.bu1Modal.search.toLowerCase()))
  }
  selectBu1(bu1?: Bu1Model) {
    this.bu1 = new MyBu1Model(bu1)
  }

  showAlert(text: string, type: 'success' | 'error') {
    Swal.fire({
      title: 'แจ้งเตือน',
      text: text,
      icon: type,
      confirmButtonText: 'ตกลง',
    });
  }
  addBu2() {
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการบันทึกข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'บันทึกข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        this.bu2ListLoading = true
        this.bu2Service.post({ ...this.bu2, parent: this.bu1.bu1id }).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getBu2List()
              this.closeDialog();
            } else {
              this.showAlert(response.message, 'error')
              this.bu2ListLoading = false
              this.closeDialog();
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.bu2ListLoading = false
            this.closeDialog();
          }
        })
      }
    });
  }

  deleteBu2() {
    if (!this.numSelectItem()) {
      this.showAlert('กรุณาเลือกข้อมูลที่ต้องการลบ', 'error')
      return
    }
    Swal.fire({
      icon: 'question',
      title: 'แจ้งเตือน',
      text: 'ยืนยันการลบข้อมูลหรือไม่',
      showCancelButton: true,
      confirmButtonText: 'ลบข้อมูล',
      cancelButtonText: 'ย้อนกลับ',
      reverseButtons: true,
    }).then((result) => {
      if (result.isConfirmed) {
        this.bu2ListLoading = true
        const selectedKeys = Array.from(this.selectedItems.data.keys());
        const body = this.bu2List.filter(x => selectedKeys.includes(x.bu2id) && this.selectedItems.data.get(x.bu2id)).map(x => new MyBu2Model(x))
        this.bu2Service.delete(body).subscribe({
          next: response => {
            if (response.success) {
              this.showAlert(response.message, 'success')
              this.getBu2List()
            } else {
              this.showAlert(response.message, 'error')
              this.bu2ListLoading = false
            }
          }, error: error => {
            this.showAlert(error.message, 'error')
            this.bu2ListLoading = false
          }
        })
      }
    });
  }


  checkPrimary() {
    return this.bu2List.find(x => x.bu2id == this.bu2.bu2id)
  }

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

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

