import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute } from '@angular/router';
import { forkJoin, Subscription } from 'rxjs';
import { CustomCubeService } from 'src/app/shared/services/custom-cube.service';
import { ExcelReportService } from 'src/app/shared/services/excel-report.service';
import { ColumnModel } from '@syncfusion/ej2-grids';
import Swal from 'sweetalert2';
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 = ""

    pageSize: number = 10
    page: number = 1
    currentPage: number = 1


    dialogRef: any
    @ViewChild("excelReportModal") excelReportModal: any;

    pathTitle = ['รายงาน Excel', 'รายงาน Excel 1']
    excelReportServiceSub?: Subscription

    @ViewChild("girdModal") girdModal: any;
    @ViewChild("pivotModal") pivotModal: any;

    columns: ColumnModel[] = []
    pivotColumns: any[] = []
    dataList: any[] = []
    gridLayout: { stimulate: boolean, data: string } = { stimulate: false, data: '' }
    pivotLayout: { stimulate: boolean, data: string } = { stimulate: false, data: '' }
    setPerspective = ""
    searchSettings = {
        fields: [],
        operator: 'contains',
        ignoreCase: false
    };
    templateOutlet: 'grid' | 'pivot' | '' = ''
    constructor(private route: ActivatedRoute,
        private excelReportService: ExcelReportService,
        private cdr: ChangeDetectorRef,
        private customCubeService: CustomCubeService,
        private dialog: MatDialog,
    ) {

    }

    ngOnInit(): void {
        this.excelReportServiceSub?.unsubscribe()
        this.loadingExcel = false
        this.cdr.detectChanges()
        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 || '')
            }
        });
    }

    ngOnDestroy(): void {
        this.excelReportServiceSub?.unsubscribe()
        this.loadingExcel = false
        this.cdr.detectChanges()
    }
    getDataExcelReport(templateId: string, fileName: string) {
        this.loading = true
        this.excelReport = undefined
        this.variableSheet = []
        this.valueDetail = []
        this.loadingExcel = false
        this.templateOutlet = ''
        this.excelReportService.getTemplateFile(templateId, fileName).subscribe((res: any) => {
            this.excelReport = res
            this.getExcelColumn()
            this.pathTitle = ['รายงาน Excel', this.excelReport.itemId + '.' + this.excelReport.tdesc]
            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 Date(y, m - 1, d) : null
                    }
                })
            }
            this.loading = false
            this.cdr.detectChanges()
        }, error => {
            this.loading = false

        })
    }
    getExcelColumn() {
        const body = {
            templateId: this.excelReport.templateId,
            fileName: this.excelReport.fileName
        }
        this.searchSettings = {
            fields: [],
            operator: 'contains',
            ignoreCase: false
        };
        this.columns = []
        this.pivotColumns = []
        this.customCubeService.getExcelColumn(body).subscribe((response: any) => {
            this.searchSettings = {
                fields: response.map((e: any) => e.split(':')[0]),
                operator: 'contains',
                ignoreCase: false
            };
            response.forEach((e: any, i: number) => {
                const [field, headerText] = e.split(':')
                this.columns.push({
                    field: field,
                    headerText: headerText,
                    type: "string",
                    isPrimaryKey: i == 0,
                })
                this.pivotColumns.push({
                    name: field,
                    caption: headerText
                })
            });
        }, error => {

        })
    }
    matDateChange(target: { [key: string]: any }, field: string, dateIso: string) {
        target[field] = this.toYYYYMMDD(dateIso)
    }
    toYYYYMMDD(dateInput?: string | null): string {
        if (!dateInput) return "";
        const parsedDate = new Date(dateInput);
        const options: Intl.DateTimeFormatOptions = {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
        };
        const formattedDate = parsedDate.toLocaleDateString('en-GB', options);
        const [day, month, year] = formattedDate.split('/');
        return `${year}-${month}-${day}`;
    }

    openModal(data: 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.dialogRef = this.dialog.open(this.excelReportModal, {
            width: '1000px',
            disableClose: false,
        });
    }
    closeDialog() {
        this.dialogRef.close()
    }

    valueDetailFilter(): any[] {
        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
        this.cdr.detectChanges()
    }

    getExcelData(type: 'grid' | 'pivot') {
        this.loadingExcel = true
        this.dataList = []
        this.setPerspective = ''
        const body: any = {
            templateId: this.excelReport.templateId,
            fileName: this.excelReport.fileName
        };
        this.variableSheet.forEach((item: any, index: number) => {
            const i = index + 1;
            body[`key${i}`] = item.key;
            if (item.type == 'help') {
                body[`val${i}`] = this.select[item.key].id
            } else if (item.type == 'list' || item.type == 'radio' || item.type == 'text') {
                body[`val${i}`] = this.select[item.key]
            } else if (item.type == 'calendar') {
                body[`val${i}`] = this.toDateStringOnly(this.select[item.key])
            }
        });
        forkJoin({
            excelData: this.customCubeService.getExcelData(body),
            excelPerspective: this.customCubeService.getExcelPerspective(body),
        }).subscribe({
            next: response => {
                this.dataList = response.excelData as any
                this.loadingExcel = false
                if (type == 'grid') {
                    this.templateOutlet = 'grid'
                    // this.openGridModal((response.excelPerspective as any).dataGridStr)
                } else if (type == 'pivot') {
                    this.templateOutlet = 'pivot'
                    // this.openPivotModal((response.excelPerspective as any).pivotStr)
                }
                this.cdr.detectChanges()
            }, error: error => {
                this.loadingExcel = false
            }
        })
    }
    openGridModal(setPerspective: string) {
        this.dialogRef = this.dialog.open(this.girdModal, {
            width: '60vw',
            disableClose: false,
        });
        setTimeout(() => {
            this.setPerspective = setPerspective
        }, 10)
    }
    openPivotModal(setPerspective: string) {
        this.dialogRef = this.dialog.open(this.pivotModal, {
            width: '60vw',
            disableClose: false,
        });
        setTimeout(() => {
            this.setPerspective = setPerspective
        }, 10)
    }

    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.toDateStringOnly(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 url = window.URL.createObjectURL(res);
            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);
            this.loadingExcel = false
            this.cdr.detectChanges()
        }, (err) => {
            this.loadingExcel = false
            this.cdr.detectChanges()
        })
    }
    toDateStringOnly(input: string | Date): string {
        let date: Date;

        if (typeof input === 'string') {
            // เช็กว่าเป็น dd-mm-yyyy
            const ddMmYyyy = /^(\d{2})-(\d{2})-(\d{4})$/;
            const match = input.match(ddMmYyyy);
            if (match) {
                // สลับเป็น yyyy-mm-dd เพื่อให้ new Date ทำงานถูกต้อง
                const [_, day, month, year] = match;
                date = new Date(`${year}-${month}-${day}`);
            } else {
                // ใช้ new Date ปกติ (เช่น yyyy-mm-dd หรือ ISO string)
                date = new Date(input);
            }
        } else {
            date = input;
        }

        if (isNaN(date.getTime())) return ''; // ไม่ใช่วันจริง
        const year = date.getFullYear();
        const month = `${date.getMonth() + 1}`.padStart(2, '0');
        const day = `${date.getDate()}`.padStart(2, '0');

        return `${year}-${month}-${day}`;
    }

    savePerspective(type: 'grid' | 'pivot') {
        if (type == 'grid') {
            this.loadingExcel = true
            setTimeout(() => {
                const body = {
                    templateId: this.excelReport.templateId,
                    fileName: this.excelReport.fileName,
                    dataGridStr: this.gridLayout.data,
                    pivotStr: "",
                }
                this.customCubeService.saveExcelPerspective(body).subscribe(response => {
                    this.loadingExcel = false
                    this.showAlert(response.message, 'success')
                    this.cdr.detectChanges()
                }, error => {
                    this.loadingExcel = false
                    this.showAlert(error.message, 'error')
                    this.cdr.detectChanges()
                })
                this.cdr.detectChanges();
            }, 500);
        } else if (type == 'pivot') {
            this.loadingExcel = true
            setTimeout(() => {
                const body = {
                    templateId: this.excelReport.templateId,
                    fileName: this.excelReport.fileName,
                    dataGridStr: '',
                    pivotStr: this.pivotLayout.data,
                }
                this.customCubeService.saveExcelPerspective(body).subscribe(response => {
                    this.loadingExcel = false
                    this.showAlert(response.message, 'success')
                    this.cdr.detectChanges()
                }, error => {
                    this.loadingExcel = false
                    this.showAlert(error.message, 'error')
                    this.cdr.detectChanges()
                })
                this.cdr.detectChanges();
            }, 500);
        }
    }

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