import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NgbDate, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ExcelReportService } from 'src/app/service/excel-report.service';
import * as FileSaver from 'file-saver';
import { IDataOptions } from '@syncfusion/ej2-angular-pivotview';
import { ModuleModel } from 'src/app/model/module.model';
import { TemplateModel, TemplateFileModel, MyTemplateFileModel, MyTemplateModel } from 'src/app/model/template.model';
import { ConfirmModalComponent } from '../confirm-modal/confirm-modal.component';
import { AlertModalComponent } from '../alert-modal/alert-modal.component';
import { Subscription } from 'rxjs';

export interface ModalDetail {
    text: { cardHead: string, search: string[], tableHead: string[] }
}
@Component({
    selector: 'app-excel-report-toggle',
    templateUrl: './excel-report-toggle.component.html',
    styleUrls: ['./excel-report-toggle.component.scss']
})
export class ExcelReportToggleComponent implements OnInit {
    template: { data: TemplateModel[], filter: TemplateModel[], loading: boolean } = { data: [], filter: [], loading: false }
    templateFile: TemplateFileModel = new MyTemplateFileModel()
    module: { data: ModuleModel[], loading: boolean } = { data: [], loading: false }
    page = 1
    pageSize = 10
    pageModal = 1
    pageSizeModal = 10
    searchBy = ''
    condition = ''
    searchValue = ''
    openTemplate: Map<string, boolean> = new Map<string, boolean>()
    bodyTemplate: {
        status: 'add' | 'edit',
        data: {
            templateId: string,
            tname: string,
            ename: string,
            tdesc: string,
            edesc: string,
            module: string
        }
    } = {
            status: 'add',
            data: {
                templateId: '',
                tname: '',
                ename: '',
                tdesc: '',
                edesc: '',
                module: ''
            }
        }
    excelPortalSearch: {
        groupId: string,
        tags: string,
        search: string
    } = {
            groupId: '',
            tags: '',
            search: ''
        }
    tableHover: Map<string, boolean> = new Map<string, boolean>()
    buttonHover: Map<string, boolean> = new Map<string, boolean>()

    changeDate = new Date();
    select: any = {}
    excelReport?: any
    variableSheet: any = []
    loading = false
    loadingExcel = false
    valueDetail = []
    modalDetail: ModalDetail = {
        text: {
            cardHead: '',
            search: [],
            tableHead: []
        }
    }
    keySelect = ""
    searchModal = ""

    getTemplateFileSubscription?: Subscription
    constructor(private excelReportService: ExcelReportService,
        private modalService: NgbModal,
        private cdr: ChangeDetectorRef) {

    }
    ngOnInit(): void {
        this.getExcelList()
    }
    getExcelList() {
        this.template.loading = true
        this.excelReportService.getExcelList().subscribe(response => {
            this.template.data = response.map(e => new MyTemplateModel(e))
            this.template.filter = response.map(e => new MyTemplateModel(e))
            this.template.loading = false
        }, error => {
            this.template.loading = false
        })
    }
    templateListSearch() {
        if (!this.searchBy || !this.condition || !this.searchValue) {
            this.template.filter = this.template.data.map(e => new MyTemplateModel(e))
        }
        const conditionMap: { [key: string]: (a: any, b: any) => boolean } = {
            includes: (a, b) => (a || '').toString().toLowerCase().includes((b || '').toString().toLowerCase()),
            lt: (a, b) => parseFloat(a) < parseFloat(b),
            gt: (a, b) => parseFloat(a) > parseFloat(b),
            eq: (a, b) => a == b,
            lte: (a, b) => parseFloat(a) <= parseFloat(b),
            gte: (a, b) => parseFloat(a) >= parseFloat(b),
            neq: (a, b) => a != b,
        };

        const compareFn = conditionMap[this.condition];
        if (!compareFn) {
            this.template.filter = this.template.data.map(e => new MyTemplateModel(e))
        }


        this.template.filter = this.template.data.filter(item => {
            const value = (item as any)[this.searchBy];
            return compareFn(value, this.searchValue);
        }).map(e => new MyTemplateModel(e));
    }

    menuActiveTemplateFile(templateFile: TemplateFileModel) {
        const modalConfirmRef = this.modalService.open(ConfirmModalComponent, {
            centered: true,
            backdrop: 'static',
        })
        modalConfirmRef.componentInstance.message = 'คุณต้องการ' + (templateFile.menuActive == '1' ? 'ปิด' : 'เปิด') + 'การใช้งานหรือไม่'
        modalConfirmRef.result.then(result => {
            templateFile.menuActive = templateFile.menuActive == '1' ? '0' : '1'
            this.excelReportService.postTemplateFile(templateFile).subscribe(response => {
                if (response.success) {
                    this.openAlertModal(response.message)
                    this.getExcelList()
                } else {
                    this.openAlertModal(response.message)
                }
            }, error => {
                this.openAlertModal(error.message)
            })
        }, reject => { })
    }

    formatISOToLocal(isoString: string) {
        const date = new Date(isoString);
        const day = String(date.getDate()).padStart(2, '0');
        const month = String(date.getMonth() + 1).padStart(2, '0'); // เดือนเริ่มที่ 0
        const year = date.getFullYear();

        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');

        return { date: `${day}-${month}-${year}`, time: `${hours}:${minutes}` };
    }

