import { ChangeDetectorRef, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NgbDate, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import * as FileSaver from 'file-saver';
import { IDataOptions } from '@syncfusion/ej2-angular-pivotview';
import { ExcelReportService } from 'src/app/service/excel-report.service';
import { MyTemplateFileModel, MyTemplateModel, TemplateFileModel, TemplateModel } from 'src/app/model/template.model';
import { AlertModalComponent } from '../alert-modal/alert-modal.component';
import { MyModuleModel, ModuleModel } from 'src/app/model/module.model';
import { ConfirmModalComponent } from '../confirm-modal/confirm-modal.component';
import { ExcelPortalModel, ExcelPortalGroupModel, MyExcelPortalModel, ExcelPortalTagsModel, MyExcelPortalGroupModel, MyExcelPortalTagsModel } from 'src/app/model/excel-portal.model';
import { forkJoin, Subscription } from 'rxjs';
import { CustomCubeService } from 'src/app/service/custom-cube.service';
import { ColumnModel } from '@syncfusion/ej2-grids';
export interface ModalDetail {
    text: { cardHead: string, search: string[], tableHead: string[] }
}
@Component({
    selector: 'app-excel-list',
    templateUrl: './excel-list.component.html',
    styleUrls: ['./excel-list.component.scss']
})
export class ExcelListComponent 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: ''
        }
    excelPortal: { data: ExcelPortalModel[], loading: boolean } = { data: [], loading: false }
    excelPortalGroup: { data: ExcelPortalGroupModel[], loading: boolean } = { data: [], loading: false }
    excelPortalTags: { data: ExcelPortalTagsModel[], loading: boolean } = { data: [], loading: false }
    videoLink = ""
    templateFileType: 'portal' | 'upload' = 'portal'
    templateFileName = ''
    tableHover: Map<string, boolean> = new Map<string, boolean>()
    buttonHover: Map<string, boolean> = new Map<string, boolean>()
    addChildModalRef?: NgbModalRef
    @ViewChild('fileInput') fileInput!: ElementRef<HTMLInputElement>;
    downloadTemplateFileLoading: 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

    searchSettings = {
        fields: [],
        operator: 'contains',
        ignoreCase: false
    };
    columns: ColumnModel[] = []
    pivotColumns: any[] = []
    dataList: any[] = []

    gridLayout: { stimulate: boolean, data: string } = { stimulate: false, data: '' }
    pivotLayout: { stimulate: boolean, data: string } = { stimulate: false, data: '' }
    setPerspective = ""
    constructor(private excelReportService: ExcelReportService,
        private modalService: NgbModal,
        private customCubeService: CustomCubeService,
        private cdr: ChangeDetectorRef) {

    }
    ngOnInit(): void {
        this.getExcelList()
        this.getModuleList()
        this.getExcelPortalList()
        this.getExcelPortalgGroupList()
        this.getExcelPortalTagsList()
    }
    getExcelPortalList() {
        this.excelPortal.loading = true
        this.excelReportService.getExcelPortalList().subscribe(response => {
            this.excelPortal.data = response.map(e => new MyExcelPortalModel(e))
            this.excelPortal.loading = false
        }, error => {
            this.excelPortal.loading = false
        })
    }
    excelPortalFilter() {
        const search = this.excelPortalSearch.search?.trim();

        let result = this.excelPortal.data.filter(x =>
            x.group?.groupId?.includes(this.excelPortalSearch.groupId) ||
            x.tags?.some(e => e.value?.includes(this.excelPortalSearch.tags))
        );

        if (search) {
            result = result.filter(x =>
                (x.thName).includes(search) ||
                (x.thDesc).includes(search) ||
                (x.dbSupport).includes(search) ||
                String(x.isPivot ?? 0).includes(search) ||
                String(x.isDataGrid ?? 0).includes(search) ||
                ((x.downloadDate + x.downloadTime)).includes(search) ||
                ((x.uploadDate + x.uploadTime)).includes(search)
            );
        }

        return result;

    }
    getExcelPortalgGroupList() {
        this.excelPortalGroup.loading = true
        this.excelReportService.getExcelPortalgGroupList().subscribe(response => {
            this.excelPortalGroup.data = response.map(e => new MyExcelPortalGroupModel(e))
            this.excelPortalGroup.loading = false
        }, error => {
            this.excelPortalGroup.loading = false
        })
    }
    getExcelPortalTagsList() {
        this.excelPortalTags.loading = true
        this.excelReportService.getExcelPortalTagsList().subscribe(response => {
            this.excelPortalTags.data = response.map(e => new MyExcelPortalTagsModel(e))
            this.excelPortalTags.loading = false
        }, error => {
            this.excelPortalTags.loading = false
        })
    }
    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
        })
    }
    getModuleList() {
        this.module.loading = true
        this.excelReportService.getModuleList().subscribe(response => {
            this.module.data = response.map(e => new MyModuleModel(e))
            this.module.loading = false
        }, error => {
            this.module.loading = false
        })
    }
    postTemplate() {

    }
    openAlertModal(message?: string) {
        const modalRef = this.modalService.open(AlertModalComponent, {
            centered: true,
            backdrop: 'static'
        })
        modalRef.componentInstance.message = message ? message : ""
        modalRef.result.then(result => {
        }, reason => {
        })
    }
    openAddGroupModal(targetModal: NgbModal, data?: TemplateModel) {
        if (data) {
            this.bodyTemplate.status = 'edit'
            this.bodyTemplate.data = {
                templateId: data.templateId,
                tname: data.tname,
                ename: data.ename,
                tdesc: data.tdesc,
                edesc: data.edesc,
                module: data.module
            }
        } else {
            this.bodyTemplate.status = 'add'
            this.bodyTemplate.data = {
                templateId: '',
                tname: '',
                ename: '',
                tdesc: '',
                edesc: '',
                module: ''
            }
        }

        const modalRef = this.modalService.open(targetModal, {
            centered: true,
            backdrop: 'static',
            size: 'lg'
        })
        modalRef.result.then(result => {
            const modalConfirmRef = this.modalService.open(ConfirmModalComponent, {
                centered: true,
                backdrop: 'static',
            })
            modalConfirmRef.componentInstance.message = 'คุณต้องการบันทึกข้อมูลหรือไม่'
            modalConfirmRef.result.then(result => {
                this.excelReportService.postTemplate(this.bodyTemplate.data).subscribe((response: any) => {
                    this.openAlertModal(response.message)
                    if (response.success) {
                        this.getExcelList()
                        this.getModuleList()
                    }

                }, error => { this.openAlertModal(error.message) })
            }, reject => { })
        }, reject => { })

    }

    deleteTemplate(template: TemplateModel) {
        const modalConfirmRef = this.modalService.open(ConfirmModalComponent, {
            centered: true,
            backdrop: 'static',
        })
        modalConfirmRef.componentInstance.message = 'คุณต้องการลบข้อมูลหรือไม่'
        modalConfirmRef.result.then(result => {
            this.excelReportService.deleteTemplate(template).subscribe(response => {
                if (response.success) {
                    this.openAlertModal(response.message)
                    this.getExcelList()
                } else {
                    this.openAlertModal(response.message)
                }
            }, error => {
                this.openAlertModal(error.message)
            })
        }, reject => { })
    }
    openAddChildModal(targetModal: NgbModal, data: TemplateModel | TemplateFileModel, status: 'add' | 'edit') {
        if (status == 'add') {
            this.templateFile = new MyTemplateFileModel({ templateId: data.templateId, module: data.module })
            this.templateFileType = 'portal'
            this.templateFileName = ''
        } else if (status == 'edit') {
            this.templateFile = new MyTemplateFileModel(data)
            this.templateFileType = this.templateFile.portalId ? 'portal' : 'upload'
            this.templateFileName = this.templateFile.portalId ? '' : this.templateFile.fileName
            this.templateFile.realFileNameOld = this.templateFile.fileName
        }
        this.addChildModalRef = this.modalService.open(targetModal, {
            centered: true,
            backdrop: 'static',
            size: 'lg'
        })
    }

    openExcelPortalModal(targetModal: NgbModal) {
        this.pageModal = 1
        this.pageSizeModal = 10
        const modalRef = this.modalService.open(targetModal, {
            centered: true,
            backdrop: 'static',
            size: 'xl'
        })
        modalRef.result.then(result => {
            this.templateFile.portalId = result.excelId
        }, reject => { })
    }
    openVideoModal(targetModal: NgbModal, videoLink: string) {
        this.videoLink = this.convertToEmbedUrl(videoLink)
        this.modalService.open(targetModal, {
            centered: true,
            windowClass: 'my-dialog-video-preview'
        })
    }
    convertToEmbedUrl(youtubeUrl: string): string {
        try {
            const url = new URL(youtubeUrl);

            if (url.hostname.includes('youtube.com') && url.searchParams.has('v')) {
                const videoId = url.searchParams.get('v');
                return `https://www.youtube.com/embed/${videoId}`;
            }

            if (url.hostname === 'youtu.be') {
                const videoId = url.pathname.slice(1); // เอา path หลัง youtu.be/
                return `https://www.youtube.com/embed/${videoId}`;
            }
        } catch (e) {
            // ถ้า url ผิดรูปแบบ
            console.warn('Invalid YouTube URL:', youtubeUrl);
        }

        // ถ้าไม่เข้าเงื่อนไขใดเลย ให้คืนลิงก์เดิม
        return youtubeUrl;
    }

    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));
    }

    onFileSelected(event: any) {
        const file: File = event.target.files[0];

        if (!file) {
            alert('กรุณาเลือกไฟล์');
            return;
        }

        const allowedExtensions = ['xls', 'xlsx'];
        const fileExtension = file.name.split('.').pop()?.toLowerCase();

        if (!allowedExtensions.includes(fileExtension || '')) {
            alert('รองรับเฉพาะไฟล์ Excel (.xls, .xlsx) เท่านั้น');
            return;
        }

        const reader = new FileReader();

        reader.onload = () => {
            const base64String = (reader.result as string).split(',')[1]; // เอาเฉพาะส่วน base64

            // ✅ สร้าง payload
            const payload = {
                filename: file.name,
                filetype: file.type,
                fileExtension: fileExtension,
                data: base64String
            };

            this.templateFileName = payload.filename
            this.templateFile.fileData = payload.data
            this.templateFile.fileType = payload.fileExtension || ''
            this.fileInput.nativeElement.value = '';
        };

        reader.readAsDataURL(file); // อ่านแบบ Base64
    }
    postTemplateFile() {
        const modalConfirmRef = this.modalService.open(ConfirmModalComponent, {
            centered: true,
            backdrop: 'static',
        })
        modalConfirmRef.componentInstance.message = 'คุณต้องการบันทึกข้อมูลหรือไม่'
        modalConfirmRef.result.then(result => {
            this.addChildModalRef?.close()
            this.templateFile.createDate = new Date().toISOString();
            this.excelReportService.postTemplateFile(this.templateFile).subscribe(response => {
                if (response.success) {
                    this.openAlertModal(response.message)
                    this.getExcelList()
                } else {
                    this.openAlertModal(response.message)
                }
            }, error => {
                this.openAlertModal(error.message)
            })
        }, reject => { })
    }
    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}` };
    }

    deleteTemplateFile(templateFile: TemplateFileModel) {
        const modalConfirmRef = this.modalService.open(ConfirmModalComponent, {
            centered: true,
            backdrop: 'static',
        })
        modalConfirmRef.componentInstance.message = 'คุณต้องการลบข้อมูลหรือไม่'
        modalConfirmRef.result.then(result => {
            this.excelReportService.deleteTemplateFile(templateFile).subscribe(response => {
                if (response.success) {
                    this.openAlertModal(response.message)
                    this.getExcelList()
                } else {
                    this.openAlertModal(response.message)
                }
            }, error => {
                this.openAlertModal(error.message)
            })
        }, reject => { })
    }

    downloadTemplateFile(templateFile: TemplateFileModel) {
        this.downloadTemplateFileLoading.set(templateFile.fileName, true)
        this.excelReportService.downloadTemplateFile(templateFile.fileName).subscribe((response: any) => {
            const blob = new Blob([response], { type: 'application/octet-stream' });
            FileSaver.saveAs(blob, templateFile.fileName);
            this.downloadTemplateFileLoading.clear()
        }, error => {
            this.downloadTemplateFileLoading.clear()
            this.openAlertModal(error.message)
        })
    }
    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) {
                this.getExcelColumn()
                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, setPerspective: string) {
        this.modalService.open(targetModal, {
            centered: true,
            backdrop: 'static',
            windowClass: 'my-dialog-big-screen'
        })
        setTimeout(() => {
            this.setPerspective = setPerspective
        }, 10)
    }
    openPivotModal(targetModal: NgbModal, setPerspective: string) {
        this.modalService.open(targetModal, {
            centered: true,
            backdrop: 'static',
            windowClass: 'my-dialog-big-screen'
        })
        setTimeout(() => {
            this.setPerspective = setPerspective
        }, 10)
    }

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

    templateFileTypeChange() {
        if (this.templateFileName || this.templateFile.portalId) {
            const modalConfirmRef = this.modalService.open(ConfirmModalComponent, {
                centered: true,
                backdrop: 'static',
            })
            modalConfirmRef.componentInstance.message = 'คุณต้องการยกเลิกไฟล์ที่เลือกหรือไม่'
            modalConfirmRef.result.then(result => {
                this.onToggleTemplateFile()
            }, reject => { })
        } else {
            this.onToggleTemplateFile()
        }
    }

    onToggleTemplateFile() {
        if (this.templateFileType == 'portal') {
            this.templateFileType = 'upload'
            this.templateFile.portalId = ''
        } else if (this.templateFileType == 'upload') {
            this.templateFileType = 'portal';
            this.templateFile.fileData = '';
            this.templateFile.fileType = '';
            this.templateFileName = ''
        }
    }


    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 => {

        })
    }
    getExcelData(targetModal: NgbModal, 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}`] = item.value.id
            } else if (item.type == 'calendar' || item.type == 'list' || item.type == 'radio' || item.type == 'text') {
                body[`val${i}`] = item.value
            }
        });
        forkJoin({
            excelData: this.customCubeService.getExcelData(body),
            excelPerspective: this.customCubeService.getExcelPerspective(body),
        }).subscribe(response => {
            this.dataList = response.excelData as any
            this.loadingExcel = false
            if (type == 'grid') {
                this.openGridModal(targetModal, (response.excelPerspective as any).dataGridStr)
            } else if (type == 'pivot') {
                this.openPivotModal(targetModal, (response.excelPerspective as any).pivotStr)
            }
            this.cdr.detectChanges()
        }, error => {
            this.loadingExcel = false
        })
    }
    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.openAlertModal(response.message)
                }, error => {
                    this.loadingExcel = false
                    this.openAlertModal(error.message)
                })
                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.openAlertModal(response.message)
                }, error => {
                    this.loadingExcel = false
                    this.openAlertModal(error.message)
                })
                this.cdr.detectChanges();
            }, 500);
        }
    }
}