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 { Subscription } from 'rxjs';

export interface ModalDetail {
    text: { cardHead: string, search: string[], tableHead: string[] }
}
@Component({
    selector: 'app-excel-report',
    templateUrl: './excel-report.component.html',
    styleUrls: ['./excel-report.component.scss']
})
export class ExcelReportComponent implements OnInit {
    changeDate = new Date();
    select: any = {}
    excelReport?: any
    variableSheet: any = []
    loading = false
    loadingExcel = false
    valueDetail = []
    modalDetail: ModalDetail = {
        text: {
            cardHead: '',
            search: [],
            tableHead: []
        }
    }
    keySelect = ""
    searchModal = ""
    page = 1
    pageSize = 10

    excelReportServiceSub?: Subscription
    constructor(private route: ActivatedRoute,
        private ngbModal: NgbModal,
        private excelReportService: ExcelReportService,
        private cdr: ChangeDetectorRef
    ) {

    }

    ngOnInit(): void {
        this.route.paramMap.subscribe(params => {
            const rawId = params.get('id');
            if (rawId) {
                const [id, queryString] = rawId.split('?');
                const params = new URLSearchParams(queryString);
                const template = params.get('template');
                const name = params.get('name');
                this.getDataExcelReport(template || '', name || '')
            }
        });
    }
    getDataExcelReport(templateId: string, fileName: string) {
        this.excelReportServiceSub?.unsubscribe()
        this.loadingExcel = false
        this.loading = true
        this.excelReport = undefined
        this.variableSheet = []
        this.valueDetail = []
        this.excelReportService.getTemplateFile(templateId, fileName).subscribe((res: any) => {
            this.excelReport = res
            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
                        })
                        this.select[key] = data.value
                    } 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 || '' }
                            })
                        })
                        this.select[key] = data.value
                    } 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 || '' }
                            })
                        })
                        this.select[key] = data.value
                    } 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 })
                        this.select[key] = { id: data.value, tdesc: data.value, edesc: data.value }
                    } 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()
        }, error => {
            this.loading = false

        })
    }

    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 = ''
        }
    }

    ngbtoDate(date?: NgbDate) {
        if (date) {
            const day = String(date.day).padStart(2, '0');
            const month = String(date.month).padStart(2, '0');
            const year = date.year;
            return `${year}-${month}-${day}`
        }
        return ''
    }

    openModal(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.ngbModal.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;
        this.select[this.keySelect] = data
    }

    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 + "=" + this.select[item.key].id
            } else if (item.type == 'list' || item.type == 'radio' || item.type == 'text') {
                return "__" + item.key + "=" + this.select[item.key]
            } else if (item.type == 'calendar') {
                return "__" + item.key + "=" + this.ngbtoDate(this.select[item.key])
            }
            return ""
        }).join('|')
        const body = {
            fileName: fileName,
            paramObj: data
        }
        this.excelReportServiceSub?.unsubscribe()
        this.excelReportServiceSub = 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.cdr.detectChanges()
        })
    }
}
