import React, { Component } from 'react'
import { Typography, TextField, Paper } from '@material-ui/core'
import Constant from '../../library/Constant'
import api from '../../api'
import { titleCase } from '../../library/Utils'
import { Autocomplete } from '@material-ui/lab'
import TableSummaryTriputra from './TableSummaryTriputra'
import { PropagateLoader } from 'react-spinners'
import ReactTooltip from 'react-tooltip'
import Images from '../../assets/Images'
import { format } from 'date-fns';

export default class SummaryOfTriputra extends Component {
    constructor(props) {
        super(props)
        this.state = {
            periode: '2020',
            perusahaan: 'TAP Group',
            laporan: 'Balance Sheet - Montly',
            tab: 0,
            listCompany: null,
            company: null,
            listPeriode: null,
            periode: null,
            reportType: [
                { value: 1, label: 'MTD Report', key: "MTD" },
                { value: 2, label: 'YTD Report', key: "YTD" },
                { value: 3, label: 'CPSM Report', key: "CPSM" },
                { value: 4, label: 'Historical', key: "historical" },
            ],
            report: null,
            loading: false,
            previewTable: false,
            listMonths: null,
            month: null
        }
    }

    selectTab = (event, newEvent) => {
        this.setState({ tab: newEvent })
    }

    componentDidMount() {
        // this.getDetailUser()
        this.setState({ report: this.state.reportType[0], loading: false }, () => {
            console.log(this.state.report);
            this.getPeriode()
        })
        
        // this.getMonth()
    }