    openAlertModal(message?: string) {
        const modalRef = this.modalService.open(AlertModalComponent, {
            centered: true,
            backdrop: 'static'
        })
        modalRef.componentInstance.message = message ? message : ""
        modalRef.result.then(result => {
        }, reason => {
        })
    }

    openPrintModal(targetModal: NgbModal, templateFile: TemplateFileModel) {
        this.getTemplateFile(templateFile)
        this.modalService.open(targetModal, {
            centered: true,
            size: 'lg'
        })
    }
    getTemplateFile(templateFile: TemplateFileModel) {
        this.loading = true
        this.excelReport = undefined
        this.variableSheet = []
        this.valueDetail = []
        this.getTemplateFileSubscription = this.excelReportService.getTemplateFile(templateFile.templateId, templateFile.fileName).subscribe(response => {
            this.excelReport = response
            if (this.excelReport.param) {
                Object.entries(this.excelReport.param.variableSheet).forEach(([key, value]) => {
                    const data = value as any
                    if (data.type == 'text') {
                        this.variableSheet.push({
                            ...data, value: data.valueDefault || '', key: key
                        })
                    } else if (data.type == 'list') {
                        this.variableSheet.push({
                            ...data, value: data.valueDefault || '', key: key, option: data.option.split('customize|')[1].split(',').map((x: any) => {
                                const [value, text] = x.split('#')
                                return { value: value || '', text: text || '' }
                            })
                        })
                    } else if (data.type == 'radio') {
                        this.variableSheet.push({
                            ...data, value: data.valueDefault || '', key: key, option: data.option.split('customize|')[1].split(',').map((x: any) => {
                                const [value, text] = x.split('#')
                                return { value: value || '', text: text || '' }
                            })
                        })
                    } else if (data.type == 'help') {
                        this.variableSheet.push({ ...data, value: data.valueDefault ? { id: data.valueDefault, tdesc: data.valueDefault, edesc: data.valueDefault } : { id: "", tdesc: "", edesc: "" }, key: key })
                    } else if (data.type == 'calendar') {
                        this.variableSheet.push({ ...data, value: data.valueDefault || '', key: key })
                        const [d, m, y] = data.valueDefault ? data.valueDefault.split('-').map(Number) : [null, null, null]
                        this.select[key] = y ? new NgbDate(y, m, d) : null
                    }
                })
            }
            this.loading = false
            this.cdr.detectChanges()
        }, (err) => {
            this.loading = false
        })
    }

    openModalData(data: any, modal: any) {
        this.searchModal = ''
        this.page = 1
        this.pageSize = 10
        this.valueDetail = data.valueDetail.map((x: any) => ({ id: x.id || '', tdesc: x.tdesc || '', edesc: x.edesc || '' }))
        this.keySelect = data.key
        this.modalDetail = {
            text: {
                cardHead: "Table " + data.table,
                search: ["Table " + data.table],
                tableHead: ['ID', 'detailTH', 'detailENG']
            }
        }
        this.modalService.open(modal, { centered: true, size: 'lg' })
    }

    valueDetailFilter() {
        return this.valueDetail.filter((item: any) =>
            item.id.toLowerCase().includes(this.searchModal.toLowerCase()) ||
            item.tdesc.toLowerCase().includes(this.searchModal.toLowerCase()) ||
            item.edesc.toLowerCase().includes(this.searchModal.toLowerCase())
        )
    }

    selectData(data: any) {
        const item = this.variableSheet.find((i: any) => i.key === this.keySelect);
        if (item) item.value = data;
    }

    formatNgbDate(key: string, date?: NgbDate) {
        if (date) {
            const day = String(date.day).padStart(2, '0');
            const month = String(date.month).padStart(2, '0');
            const year = date.year;
            const item = this.variableSheet.find((i: any) => i.key === key);
            if (item) item.value = `${day}-${month}-${year}`
        } else {
            const item = this.variableSheet.find((i: any) => i.key === key);
            if (item) item.value = ''
        }
    }

    dowloadExcelReport() {
        this.loadingExcel = true
        const fileName = this.excelReport.param.excelFile
        const param = this.excelReport.param.variableName
        const data = this.variableSheet.map((item: any) => {
            if (item.type == 'help') {
                return "__" + item.key + "=" + item.value.id
            } else if (item.type == 'calendar' || item.type == 'list' || item.type == 'radio' || item.type == 'text') {
                return "__" + item.key + "=" + item.value
            }
            return ""
        }).join('|')
        const body = {
            fileName: fileName,
            paramObj: data
        }

        this.excelReportService.printExcelReport(body).subscribe((res: any) => {
            const blob = new Blob([res], { type: 'application/octet-stream' });
            FileSaver.saveAs(blob, fileName);
            this.loadingExcel = false
            this.cdr.detectChanges()
        }, (err) => {
            this.loadingExcel = false
            this.openAlertModal(err.message)
            this.cdr.detectChanges()
        })
    }

    openGridModal(targetModal: NgbModal) {
        this.modalService.open(targetModal, {
            centered: true,
            backdrop: 'static',
            size: 'lg'
        })
    }
    openPivotModal(targetModal: NgbModal) {
        this.modalService.open(targetModal, {
            centered: true,
            backdrop: 'static',
            size: 'lg'
        })
    }

    ngOnDestroy(): void {
        this.getTemplateFileSubscription?.unsubscribe()
    }
}