import React, { Component } from 'react'
import { Typography, MenuItem, TextField, AppBar, Paper, Tabs, Tab } 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' },
                { value: 2, label: 'YTD Report' },
                { value: 3, label: 'CPSM Report' },
                { value: 4, label: '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: true })
        this.getPeriode()
        // this.getMonth()
    }

    getDetailUser() {
        let userId = localStorage.getItem(Constant.USER)
        api.create().getDetailUser(userId).then((response) => {
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === 'success') {
                        this.setState({ userCompany: response.data.data.company }, () => {
                            this.getCompanyActive()
                        })
                    }
                }
            }
        })
    }

    getCompanyActive() {
        api.create().getPerusahaanActive().then((response) => {
            // console.log(response);
            if (response.data) {
                if (response.data.status === 'success') {
                    let data = response.data.data
                    let comID = this.state.rawData ? this.state.rawData.company_id : 0
                    let companyData = data.map((item) => {
                        return {
                            company_id: item.company_id,
                            company_name: item.company_name,
                        }
                    })

                    let arrayBaru = []
                    this.state.userCompany.map((item, index) => {
                        let indexID = companyData.findIndex((val) => val.company_id == item)
                        if (indexID !== -1) {
                            arrayBaru.push(companyData[indexID])
                        }
                    })

                    let defaultProps = {
                        options: arrayBaru,
                        getOptionLabel: (option) => titleCase(option.company_name),
                    };
                    let index = arrayBaru.findIndex((val) => val.company_id == comID)
                    this.setState({ listCompany: defaultProps, company: arrayBaru.length < 1 ? companyData[0] : (index == -1 ? arrayBaru[0] : arrayBaru[index]) }, () => {
                        this.getLastPeriod()
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        if (response.data.message.includes("Someone Logged In")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', listCompany: null, company: null })
            }
        })
    }

    getLastPeriod() {
        api.create().getLastPeriod(this.state.company.company_id).then(response => {
            // console.log(response);
            if (response.data.status === "success") {
                this.setState({ lastPeriod: response.data.data.last_periode, latestPeriode: response.data.data.latest_periode }, () => {
                    this.getPeriode()
                })
            }
        })
    }

    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))) {
                                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()
                        // }
                    })
                }
            }
        })
    }

    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.month_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)
                }
            }
        })
    }

    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() {
        let payload = {
            "report_type": this.state.report.value,
            "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) {
            let dbMTD =[]
            api.create().getHierarkiReportMTD(payload).then(response => {
            console.log(response);
            // console.log(payload)
                // let dataTable = []
                if (response.data) {
                    let res = response.data.data
                    const handlePushChild = (item) => {
                        let indexIDzz = dbMTD.findIndex((val) => val[0] === item.company_id)
                        if (indexIDzz === -1) {
                            let mtd_revenue_act = item.mtd_revenue_act = '' ? 0 : Number(item.mtd_revenue_act)
                            let mtd_revenue_mb = item.mtd_revenue_mb = '' ? 0 : Number(item.mtd_revenue_mb)
                            let persenRevMB = 0
                            if (mtd_revenue_mb < 0) {
                                if (mtd_revenue_act >= mtd_revenue_mb) {
                                    persenRevMB = ( mtd_revenue_mb - mtd_revenue_act ) / mtd_revenue_mb + 1
                                } else {
                                    persenRevMB = ( mtd_revenue_mb - mtd_revenue_act ) / mtd_revenue_mb
                                }
                                
                            } else {
                                persenRevMB = mtd_revenue_act / mtd_revenue_mb
                            }

                            let mtd_ebitda_act = item.mtd_ebitda_act = '' ? 0 : Number(item.mtd_ebitda_act)
                            let mtd_ebitda_mb = item.mtd_ebitda_mb = '' ? 0 : Number(item.mtd_ebitda_mb)
                            let persenEbitMB = 0
                            if (mtd_ebitda_mb < 0) {
                                if (mtd_ebitda_act >= mtd_ebitda_mb) {
                                    persenEbitMB = ( mtd_ebitda_mb - mtd_ebitda_act ) / mtd_ebitda_mb + 1
                                } else {
                                    persenEbitMB = ( mtd_ebitda_mb - mtd_ebitda_act ) / mtd_ebitda_mb
                                }
                                
                            } else {
                                persenEbitMB = mtd_ebitda_act / mtd_ebitda_mb
                            }

                            let mtd_tpat_act = item.mtd_tpat_act = '' ? 0 : Number(item.mtd_tpat_act)
                            let mtd_tpat_mb = item.mtd_tpat_mb = '' ? 0 : Number(item.mtd_tpat_mb)
                            let persenTPATMB = 0
                            if (mtd_tpat_mb < 0) {
                                if (mtd_tpat_act >= mtd_tpat_mb) {
                                    persenTPATMB = ( mtd_tpat_mb - mtd_tpat_act ) / mtd_tpat_mb + 1
                                } else {
                                    persenTPATMB = ( mtd_tpat_mb - mtd_tpat_act ) / mtd_tpat_mb
                                }
                                
                            } else {
                                persenTPATMB = mtd_tpat_act / mtd_tpat_mb
                            }

                            let mtd_npat_act = item.mtd_npat_act = '' ? 0 : Number(item.mtd_npat_act)
                            let mtd_npat_mb = item.mtd_npat_mb = '' ? 0 : Number(item.mtd_npat_mb)
                            let persenNPATMB = 0
                            if (mtd_npat_mb < 0) {
                                if (mtd_npat_act >= mtd_npat_mb) {
                                    persenNPATMB = ( mtd_npat_mb - mtd_npat_act ) / mtd_npat_mb + 1
                                } else {
                                    persenNPATMB = ( mtd_npat_mb - mtd_npat_act ) / mtd_npat_mb
                                }
                                
                            } else {
                                persenNPATMB = mtd_npat_act / mtd_npat_mb
                            }

                            let mtd_cf_cfo = item.mtd_cf_cfo = '' ? 0 : Number(item.mtd_cf_cfo)
                            let mtd_cf_cfi = item.mtd_cf_cfi = '' ? 0 : Number(item.mtd_cf_cfi)
                            let mtd_cf_cff = item.mtd_cf_cff = '' ? 0 : Number(item.mtd_cf_cff)
                            let mtd_net_cf = mtd_cf_cfo + mtd_cf_cfi + mtd_cf_cff

                            let mtd_os_bank_loan_ki = item.mtd_os_bank_loan_ki = '' ? 0 : Number(item.mtd_os_bank_loan_ki)
                            let mtd_os_bank_loan_wc = item.mtd_os_bank_loan_wc = '' ? 0 : Number(item.mtd_os_bank_loan_wc)
                            let mtd_os_bank_loan_others = item.mtd_os_bank_loan_others = '' ? 0 : Number(item.mtd_os_bank_loan_others)
                            let mtd_os_bank_loan_total = mtd_os_bank_loan_ki + mtd_os_bank_loan_wc + mtd_os_bank_loan_others

                            let mtd_fr_ar_days = item.mtd_fr_ar_days = '' ? 0 : Number(item.mtd_fr_ar_days)
                            let mtd_fr_inv_days = item.mtd_fr_inv_days = '' ? 0 : Number(item.mtd_fr_inv_days)
                            let mtd_fr_ap_days = item.mtd_fr_ap_days = '' ? 0 : Number(item.mtd_fr_ap_days)
                            let mtd_fr_ccc = mtd_fr_ar_days + mtd_fr_inv_days - mtd_fr_ap_days


                            dbMTD.push([
                                item.company_id,
                                item.parent,
                                item.level,
                                item.company_name,
                                item.mtd_revenue_act,
                                item.mtd_revenue_mb,
                                isNaN(persenRevMB) || persenRevMB == 'Infinity' || persenRevMB == '-Infinity'? (item.mtd_revenue_mb == '' || item.mtd_revenue_mb == 0? -0 : 0) : (item.mtd_revenue_mb == '' || item.mtd_revenue_mb == 0? persenRevMB * -100 : persenRevMB * 100),
                                item.mtd_ebitda_act,
                                item.mtd_ebitda_mb,
                                isNaN(persenEbitMB) || persenEbitMB == 'Infinity' || persenEbitMB == '-Infinity'? (item.mtd_ebitda_mb == '' || item.mtd_ebitda_mb == 0? -0 : 0) : (item.mtd_ebitda_mb == '' || item.mtd_ebitda_mb == 0? persenEbitMB * -100 : persenEbitMB * 100),
                                item.mtd_tpat_act,
                                item.mtd_tpat_mb,
                                isNaN(persenTPATMB) || persenTPATMB == 'Infinity' || persenTPATMB == '-Infinity'? (item.mtd_tpat_mb == '' || item.mtd_tpat_mb == 0? -0 : 0) : (item.mtd_tpat_mb == '' || item.mtd_tpat_mb == 0? persenTPATMB * -100 : persenTPATMB * 100),
                                item.mtd_npat_act,
                                item.mtd_npat_mb,
                                isNaN(persenNPATMB) || persenNPATMB == 'Infinity' || persenNPATMB == '-Infinity'? (item.mtd_npat_mb == '' || item.mtd_npat_mb == 0? -0 : 0) : (item.mtd_npat_mb == '' || item.mtd_npat_mb == 0? persenNPATMB * -100 : persenNPATMB * 100),
                                item.mtd_cf_cfo,
                                item.mtd_cf_cfi,
                                item.mtd_cf_cff,
                                mtd_net_cf,
                                item.mtd_os_bank_loan_ki,
                                item.mtd_os_bank_loan_wc,
                                item.mtd_os_bank_loan_others,
                                mtd_os_bank_loan_total,
                                item.mtd_os_shl,
                                item.mtd_bs_cash_bank,
                                item.mtd_bs_ca,
                                item.mtd_bs_cl,
                                item.mtd_bs_equility,
                                item.mtd_fr_cr,
                                item.mtd_fr_der,
                                item.mtd_fr_debt_ebitda,
                                item.mtd_fr_interest,
                                item.mtd_fr_ar_days,
                                item.mtd_fr_inv_days,
                                item.mtd_fr_ap_days,
                                mtd_fr_ccc,
                                item.order,
                            ])
                        }
                        if (item.children !== null) {
                            if (item.children.length > 0) {
                                item.children.map((items, indexs) => {
                                    handlePushChild(items)
                                })
                            }
                        }
                    }
                    res.map((item, index) => {
                        let mtd_revenue_act = item.mtd_revenue_act = '' ? 0 : Number(item.mtd_revenue_act)
                            let mtd_revenue_mb = item.mtd_revenue_mb = '' ? 0 : Number(item.mtd_revenue_mb)
                            let persenRevMB = 0
                            if (mtd_revenue_mb < 0) {
                                if (mtd_revenue_act >= mtd_revenue_mb) {
                                    persenRevMB = ( mtd_revenue_mb - mtd_revenue_act ) / mtd_revenue_mb + 1
                                } else {
                                    persenRevMB = ( mtd_revenue_mb - mtd_revenue_act ) / mtd_revenue_mb
                                }
                                
                            } else {
                                persenRevMB = mtd_revenue_act / mtd_revenue_mb
                            }

                            let mtd_ebitda_act = item.mtd_ebitda_act = '' ? 0 : Number(item.mtd_ebitda_act)
                            let mtd_ebitda_mb = item.mtd_ebitda_mb = '' ? 0 : Number(item.mtd_ebitda_mb)
                            let persenEbitMB = 0
                            if (mtd_ebitda_mb < 0) {
                                if (mtd_ebitda_act >= mtd_ebitda_mb) {
                                    persenEbitMB = ( mtd_ebitda_mb - mtd_ebitda_act ) / mtd_ebitda_mb + 1
                                } else {
                                    persenEbitMB = ( mtd_ebitda_mb - mtd_ebitda_act ) / mtd_ebitda_mb
                                }
                                
                            } else {
                                persenEbitMB = mtd_ebitda_act / mtd_ebitda_mb
                            }

                            let mtd_tpat_act = item.mtd_tpat_act = '' ? 0 : Number(item.mtd_tpat_act)
                            let mtd_tpat_mb = item.mtd_tpat_mb = '' ? 0 : Number(item.mtd_tpat_mb)
                            let persenTPATMB = 0
                            if (mtd_tpat_mb < 0) {
                                if (mtd_tpat_act >= mtd_tpat_mb) {
                                    persenTPATMB = ( mtd_tpat_mb - mtd_tpat_act ) / mtd_tpat_mb + 1
                                } else {
                                    persenTPATMB = ( mtd_tpat_mb - mtd_tpat_act ) / mtd_tpat_mb
                                }
                                
                            } else {
                                persenTPATMB = mtd_tpat_act / mtd_tpat_mb
                            }

                            let mtd_npat_act = item.mtd_npat_act = '' ? 0 : Number(item.mtd_npat_act)
                            let mtd_npat_mb = item.mtd_npat_mb = '' ? 0 : Number(item.mtd_npat_mb)
                            let persenNPATMB = 0
                            if (mtd_npat_mb < 0) {
                                if (mtd_npat_act >= mtd_npat_mb) {
                                    persenNPATMB = ( mtd_npat_mb - mtd_npat_act ) / mtd_npat_mb + 1
                                } else {
                                    persenNPATMB = ( mtd_npat_mb - mtd_npat_act ) / mtd_npat_mb
                                }
                                
                            } else {
                                persenNPATMB = mtd_npat_act / mtd_npat_mb
                            }

                            let mtd_cf_cfo = item.mtd_cf_cfo = '' ? 0 : Number(item.mtd_cf_cfo)
                            let mtd_cf_cfi = item.mtd_cf_cfi = '' ? 0 : Number(item.mtd_cf_cfi)
                            let mtd_cf_cff = item.mtd_cf_cff = '' ? 0 : Number(item.mtd_cf_cff)
                            let mtd_net_cf = mtd_cf_cfo + mtd_cf_cfi + mtd_cf_cff

                            let mtd_os_bank_loan_ki = item.mtd_os_bank_loan_ki = '' ? 0 : Number(item.mtd_os_bank_loan_ki)
                            let mtd_os_bank_loan_wc = item.mtd_os_bank_loan_wc = '' ? 0 : Number(item.mtd_os_bank_loan_wc)
                            let mtd_os_bank_loan_others = item.mtd_os_bank_loan_others = '' ? 0 : Number(item.mtd_os_bank_loan_others)
                            let mtd_os_bank_loan_total = mtd_os_bank_loan_ki + mtd_os_bank_loan_wc + mtd_os_bank_loan_others

                            let mtd_fr_ar_days = item.mtd_fr_ar_days = '' ? 0 : Number(item.mtd_fr_ar_days)
                            let mtd_fr_inv_days = item.mtd_fr_inv_days = '' ? 0 : Number(item.mtd_fr_inv_days)
                            let mtd_fr_ap_days = item.mtd_fr_ap_days = '' ? 0 : Number(item.mtd_fr_ap_days)
                            let mtd_fr_ccc = mtd_fr_ar_days + mtd_fr_inv_days - mtd_fr_ap_days

                        dbMTD.push([
                            item.company_id,
                            item.parent,
                            item.level,
                            item.company_name,
                            item.mtd_revenue_act,
                            item.mtd_revenue_mb,
                            isNaN(persenRevMB) || persenRevMB == 'Infinity' || persenRevMB == '-Infinity'? (item.mtd_revenue_mb == '' || item.mtd_revenue_mb == 0? -0 : 0) : (item.mtd_revenue_mb == '' || item.mtd_revenue_mb == 0? persenRevMB * -100 : persenRevMB * 100),
                            item.mtd_ebitda_act,
                            item.mtd_ebitda_mb,
                            isNaN(persenEbitMB) || persenEbitMB == 'Infinity' || persenEbitMB == '-Infinity'? (item.mtd_ebitda_mb == '' || item.mtd_ebitda_mb == 0? -0 : 0) : (item.mtd_ebitda_mb == '' || item.mtd_ebitda_mb == 0? persenEbitMB * -100 : persenEbitMB * 100),
                            item.mtd_tpat_act,
                            item.mtd_tpat_mb,
                            isNaN(persenTPATMB) || persenTPATMB == 'Infinity' || persenTPATMB == '-Infinity'? (item.mtd_tpat_mb == '' || item.mtd_tpat_mb == 0? -0 : 0) : (item.mtd_tpat_mb == '' || item.mtd_tpat_mb == 0? persenTPATMB * -100 : persenTPATMB * 100),
                            item.mtd_npat_act,
                            item.mtd_npat_mb,
                            isNaN(persenNPATMB) || persenNPATMB == 'Infinity' || persenNPATMB == '-Infinity'? (item.mtd_npat_mb == '' || item.mtd_npat_mb == 0? -0 : 0) : (item.mtd_npat_mb == '' || item.mtd_npat_mb == 0? persenNPATMB * -100 : persenNPATMB * 100),
                            item.mtd_cf_cfo,
                            item.mtd_cf_cfi,
                            item.mtd_cf_cff,
                            mtd_net_cf,
                            item.mtd_os_bank_loan_ki,
                            item.mtd_os_bank_loan_wc,
                            item.mtd_os_bank_loan_others,
                            mtd_os_bank_loan_total,
                            item.mtd_os_shl,
                            item.mtd_bs_cash_bank,
                            item.mtd_bs_ca,
                            item.mtd_bs_cl,
                            item.mtd_bs_equility,
                            item.mtd_fr_cr,
                            item.mtd_fr_der,
                            item.mtd_fr_debt_ebitda,
                            item.mtd_fr_interest,
                            item.mtd_fr_ar_days,
                            item.mtd_fr_inv_days,
                            item.mtd_fr_ap_days,
                            mtd_fr_ccc,
                            item.order,
                        ])
                        if (item.children !== null) {
                            if (item.children.length > 0) {
                                item.children.map((items, indexs) => {
                                    handlePushChild(items)
                                })
                            }
                        }
                    })
                    console.log(dbMTD)
                    this.setState({ dataTable: dbMTD, previewTable: true, loading: false, previewDownload: true })
                } 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) {
                    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,
                                item.parent,
                                item.level,
                                item.company_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,
                            ])
                        }
                        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,
                            item.parent,
                            item.level,
                            item.company_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,
                        ])
                        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({ dataTable: [], previewTable: false, loading: false, previewDownload: false })
                }
            })
        } else if (this.state.report.value === 3) {
            // api.create().getReportHierarkiPL(payload).then(response => {
            //     // console.log(response);
            //     if (response.data) {
                    let dataTable = []
            //         console.log(response)
            //         let res = response.data.data
            //         const handlePushChild = (item) => {
            //             dataTable.push([
            //                 item.type_report_id,
            //                 item.id,
            //                 item.parent,
            //                 item.formula,
            //                 item.level,
            //                 item.description,
            //                 item.profit_detail.total_actual_before === null ? "0" : item.profit_detail.total_actual_before === "" ? "0" : item.profit_detail.total_actual_before,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.january, formula: item.profit_detail.january_formula } : item.profit_detail.january,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.february, formula: item.profit_detail.february_formula } : item.profit_detail.february,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.march, formula: item.profit_detail.march_formula } : item.profit_detail.march,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.april, formula: item.profit_detail.april_formula } : item.profit_detail.april,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.may, formula: item.profit_detail.may_formula } : item.profit_detail.may,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.june, formula: item.profit_detail.june_formula } : item.profit_detail.june,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.july, formula: item.profit_detail.july_formula } : item.profit_detail.july,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.august, formula: item.profit_detail.august_formula } : item.profit_detail.august,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.september, formula: item.profit_detail.september_formula } : item.profit_detail.september,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.october, formula: item.profit_detail.october_formula } : item.profit_detail.october,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.november, formula: item.profit_detail.november_formula } : item.profit_detail.november,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.december, formula: item.profit_detail.december_formula } : item.profit_detail.december,
            //                 item.profit_detail.total_current_year,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? 0 : item.profit_detail.total_next_year,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? 0 : item.profit_detail.total_more_year,
            //                 item.order,
            //                 item.condition_it_should_be,
            //                 item.condition_if_wrong,
            //                 item.profit_detail.forecast_formula == null ? [] : item.profit_detail.forecast_formula
            //             ])

            //             if (item.children !== null) {
            //                 if (item.children.length > 0) {
            //                     item.children.map((items, indexs) => {
            //                         handlePushChild(items)
            //                     })
            //                 }
            //             }
            //         }
            //         res.map((item, index) => {
            //             dataTable.push([
            //                 item.type_report_id,
            //                 item.id,
            //                 item.parent,
            //                 item.formula,
            //                 item.level,
            //                 item.description,
            //                 item.profit_detail.total_actual_before === null ? "0" : item.profit_detail.total_actual_before === "" ? "0" : item.profit_detail.total_actual_before,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.january, formula: item.profit_detail.january_formula } : item.profit_detail.january,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.february, formula: item.profit_detail.february_formula } : item.profit_detail.february,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.march, formula: item.profit_detail.march_formula } : item.profit_detail.march,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.april, formula: item.profit_detail.april_formula } : item.profit_detail.april,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.may, formula: item.profit_detail.may_formula } : item.profit_detail.may,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.june, formula: item.profit_detail.june_formula } : item.profit_detail.june,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.july, formula: item.profit_detail.july_formula } : item.profit_detail.july,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.august, formula: item.profit_detail.august_formula } : item.profit_detail.august,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.september, formula: item.profit_detail.september_formula } : item.profit_detail.september,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.october, formula: item.profit_detail.october_formula } : item.profit_detail.october,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.november, formula: item.profit_detail.november_formula } : item.profit_detail.november,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail.december, formula: item.profit_detail.december_formula } : item.profit_detail.december,
            //                 item.profit_detail.total_current_year,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? 0 : item.profit_detail.total_next_year,
            //                 item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? 0 : item.profit_detail.total_more_year,
            //                 item.order,
            //                 item.condition_it_should_be,
            //                 item.condition_if_wrong,
            //                 item.profit_detail.forecast_formula == null ? [] : item.profit_detail.forecast_formula
            //             ])
            //             if (item.children !== null) {
            //                 if (item.children.length > 0) {
            //                     item.children.map((items, indexs) => {
            //                         handlePushChild(items)
            //                     })
            //                 }
            //             }
            //         })
                    this.setState({ dataTable, previewTable: true, loading: false, previewDownload: true })
            //     } 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) {
                //     let res = response.data.data
                //     const handlePushChild = (item) => {
                //         let indexIDzz = dataTable.findIndex((val) => val[1] === item.id)
                //         if (indexIDzz === -1) {
                //             dataTable.push([
                //                 item.type_report_id,
                //                 item.id,
                //                 item.parent,
                //                 item.formula,
                //                 item.level,
                //                 item.description,
                //                 item.ratio.total_actual_before === null ? "0.0" : item.ratio.total_actual_before === "" ? "0.0" : item.ratio.total_actual_before,
                //                 Number(item.ratio.january).toFixed(1),
                //                 Number(item.ratio.february).toFixed(1),
                //                 Number(item.ratio.march).toFixed(1),
                //                 Number(item.ratio.april).toFixed(1),
                //                 Number(item.ratio.may).toFixed(1),
                //                 Number(item.ratio.june).toFixed(1),
                //                 Number(item.ratio.july).toFixed(1),
                //                 Number(item.ratio.august).toFixed(1),
                //                 Number(item.ratio.september).toFixed(1),
                //                 Number(item.ratio.october).toFixed(1),
                //                 Number(item.ratio.november).toFixed(1),
                //                 Number(item.ratio.december).toFixed(1),
                //                 Number(item.ratio.total_current_year).toFixed(1),
                //                 Number(item.ratio.total_next_year).toFixed(1),
                //                 Number(item.ratio.total_more_year).toFixed(1),
                //                 item.order,
                //                 item.condition_it_should_be,
                //                 item.condition_if_wrong
                //             ])
                //         }
                //         if (item.children !== null) {
                //             if (item.children.length > 0) {
                //                 item.children.map((items, indexs) => {
                //                     handlePushChild(items)
                //                 })
                //             }
                //         }
                //     }
                //     res.map((item, index) => {
                //         dataTable.push([
                //             item.type_report_id,
                //             item.id,
                //             item.parent,
                //             item.formula,
                //             item.level,
                //             item.description,
                //             item.ratio.total_actual_before === null ? "0.0" : item.ratio.total_actual_before === "" ? "0.0" : item.ratio.total_actual_before,
                //             Number(item.ratio.january).toFixed(1),
                //             Number(item.ratio.february).toFixed(1),
                //             Number(item.ratio.march).toFixed(1),
                //             Number(item.ratio.april).toFixed(1),
                //             Number(item.ratio.may).toFixed(1),
                //             Number(item.ratio.june).toFixed(1),
                //             Number(item.ratio.july).toFixed(1),
                //             Number(item.ratio.august).toFixed(1),
                //             Number(item.ratio.september).toFixed(1),
                //             Number(item.ratio.october).toFixed(1),
                //             Number(item.ratio.november).toFixed(1),
                //             Number(item.ratio.december).toFixed(1),
                //             Number(item.ratio.total_current_year).toFixed(1),
                //             Number(item.ratio.total_next_year).toFixed(1),
                //             Number(item.ratio.total_more_year).toFixed(1),
                //             item.order,
                //             item.condition_it_should_be,
                //             item.condition_if_wrong
                //         ])
                //         if (item.children !== null) {
                //             if (item.children.length > 0) {
                //                 item.children.map((items, indexs) => {
                //                     handlePushChild(items)
                //                 })
                //             }
                //         }
                //     })
                    this.setState({ dataTable, previewTable: true, loading: false, previewDownload: true })
                // } else {
                //     this.setState({ dataTable: [], previewTable: false, loading: false, previewDownload: false })
                // }
            })
        }    
    }

    async downloadAllData() {
        if (this.state.report.value === 1) {
            alert("Download MTD Report Coming Soon")
            // let res = await fetch(
            //     `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/db_report/export_master_budget?submission_id=${this.state.submissionID === null ? "" : this.state.submissionID}&&report_id=${this.state.report.value}&&company_id=${this.state.company.company_id}&&year=${this.state.periode.periode}&&revision=${this.state.lastRevision}`
            // )
            // 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 DB Profit & Loss Detail.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/db_report/export_master_budget?submission_id=${this.state.submissionID}&&report_id=${this.state.report.value}&&company_id=${this.state.company.company_id}&&year=${this.state.periode.periode}&&revision=${this.state.lastRevision}`
            // let sub_null = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/db_report/export_master_budget?submission_id=&&report_id=${this.state.report.value}&&company_id=${this.state.company.company_id}&&year=${this.state.periode.periode}&&revision=${this.state.lastRevision}`
            // // 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 DB Balance Sheet.xlsx';
            //     a.click();
            // }
        } else if (this.state.report.value === 3) {
            alert("Download CPSM Report Coming Soon")
            // let res = await fetch(
            //     `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/db_report_detail/export_master_budget?submission_id=${this.state.submissionID === null ? "" : this.state.submissionID}&&report_id=${this.state.report.value}&&company_id=${this.state.company.company_id}&&year=${this.state.periode.periode}&&revision=${this.state.lastRevision}`
            // )
            // 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 DB Profit & Loss.xlsx';
            //     a.click();
            // }
        } else if (this.state.report.value === 4) {
            alert("Download Historical Report Coming Soon")
            // let res = await fetch(
            //     `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/db_report_detail/export_master_budget?submission_id=${this.state.submissionID === null ? "" : this.state.submissionID}&&report_id=${this.state.report.value}&&company_id=${this.state.company.company_id}&&year=${this.state.periode.periode}&&revision=${this.state.lastRevision}`
            // )
            // 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 DB Financial Ratio.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 }, () => {
                                            // this.getSubmission()
                                            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>
                                <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: false }, () => {
                                                        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>
        )
    }
}