    getPeriode() {
        api.create().getPeriodeTransaction().then(response => {
            let currentYear = new Date().getFullYear()
            console.log(currentYear)
            console.log(response)
            if (response.data) {
                if (response.data.status === "success") {
                    let data = []
                    response.data.data.map((item) => {
                        // if (this.state.isApprover) {
                            if (item >= 2000 && item <= (Number(currentYear) + 1)) {
                                data.push(item)
                            }
                        // } else {
                        //     if ((item >= 2000) && (item == this.state.lastPeriod || item < this.state.lastPeriod)) {
                        //         data.push(item)
                        //     }
                        // }
                    })
                    let periodeData = data.map((item) => {
                        return {
                            periode: item,
                        }
                    })
                    let defaultProps = {
                        options: periodeData,
                        getOptionLabel: (option) => option.periode,
                    };
                    // let periode = (this.state.lastPeriod == "" ? String(Number(currentYear) + 1) : this.state.lastPeriod)
                    let periode = String(Number(currentYear))
                    let index = data.sort((a, b) => a - b).findIndex((val) => val === periode)
                    // console.log(data)
                    // console.log(this.state.latestPeriode)
                    // console.log(periodeData)
                    console.log(index)
                    this.setState({ listPeriode: defaultProps, periode: index === -1 ? periodeData[0] : periodeData[index], loading: false }, () => {
                        // this.getDataTable()
                        this.getMonth()
                        // this.getSubmission()
                        // if (this.state.isApprover === true) {
                        //     this.getCompanySubmitted()
                        // } else {
                        //     this.getRevision()
                        // }
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
            }
        })
    }

    getMonth() {
        api.create().getMonthTransaction().then(response => {
            let dateNow = new Date
            let month = format(dateNow, 'MMMM')
            console.log(month)
            console.log(response)
            if (response.data) {
                if (response.data.status === "success") {
                    let data = response.data.data
                    let monthData = data.map((item) => {
                        return {
                            month_id: item.id,
                            month_name: item.month_name
                        }
                    })
                    let defaultProps = {
                        options: monthData,
                        getOptionLabel: (option) => option.month_name,
                    };
                    // let index = data.sort((a, b) => a - b).findIndex((val) => val == bulan)
                    // this.setState({ listMonth: defaultProps, month: index == -1 ? monthData[0] : monthData[index] })

                    let index = data.findIndex((val) => val.month_name == month)
                    console.log(index)
                    console.log(monthData)
                    this.setState({ listMonths: defaultProps, month: index == -1 ? monthData[0] : monthData[index] }, () => {
                        this.getDataTable()
                    })
                    console.log(this.state.month)
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
            }
        })
    }

    // getReportType() {
    //     let payload = {
    //         "company_id": this.state.company.company_id,
    //         "periode": this.state.periode.periode,
    //         "report_type": "Master Budget",
    //     }
    //     api.create().getReportTypeBody(payload).then(response => {
    //         console.log(response);
    //         if (response.data) {
    //             if (response.data.status === "success") {
    //                 if (this.state.report.value === 1) {
    //                     response.data.data.map((item, index) => {
    //                         if (item.report_name === 'MTD Report') {
    //                             this.setState({ revisionType: item.revision }, ()=> {
    //                                 this.getSubmission()
    //                             })
    //                         }
    //                     })
    //                 } else if (this.state.report.value === 1) {
    //                     response.data.data.map((item, index) => {
    //                         if (item.report_name === 'YTD Report') {
    //                             this.setState({ revisionType: item.revision }, ()=> {
    //                                 this.getSubmission()
    //                             })
    //                         }
    //                     })
    //                 } else {
    //                     this.setState({ revisionType: 0 }, ()=> {
    //                         this.getSubmission()
    //                     })
    //                 }
    //             }
    //         }
    //     })
    // }

    // getSubmission() {
    //     this.setState({ loading: true })
    //     let payload = {
    //         "company_id": this.state.company.company_id,
    //         "periode": this.state.periode.periode,
    //         "is_approver": true
    //     }
    //     api.create().getSubmission(payload).then(response => {
    //         // console.log(response)
    //         if (response.data) {
    //             if (response.data.status === "success") {
    //                 this.setState({
    //                     submissionID: response.data.data.submission_id,
    //                     lastRevision: response.data.data.last_revision,
    //                 }, () => {
    //                     this.getDataTable()
    //                 })
    //             } else {
    //                 this.setState({ submissionID: null, loading: false })
    //             }
    //         }
    //     })
    // }

    getDataTable() {
        this.setState({ loading: true })
        let payload = {
            "report_type": this.state.report.key,
            "periode": this.state.periode.periode,
            "months" : this.state.month.month_id
        }
        let newPayload = {
            "periode": this.state.periode.periode,
            "report_type":"historical"
        }
        if (this.state.report.value === 1) {
            api.create().getHierarkiReportMTD(payload).then(response => {
                console.log(payload);
                console.log(response);
                let dataTable = []
                if (response.data) {
                    if (response.data.status === 'success') {
                        let res = [response.data.data]
                        const handlePushChild = (item) => {
                            let indexIDzz = dataTable.findIndex((val) => val[0] === item.company_id)
                            if (indexIDzz === -1) {
                                dataTable.push([
                                    // item.company_id,
                                    0,
                                    item.parent,
                                    item.level,
                                    item.item_name,
                                    item.revenue_act,
                                    item.revenue_mb,
                                    item.revenue_percent_of_mb,
                                    item.ebitda_act,
                                    item.ebitda_mb,
                                    item.ebitda_percent_of_mb,
                                    item.tpat_act,
                                    item.tpat_mb,
                                    item.tpat_percent_of_mb,
                                    item.npat_act,
                                    item.npat_mb,
                                    item.npat_percent_of_mb,
                                    item.cash_flow_cfo,
                                    item.cash_flow_cfi,
                                    item.cash_flow_cff,
                                    item.cash_flow_cf,
                                    item.os_bank_loan_ki,
                                    item.os_bank_loan_wc,
                                    item.os_bank_loan_other,
                                    item.os_bank_loan_total,
                                    item.os_shl,
                                    item.balance_sheet_cash_bank,
                                    item.balance_sheet_ca,
                                    item.balance_sheet_cl,
                                    item.balance_sheet_equity,
                                    item.ratio_cr,
                                    item.ratio_der,
                                    item.ratio_debt_to_ebitda,
                                    item.ratio_to_interest,
                                    item.ratio_ar_days,
                                    item.ratio_inv_days,
                                    item.ratio_ap_days,
                                    item.ratio_ccc,
                                    item.is_approved == undefined ? true : item.is_approved,
                                    // item.order,
                                ])
                            }
                            if (item.children !== null) {
                                if (item.children.length > 0) {
                                    item.children.map((items, indexs) => {
                                        handlePushChild(items)
                                    })
                                }
                            }
                        }
                        res.map((item, index) => {
                            dataTable.push([
                                // item.company_id,
                                0,
                                item.parent,
                                item.level,
                                item.item_name,
                                item.revenue_act,
                                item.revenue_mb,
                                item.revenue_percent_of_mb,
                                item.ebitda_act,
                                item.ebitda_mb,
                                item.ebitda_percent_of_mb,
                                item.tpat_act,
                                item.tpat_mb,
                                item.tpat_percent_of_mb,
                                item.npat_act,
                                item.npat_mb,
                                item.npat_percent_of_mb,
                                item.cash_flow_cfo,
                                item.cash_flow_cfi,
                                item.cash_flow_cff,
                                item.cash_flow_cf,
                                item.os_bank_loan_ki,
                                item.os_bank_loan_wc,
                                item.os_bank_loan_other,
                                item.os_bank_loan_total,
                                item.os_shl,
                                item.balance_sheet_cash_bank,
                                item.balance_sheet_ca,
                                item.balance_sheet_cl,
                                item.balance_sheet_equity,
                                item.ratio_cr,
                                item.ratio_der,
                                item.ratio_debt_to_ebitda,
                                item.ratio_to_interest,
                                item.ratio_ar_days,
                                item.ratio_inv_days,
                                item.ratio_ap_days,
                                item.ratio_ccc,
                                item.is_approved == undefined ? true : item.is_approved,
                                // item.order,
                            ])
                            if (item.children !== null) {
                                if (item.children.length > 0) {
                                    item.children.map((items, indexs) => {
                                        handlePushChild(items)
                                    })
                                }
                            }
                        })
                        console.log(dataTable)
                        this.setState({ dataTable, previewTable: true, loading: false, previewDownload: true })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                            if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    this.setState({ dataTable: [], previewTable: false, loading: false, previewDownload: false })
                }
            })
        } else if (this.state.report.value === 2) {
            api.create().getHierarkiReportYtd(payload).then(response => {
                console.log(payload);
                console.log(response);
                let dataTable = []
                if (response.data) {
                    if (response.data.status === 'success') {
                        let res = [response.data.data]
                        const handlePushChild = (item) => {
                            let indexIDzz = dataTable.findIndex((val) => val[0] === item.company_id)
                            if (indexIDzz === -1) {
                                dataTable.push([
                                    0,
                                    item.parent,
                                    item.level,
                                    item.item_name,
                                    item.revenue_ytd_act,
                                    item.revenue_ytd_mb,
                                    item.revenue_ytd_percent_of_mb,
                                    item.revenue_ytd_last_year,
                                    item.revenue_ytd_percent_of_last_year,
                                    item.revenue_fy_ol,
                                    item.revenue_fy_mb,
                                    item.revenue_fy_percent_of_mb,
                                    item.revenue_fy_last_year,
                                    item.revenue_fy_percent_of_last_year,
                                    item.ebitda_ytd_act,
                                    item.ebitda_ytd_mb,
                                    item.ebitda_ytd_percent_of_mb,
                                    item.ebitda_ytd_last_year,
                                    item.ebitda_ytd_percent_of_last_year,
                                    item.ebitda_fy_ol,
                                    item.ebitda_fy_mb,
                                    item.ebitda_fy_percent_of_mb,
                                    item.ebitda_fy_last_year,
                                    item.ebitda_fy_percent_of_last_year,
                                    item.tpat_ytd_act,
                                    item.tpat_ytd_mb,
                                    item.tpat_ytd_percent_of_mb,
                                    item.tpat_ytd_last_year,
                                    item.tpat_ytd_percent_of_last_year,
                                    item.tpat_fy_ol,
                                    item.tpat_fy_mb,
                                    item.tpat_fy_percent_of_mb,
                                    item.tpat_fy_last_year,
                                    item.tpat_fy_percent_of_last_year,
                                    item.npat_ytd_act,
                                    item.npat_ytd_mb,
                                    item.npat_ytd_percent_of_mb,
                                    item.npat_ytd_last_year,
                                    item.npat_ytd_percent_of_last_year,
                                    item.npat_fy_ol,
                                    item.npat_fy_mb,
                                    item.npat_fy_percent_of_mb,
                                    item.npat_fy_last_year,
                                    item.npat_fy_percent_of_last_year,
                                    item.order,
                                    item.is_approved == undefined ? true : item.is_approved,
                                    item.ytd_optional_cashflow_cfo,
                                    item.ytd_optional_cashflow_cfi,
                                    item.ytd_optional_cashflow_cff,
                                    item.ytd_optional_cashflow_netcf,
                                    item.ytd_optional_osbankloan_ki,
                                    item.ytd_optional_osbankloan_wc,
                                    item.ytd_optional_osbankloan_others,
                                    item.ytd_optional_osbankloan_total,
                                    item.ytd_optional_os_shl,
                                    item.ytd_optional_balancesheet_cashbank,
                                    item.ytd_optional_balancesheet_ca,
                                    item.ytd_optional_balancesheet_cl,
                                    item.ytd_optional_balancesheet_equity,
                                    item.ytd_optional_financialratio_cr,
                                    item.ytd_optional_financialratio_der,
                                    item.ytd_optional_financialratio_debttoebitda,
                                    item.ytd_optional_financialratio_tointerest,
                                    item.ytd_optional_financialratio_ardays,
                                    item.ytd_optional_financialratio_invdays,
                                    item.ytd_optional_financialratio_apdays,
                                    item.ytd_optional_financialratio_ccc,
                                ])
                            }
                            if (item.children !== null) {
                                if (item.children.length > 0) {
                                    item.children.map((items, indexs) => {
                                        handlePushChild(items)
                                    })
                                }
                            }
                        }
                        res.map((item, index) => {
                            dataTable.push([
                                0,
                                item.parent,
                                item.level,
                                item.item_name,
                                item.revenue_ytd_act,
                                item.revenue_ytd_mb,
                                item.revenue_ytd_percent_of_mb,
                                item.revenue_ytd_last_year,
                                item.revenue_ytd_percent_of_last_year,
                                item.revenue_fy_ol,
                                item.revenue_fy_mb,
                                item.revenue_fy_percent_of_mb,
                                item.revenue_fy_last_year,
                                item.revenue_fy_percent_of_last_year,
                                item.ebitda_ytd_act,
                                item.ebitda_ytd_mb,
                                item.ebitda_ytd_percent_of_mb,
                                item.ebitda_ytd_last_year,
                                item.ebitda_ytd_percent_of_last_year,
                                item.ebitda_fy_ol,
                                item.ebitda_fy_mb,
                                item.ebitda_fy_percent_of_mb,
                                item.ebitda_fy_last_year,
                                item.ebitda_fy_percent_of_last_year,
                                item.tpat_ytd_act,
                                item.tpat_ytd_mb,
                                item.tpat_ytd_percent_of_mb,
                                item.tpat_ytd_last_year,
                                item.tpat_ytd_percent_of_last_year,
                                item.tpat_fy_ol,
                                item.tpat_fy_mb,
                                item.tpat_fy_percent_of_mb,
                                item.tpat_fy_last_year,
                                item.tpat_fy_percent_of_last_year,
                                item.npat_ytd_act,
                                item.npat_ytd_mb,
                                item.npat_ytd_percent_of_mb,
                                item.npat_ytd_last_year,
                                item.npat_ytd_percent_of_last_year,
                                item.npat_fy_ol,
                                item.npat_fy_mb,
                                item.npat_fy_percent_of_mb,
                                item.npat_fy_last_year,
                                item.npat_fy_percent_of_last_year,
                                item.order,
                                item.is_approved == undefined ? true : item.is_approved,
                                item.ytd_optional_cashflow_cfo,
                                item.ytd_optional_cashflow_cfi,
                                item.ytd_optional_cashflow_cff,
                                item.ytd_optional_cashflow_netcf,
                                item.ytd_optional_osbankloan_ki,
                                item.ytd_optional_osbankloan_wc,
                                item.ytd_optional_osbankloan_others,
                                item.ytd_optional_osbankloan_total,
                                item.ytd_optional_os_shl,
                                item.ytd_optional_balancesheet_cashbank,
                                item.ytd_optional_balancesheet_ca,
                                item.ytd_optional_balancesheet_cl,
                                item.ytd_optional_balancesheet_equity,
                                item.ytd_optional_financialratio_cr,
                                item.ytd_optional_financialratio_der,
                                item.ytd_optional_financialratio_debttoebitda,
                                item.ytd_optional_financialratio_tointerest,
                                item.ytd_optional_financialratio_ardays,
                                item.ytd_optional_financialratio_invdays,
                                item.ytd_optional_financialratio_apdays,
                                item.ytd_optional_financialratio_ccc,
                            ])
                            if (item.children !== null) {
                                if (item.children.length > 0) {
                                    item.children.map((items, indexs) => {
                                        handlePushChild(items)
                                    })
                                }
                            }
                        })
                        console.log(dataTable)
                        this.setState({ dataTable, previewTable: true, loading: false, previewDownload: true })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                            if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    this.setState({ dataTable: [], previewTable: false, loading: false, previewDownload: false })
                }
            })
        } else if (this.state.report.value === 3) {
            api.create().getHierarkiReportCPSM(payload).then(response => {
                console.log(payload);
                console.log(response);
                let dataTable = []
                if (response.data) {
                    if (response.data.status === 'success') {
                        let res = [response.data.data]
                        const handlePushChild = (item) => {
                            let indexIDzz = dataTable.findIndex((val) => val[0] === item.company_id)
                            if (indexIDzz === -1) {
                                dataTable.push([
                                    0,
                                    item.parent,
                                    item.level,
                                    item.item_name,
                                    item.revenue_last_year,
                                    item.revenue_ol,
                                    item.revenue_mb,
                                    item.revenue_percent_of_mb,
                                    item.revenue_next_year,
                                    item.revenue_next_two_year,
                                    item.ebitda_last_year,
                                    item.ebitda_ol,
                                    item.ebitda_mb,
                                    item.ebitda_percent_of_mb,
                                    item.ebitda_next_year,
                                    item.ebitda_next_two_year,
                                    item.tpat_last_year,
                                    item.tpat_ol,
                                    item.tpat_mb,
                                    item.tpat_percent_of_mb,
                                    item.tpat_next_year,
                                    item.tpat_next_two_year,
                                    item.npat_last_year,
                                    item.npat_ol,
                                    item.npat_mb,
                                    item.npat_percent_of_mb,
                                    item.npat_next_year,
                                    item.npat_next_two_year,
                                    item.roic_ol,
                                    item.roic_next_year,
                                    item.roic_next_two_year,
                                    item.ebitda_margin_ol,
                                    item.ebitda_margin_next_year,
                                    item.ebitda_margin_next_two_year,
                                    item.tpat_margin_ol,
                                    item.tpat_margin_next_year,
                                    item.tpat_margin_next_two_year,
                                    item.percent_revenue_yoy_ol,
                                    item.percent_revenue_yoy_next_year,
                                    item.percent_revenue_yoy_next_two_year,
                                    item.percent_ebitda_yoy_ol,
                                    item.percent_ebitda_yoy_next_year,
                                    item.percent_ebitda_yoy_next_two_year,
                                    item.percent_tpat_yoy_ol,
                                    item.percent_tpat_yoy_next_year,
                                    item.percent_tpat_yoy_next_two_year,
                                    item.percent_npat_yoy_ol,
                                    item.percent_npat_yoy_next_year,
                                    item.percent_npat_yoy_next_two_year,
                                    item.is_approved == undefined ? true : item.is_approved,
                                    // item.order,
                                ])
                            }
                            if (item.children !== null) {
                                if (item.children.length > 0) {
                                    item.children.map((items, indexs) => {
                                        handlePushChild(items)
                                    })
                                }
                            }
                        }
                        res.map((item, index) => {
                            dataTable.push([
                                0,
                                item.parent,
                                item.level,
                                item.item_name,
                                item.revenue_last_year,
                                item.revenue_ol,
                                item.revenue_mb,
                                item.revenue_percent_of_mb,
                                item.revenue_next_year,
                                item.revenue_next_two_year,
                                item.ebitda_last_year,
                                item.ebitda_ol,
                                item.ebitda_mb,
                                item.ebitda_percent_of_mb,
                                item.ebitda_next_year,
                                item.ebitda_next_two_year,
                                item.tpat_last_year,
                                item.tpat_ol,
                                item.tpat_mb,
                                item.tpat_percent_of_mb,
                                item.tpat_next_year,
                                item.tpat_next_two_year,
                                item.npat_last_year,
                                item.npat_ol,
                                item.npat_mb,
                                item.npat_percent_of_mb,
                                item.npat_next_year,
                                item.npat_next_two_year,
                                item.roic_ol,
                                item.roic_next_year,
                                item.roic_next_two_year,
                                item.ebitda_margin_ol,
                                item.ebitda_margin_next_year,
                                item.ebitda_margin_next_two_year,
                                item.tpat_margin_ol,
                                item.tpat_margin_next_year,
                                item.tpat_margin_next_two_year,
                                item.percent_revenue_yoy_ol,
                                item.percent_revenue_yoy_next_year,
                                item.percent_revenue_yoy_next_two_year,
                                item.percent_ebitda_yoy_ol,
                                item.percent_ebitda_yoy_next_year,
                                item.percent_ebitda_yoy_next_two_year,
                                item.percent_tpat_yoy_ol,
                                item.percent_tpat_yoy_next_year,
                                item.percent_tpat_yoy_next_two_year,
                                item.percent_npat_yoy_ol,
                                item.percent_npat_yoy_next_year,
                                item.percent_npat_yoy_next_two_year,
                                item.is_approved == undefined ? true : item.is_approved,
                                // item.order,
                            ])
                            if (item.children !== null) {
                                if (item.children.length > 0) {
                                    item.children.map((items, indexs) => {
                                        handlePushChild(items)
                                    })
                                }
                            }
                        })
                        console.log(dataTable);
                        this.setState({ dataTable, previewTable: true, loading: false, previewDownload: true })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                            if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    this.setState({ dataTable: [], previewTable: false, loading: false, previewDownload: false })
                }
            })
        } else if (this.state.report.value === 4) {
            api.create().getHierarkiReportHistorical(newPayload).then(response => {
                console.log(newPayload);
                console.log(response);
                let dataTable = []
                if (response.data) {
                    if (response.data.status === 'success') {
                        let res = [response.data.data]
                        console.log(res)
                        const handlePushChild = (item) => {
                            let indexIDzz = dataTable.findIndex((val) => val[0] === item.company_id)
                            if (indexIDzz === -1) {
                                dataTable.push([
                                    0,
                                    item.parent,
                                    item.level,
                                    item.item_name,
                                    item.revenue_last_ten_year,
                                    item.revenue_last_nine_year,
                                    item.revenue_last_eight_year,
                                    item.revenue_last_seven_year,
                                    item.revenue_last_six_year,
                                    item.revenue_last_five_year,
                                    item.revenue_last_four_year,
                                    item.revenue_last_three_year,
                                    item.revenue_last_two_year,
                                    item.revenue_last_year,
                                    // item.revenue,
                                    0,
                                    item.ebitda_last_ten_year,
                                    item.ebitda_last_nine_year,
                                    item.ebitda_last_eight_year,
                                    item.ebitda_last_seven_year,
                                    item.ebitda_last_six_year,
                                    item.ebitda_last_five_year,
                                    item.ebitda_last_four_year,
                                    item.ebitda_last_three_year,
                                    item.ebitda_last_two_year,
                                    item.ebitda_last_year,
                                    // item.ebitda,
                                    0,
                                    item.tpat_last_ten_year,
                                    item.tpat_last_nine_year,
                                    item.tpat_last_eight_year,
                                    item.tpat_last_seven_year,
                                    item.tpat_last_six_year,
                                    item.tpat_last_five_year,
                                    item.tpat_last_four_year,
                                    item.tpat_last_three_year,
                                    item.tpat_last_two_year,
                                    item.tpat_last_year,
                                    // item.tpat,
                                    0,
                                    item.npat_last_ten_year,
                                    item.npat_last_nine_year,
                                    item.npat_last_eight_year,
                                    item.npat_last_seven_year,
                                    item.npat_last_six_year,
                                    item.npat_last_five_year,
                                    item.npat_last_four_year,
                                    item.npat_last_three_year,
                                    item.npat_last_two_year,
                                    item.npat_last_year,
                                    // item.npat,
                                    0,
                                    item.total_asset_last_ten_year,
                                    item.total_asset_last_nine_year,
                                    item.total_asset_last_eight_year,
                                    item.total_asset_last_seven_year,
                                    item.total_asset_last_six_year,
                                    item.total_asset_last_five_year,
                                    item.total_asset_last_four_year,
                                    item.total_asset_last_three_year,
                                    item.total_asset_last_two_year,
                                    item.total_asset_last_year,
                                    // item.total_asset,
                                    0,
                                    item.total_equity_last_ten_year,
                                    item.total_equity_last_nine_year,
                                    item.total_equity_last_eight_year,
                                    item.total_equity_last_seven_year,
                                    item.total_equity_last_six_year,
                                    item.total_equity_last_five_year,
                                    item.total_equity_last_four_year,
                                    item.total_equity_last_three_year,
                                    item.total_equity_last_two_year,
                                    item.total_equity_last_year,
                                    // item.total_equity,
                                    0,
                                    item.order,
                                ])
                            }
                            if (item.children !== null) {
                                if (item.children.length > 0) {
                                    item.children.map((items, indexs) => {
                                        handlePushChild(items)
                                    })
                                }
                            }
                        }
                        res.map((item, index) => {
                            dataTable.push([
                                0,
                                item.parent,
                                item.level,
                                item.item_name,
                                item.revenue_last_ten_year,
                                item.revenue_last_nine_year,
                                item.revenue_last_eight_year,
                                item.revenue_last_seven_year,
                                item.revenue_last_six_year,
                                item.revenue_last_five_year,
                                item.revenue_last_four_year,
                                item.revenue_last_three_year,
                                item.revenue_last_two_year,
                                item.revenue_last_year,
                                item.revenue,
                                item.ebitda_last_ten_year,
                                item.ebitda_last_nine_year,
                                item.ebitda_last_eight_year,
                                item.ebitda_last_seven_year,
                                item.ebitda_last_six_year,
                                item.ebitda_last_five_year,
                                item.ebitda_last_four_year,
                                item.ebitda_last_three_year,
                                item.ebitda_last_two_year,
                                item.ebitda_last_year,
                                item.ebitda,
                                item.tpat_last_ten_year,
                                item.tpat_last_nine_year,
                                item.tpat_last_eight_year,
                                item.tpat_last_seven_year,
                                item.tpat_last_six_year,
                                item.tpat_last_five_year,
                                item.tpat_last_four_year,
                                item.tpat_last_three_year,
                                item.tpat_last_two_year,
                                item.tpat_last_year,
                                item.tpat,
                                item.npat_last_ten_year,
                                item.npat_last_nine_year,
                                item.npat_last_eight_year,
                                item.npat_last_seven_year,
                                item.npat_last_six_year,
                                item.npat_last_five_year,
                                item.npat_last_four_year,
                                item.npat_last_three_year,
                                item.npat_last_two_year,
                                item.npat_last_year,
                                item.npat,
                                item.total_asset_last_ten_year,
                                item.total_asset_last_nine_year,
                                item.total_asset_last_eight_year,
                                item.total_asset_last_seven_year,
                                item.total_asset_last_six_year,
                                item.total_asset_last_five_year,
                                item.total_asset_last_four_year,
                                item.total_asset_last_three_year,
                                item.total_asset_last_two_year,
                                item.total_asset_last_year,
                                item.total_asset,
                                item.total_equity_last_ten_year,
                                item.total_equity_last_nine_year,
                                item.total_equity_last_eight_year,
                                item.total_equity_last_seven_year,
                                item.total_equity_last_six_year,
                                item.total_equity_last_five_year,
                                item.total_equity_last_four_year,
                                item.total_equity_last_three_year,
                                item.total_equity_last_two_year,
                                item.total_equity_last_year,
                                item.total_equity,
                                item.order,
                            ])
                            if (item.children !== null) {
                                if (item.children.length > 0) {
                                    item.children.map((items, indexs) => {
                                        handlePushChild(items)
                                    })
                                }
                            }
                        })
                        console.log()
                        this.setState({ dataTable, previewTable: true, loading: false, previewDownload: true })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                            if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    this.setState({ dataTable: [], previewTable: false, loading: false, previewDownload: false })
                }
            })
        }    
    }

    async downloadAllData() {
        let {month, periode} = this.state
        console.log(month, periode);
        if (this.state.report.value === 1) {
            // alert("Download MTD Report Coming Soon")
            let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/summary_mtd/export_report?year=${this.state.periode.periode}&&months=${this.state.month.month_id}`
            let sub_null = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/summary_mtd/export_report?year=${this.state.periode.periode}&&months=${this.state.month.month_id}`
            console.log(url);
            let res = await fetch(
                this.state.submissionID == null ? sub_null : url
            )
            res = await res.blob()
            this.setState({ loading: false })
            if (res.size > 0) {
                let url = window.URL.createObjectURL(res);
                let a = document.createElement('a');
                a.href = url;
                a.download = `Report MTD ${month.month_name} ${periode.periode}.xlsx`;
                a.click();
            }
        } else if (this.state.report.value === 2) {
            // alert("Download YTD Report Coming Soon")
            let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/summary_ytd/export_report?year=${this.state.periode.periode}&&months=${this.state.month.month_id}`
            let sub_null = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/summary_ytd/export_report?year=${this.state.periode.periode}&&months=${this.state.month.month_id}`
            console.log(url);
            let res = await fetch(
                this.state.submissionID == null ? sub_null : url
            )
            res = await res.blob()
            this.setState({ loading: false })
            if (res.size > 0) {
                let url = window.URL.createObjectURL(res);
                let a = document.createElement('a');
                a.href = url;
                a.download = `Report YTD ${month.month_name} ${periode.periode}.xlsx`;
                a.click();
            }
        } else if (this.state.report.value === 3) {
            // alert("Download CPSM Report Coming Soon")
            let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/summary_cpsm/export_report?year=${this.state.periode.periode}&&months=${this.state.month.month_id}`
            let sub_null = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/summary_cpsm/export_report?year=${this.state.periode.periode}&&months=${this.state.month.month_id}`
            console.log(url);
            let res = await fetch(
                this.state.submissionID == null ? sub_null : url
            )
            res = await res.blob()
            this.setState({ loading: false })
            if (res.size > 0) {
                let url = window.URL.createObjectURL(res);
                let a = document.createElement('a');
                a.href = url;
                a.download = `Report CPSM ${month.month_name} ${periode.periode}.xlsx`;
                a.click();
            }
        } else if (this.state.report.value === 4) {
            // alert("Download Historical Report Coming Soon")
            let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/summary_historical/export_report?year=${this.state.periode.periode}`
            let sub_null = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/summary_historical/export_report?year=${this.state.periode.periode}`
            console.log(url);
            let res = await fetch(
                this.state.submissionID == null ? sub_null : url
            )
            res = await res.blob()
            this.setState({ loading: false })
            if (res.size > 0) {
                let url = window.URL.createObjectURL(res);
                let a = document.createElement('a');
                a.href = url;
                a.download = `Report Historical ${periode.periode}.xlsx`;
                a.click();
            }
        } else {
            
            // setTimeout(() => {
            //     this.setState({ loading: false })
            // }, 1000);
        }
    }

    render() {

        const loadingComponent = (
            <div style={{ position: 'absolute', zIndex: 110, top: 0, left: 0, width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', background: 'rgba(255,255,255,0.8)' }}>
                <PropagateLoader
                    // css={override}
                    size={20}
                    color={"#274B80"}
                    loading={this.state.loading}
                />
            </div>
        );
        return (
            <div style={{ flex: 1, backgroundColor: '#f8f8f8' }} ref={this.myRef}>
                <div>
                    <div className={"main-color"} style={{ height: 78, display: 'flex', alignItems: 'center', paddingLeft: 20 }}>
                        <Typography style={{ fontSize: '16px', color: 'white' }}>Summary Triputra Group Report</Typography>
                    </div>
                    <div style={{ padding: 20, width: '100%' }}>
                        <Paper style={{ paddingTop: 10 }}>
                            <div style={{ borderBottom: 'solid 1px #c4c4c4' }} >
                                <Typography style={{ fontSize: '12px', color: '#4b4b4b', margin: 10 }}>Financial Summary of Triputra Group</Typography>
                            </div>
                            <div style={{ minWidth: 'max-content', padding: '20px 20px 0px 20px' }}>
                                <div style={{ marginTop: 15 }}>
                                    <Autocomplete
                                        options={this.state.reportType}
                                        getOptionLabel={(option) => titleCase(option.label)}
                                        id="typereport"
                                        onChange={(event, newInputValue) => this.setState({ report: newInputValue, loading: true, previewTable: false }, () => {
                                            let data = this.state.listPeriode.options
                                            let currentYear = new Date().getFullYear()
                                            let periode = (this.state.lastPeriod == "" ? String(Number(currentYear) + 1) : this.state.lastPeriod)
                                            let dateNow = new Date()
                                            dateNow.setMonth(dateNow.getMonth() - 1);
                                            let yearNow = dateNow.getFullYear()
                                            // this.getSubmission()
                                            if (!String(this.state.report.label).toLocaleLowerCase().includes('historical')) {
                                                let index = data.sort((a, b) => a - b).findIndex((val) => val.periode == yearNow)
                                                // console.log(index)
                                                this.setState({periode: data[index]}, () => {
                                                    this.getDataTable()
                                                })
                                            } else {
                                                this.getDataTable()
                                            }
                                            
                                        })}
                                        disableClearable
                                        style={{ width: 250 }}
                                        renderInput={(params) => <TextField {...params} label="Report Type" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.report}
                                    />
                                </div>
                                <div style={{ marginTop: 15 }}>
                                    <Autocomplete
                                        {...this.state.listPeriode}
                                        id="periode"
                                        onChange={(event, newInputValue) => this.setState({ periode: newInputValue, loading: true, previewTable: false }, () => {
                                            // this.getSubmission()
                                            this.getDataTable()
                                        })}
                                        disabled={this.state.intent === 'Home' ? true : false}
                                        disableClearable
                                        style={{ width: 250 }}
                                        renderInput={(params) =>
                                            <TextField {...params} label="Period" margin="normal" style={{ marginTop: 7 }}
                                            />}
                                        value={this.state.periode}
                                    />
                                </div>
                                
                                {(this.state.report != null && !String(this.state.report.label).toLocaleLowerCase().includes('historical')) && <div style={{ marginTop: 15 }}>
                                    <Autocomplete
                                        {...this.state.listMonths}
                                        // getOptionLabel={(option) => titleCase(option.label)}
                                        id="months"
                                        onChange={(event, newInputValue) => this.setState({ month: newInputValue, loading: true, previewTable: false }, () => {
                                            this.getDataTable()
                                        })}
                                        disableClearable
                                        style={{ width: 250 }}
                                        renderInput={(params) => <TextField {...params} label="Months" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.month}
                                    />
                                </div>}
                            </div>
                            <div>
                                <div style={{ display: 'flex', justifyContent: 'space-between', padding: '0px 20px 10px 20px' }}>
                                    <div></div>
                                    {this.state.previewDownload && (
                                        <div style={{ width: '50%', justifyContent: 'flex-end', display: 'flex', flexFlow: 'wrap' }}>
                                            <a data-tip={'Download'} data-for="download">
                                                <button
                                                    style={{
                                                        backgroundColor: 'transparent',
                                                        cursor: 'pointer',
                                                        borderColor: 'transparent',
                                                        margin: 5,
                                                        outline: 'none'
                                                    }}
                                                    onClick={() => this.setState({ loading: true }, () => {
                                                        setTimeout(() => {
                                                            this.downloadAllData()
                                                        }, 100);
                                                    })}
                                                >
                                                    <img src={Images.download} />
                                                </button>
                                            </a>
                                            <ReactTooltip border={true} id="download" place="bottom" type="light" effect="solid" />
                                        </div>
                                    )}
                                </div>
                                {this.state.loading && loadingComponent}
                                {this.state.previewTable && (
                                    <TableSummaryTriputra
                                        width={this.props.width}
                                        height={this.props.height}
                                        open={this.props.open}
                                        month={this.state.month}
                                        type={this.state.report ? this.state.report.value : 1}
                                        dataTable={this.state.dataTable}
                                        periode={this.state.periode ? this.state.periode.periode : null}
                                    />
                                )}
                            </div>
                        </Paper>
                    </div>
                </div>
            </div>
        )
    }
}
