import React, { Component } from 'react';
import { Typography, Paper, TextField, MenuItem, Select, FormControlLabel, Snackbar, withStyles, createMuiTheme, MuiThemeProvider, Checkbox, Input } from '@material-ui/core';
import MUIDataTable from 'mui-datatables';
import Images from '../../assets/Images';
import api from '../../api';
import Autocomplete from '@material-ui/lab/Autocomplete';
import { titleCase } from '../../library/Utils';
import { ExcelRenderer } from 'react-excel-renderer';
import UploadFile from "../../library/Upload";
import { format } from 'date-fns';
import BalanceSheetMR from './BalanceSheetMR';
import ProfitLossMR from './ProfitLossMR';
import TaxPlanningMR from './TaxPlanningMR';
import FixedAssetsMovementMR from './FixedAssetsMovementMR';
import ListOfCreditFacilities from './ListOfCreditFacilitiesMR'
import { PropagateLoader } from 'react-spinners';
import MuiAlert from '@material-ui/lab/Alert';
import Constant from '../../library/Constant';
import OperatingIndicatorMR from './OperatingIndicatorMR';
import CorporateAnnualTargetMR from './CorporateAnnualTargetMR';
import CashFlowMR from './CashFlowMR';
import { DatePicker } from '@material-ui/pickers';
import moment from 'moment';
import * as R from 'ramda'
import { PhotoSizeSelectLargeTwoTone, ThreeSixty } from '@material-ui/icons';
import { startTransition } from 'react';

var ct = require("../../library/CustomTable");
const getMuiTheme = () => createMuiTheme(ct.customTable6());

const Alert = withStyles({
})((props) => <MuiAlert elevation={6} variant="filled" {...props} />);

const CustomCheckbox = withStyles({
    root: {
        color: '#5198ea',
        '&$checked': {
            color: '#5198ea',
        },
    },
    checked: {},
})((props) => <Checkbox color="default" {...props} />);

export default class MonthlyReport extends Component {
    constructor(props) {
        super(props)
        this.state = {
            perusahaan: 'TAP Group',
            listRevision: null,
            revision: null,
            visibleMonthlyReport: true,
            visibleBS: false,
            listPeriode: null,
            periode: null,
            listMonth: null,
            month: null,
            listCompany: null,
            company: null,
            report_id: null,
            visiblePL: false,
            visibleFAM: false,
            visibleCAT: false,
            visibleOI: false,
            visibleCF: false,
            visibleUpload: false,
            lastRevision: 0,
            loading: false,
            alert: false,
            tipeAlert: '',
            messageAlert: '',
            btnCreate: false,
            loadview: false,
            submittedOnly: false,
            company_active: null,
            company_submit: null,
            still_approver: false,
            status: '',
            lastStatus: '',
            approverTrue: false,
            listStatus: [],
            selectedStatus: [],
            detailRevisiCheck: [],
            isApprovedMB: false,
            textRevision: '',
            dbCF: [],
            dbPL: [],
            PLBSFAMSubmitted: false,
            PLID: null,
            monthHome: null,
            listApprover: null,
            approver: null,
            isAdmin: false,
            selectReport: [],
            isCheckAll: false,
            downloadedFileReportId: null,
            arrayReport: [],
            popupDownload: false,
            defaultCurrency: null,
            currency: [],
            visibleAlertSave: false,
            dataCurrency: [
                {
                    "id": 1,
                    "value": "IDR"
                },
                {
                    "id": 2,
                    "value": "USD",
                }
            ],

            dataTableCAT: [],
            dataTableRevisionCAT: [],
            dataForRevisionCAT: [],
            rowDataFinance: [],
            rowDataCAT: [],
            submitterCAT: null,
            approverIDCAT: null,
            picCAT: null,
            btnApproveCAT: false,
            lastStatusCat: null,
            rowData: [],
            dataTableHistoryCAT: [],
            visibleTableHistoryCAT: false,
            isApproverFinance: false,
            isApproverCAT: false,
            currentMasterReportTypeId: null,
            listReportTypeId: [],
            listAttachmentCAT: [],
            listAttachment: [],
        }
        this.myRef = React.createRef()
        this.fileHandler = this.fileHandler.bind(this);
    }

    scrollToMyRef = () => window.scrollTo(0, this.myRef.current.offsetTop)

    getPermission() {
        let payload = {
            menu: "monthly report"
        }
        api.create().getPermission(payload).then(response => {
            console.log(response)
            if (response.data) {
                if (response.data.status === "success") {
                    this.setState({
                        btnCreate: response.data.data.create,
                        btnEdit: response.data.data.edit
                    }, () => {
                        this.getChecApprover()
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        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' })
            }
        })
    }

    componentDidMount() {
        // this.getPermission()
        this.setState({ loading: true })
        this.props.selectIndex('Monthly Report')
        if (this.props.location.state !== undefined) {
            console.log(this.props);
            if (this.props.location.state.month != null || this.props.location.state.month != undefined) {
                this.setState({ monthHome: this.props.location.state.month })
            }
            this.setState({ userType: this.props.location.state.userType, intent: 'Home', lastPeriod: this.props.location.state.rawData.periode, rawData: this.props.location.state.rawData }, () => {
                this.getPermission()
            })
        } else {
            this.getPermission()
        }
        // console.log(this.props)
        // this.getCompanyActive()
        // this.getCompanySubmitted()
        // console.log(a)
    }

    getChecApprover() {
        let listStatus1 = [
            { name: 'Open', value: 'not-yet' },
            { name: 'Submitted', value: 'approval_review' },
            { name: 'Waiting for Review / Approval', value: 'approval_proccess' },
            // {name: 'Waiting for Approval', value: 'approval_proccess'},
            // {name: 'Revision', value: 'revision'},
            { name: 'Approved', value: 'approved' },
        ]

        let listStatus2 = [
            { name: 'Open', value: 'not-yet' },
            { name: 'Submitted', value: 'approval_review' },
            // {name: 'Revision', value: 'revision'},
            { name: 'Approved', value: 'approved' },
        ]

        api.create().checkApproverMonthly().then(response => {
            console.log(response)
            if (response.data) {
                if (response.data.status === "success") {
                    if (response.data.data.is_approver === true) {
                        this.setState({ isApprover: true, isApproverFinance: response.data.data.is_finance, isApproverCAT: response.data.data.is_cat, checkApprover: true, still_approver: true, approverTrue: true, listStatus: listStatus1, selectedStatus: listStatus1 }, () => {
                            // if (this.state.submittedOnly) {
                            this.getMonth()
                            // } else {
                            //     this.getCompanyActive()
                            // }
                        })
                    } else {
                        this.setState({ isApprover: false, isApproverFinance: false, isApproverCAT: false, checkApprover: false, still_approver: false, approverTrue: false, listStatus: listStatus2, selectedStatus: listStatus2 }, () =>
                            this.getMonth())
                        // this.getCompanyActive())
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        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' })
            }
        })
    }

    getReportAttachment() {
        this.state.listReportTypeId.forEach((master_report_type_id) => {
            let payload = {
                "company_id": this.state.company.company_id,
                "periode": this.state.periode.periode,
                "revision": this.state.revision.revision,
                "months": this.state.month.month_id,
                master_report_type_id
            }
            api.create().getMontlyReportAtt(payload).then(response => {
                if (response.data) {
                    if (response.data.status === "success") {
                        this.setState({ [master_report_type_id === 2 ? 'listAttachmentCAT' : 'listAttachment']: response.data.data })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            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.data.message, tipeAlert: 'error' })
                }
            })
        })
    }

    getReport() {
        let payload = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "report_type": "Monthly Report",
            "months": this.state.month.month_id,
            "currency_id": this.state.defaultCurrency.id
        }
        api.create().getMonthlyReport(payload).then(response => {
            console.log(response);
            if (response.data) {
                if (response.data.status === "success") {
                    const listData = response?.data?.data || []
                    let dataTable = listData.map((item, index) => {
                        let indexC = String(item.current_status).toLocaleUpperCase().indexOf('C')
                        let status_approv = ''
                        if (String(item.current_status).toLocaleUpperCase().includes('CC')) {
                            status_approv = `${String(item.current_status).substr(0, indexC)}${String(item.current_status).substr(indexC + 1, String(item.current_status).length)}`
                        } else {
                            status_approv = String(item.current_status)
                        }
                        return [
                            item.number,
                            item.report_name === "CAT" ? "Corporate Annual Target" : item.report_name,
                            item.revision,
                            this.state.isApprovedMB ? ((item?.master_report_type_id === 2 ? this.state.lastStatusCat : this.state.lastStatus) === 'APPROVED' ? 'CLOSED' : this.state.isSubmit === false ? "CLOSED" : status_approv) : "CLOSED",
                            item.report_id,
                            // item.is_can_upload,
                            item.report_name === "Cash Flow" ? item.is_can_upload : (Number(item.revision) > 0 ? (item.current_status === "not-yet" ? false : item.is_can_upload) : item.is_can_upload),
                            item.revision
                        ]
                    })

                    const transformRevision = (rows = []) =>
                        rows
                            .filter(item => item.report_name !== 'Cash Flow')
                            .map(item => [
                                item.report_id,
                                item.report_name === 'CAT'
                                    ? 'Corporate Annual Target'
                                    : item.report_name,
                                '',
                                item.number,
                            ])
                    const [rawCAT, resultDataTableFinance] = (dataTable ?? []).reduce(
                        (acc, item) => {
                            acc[item[1] === 'Corporate Annual Target' ? 0 : 1].push(item)
                            return acc
                        },
                        [[], []]
                    )
                    const [rowDataTableCAT, rowDataTableFinance] = (response?.data?.data ?? []).reduce(
                        (acc, item) => {
                            acc[item.report_name === 'CAT' ? 0 : 1].push(item)
                            return acc
                        },
                        [[], []]
                    )
                    const resultDataTableCAT = rawCAT.map((item, i) => [
                        i + 1,
                        ...item.slice(1),
                    ])

                    const rowDataFinance = listData.filter(
                        item => item.master_report_type_id === 1
                    );

                    const rowDataCAT = listData.filter(
                        item => item.master_report_type_id === 2
                    );
                    const dataTableRevisionCAT = transformRevision(rowDataTableCAT)
                    const dataTableRevision = transformRevision(rowDataTableFinance)
                    // console.log(dataTable);
                    this.setState({
                        dataTable: resultDataTableFinance, dataTableCAT: resultDataTableCAT,
                        rowDataFinance,
                        rowDataCAT,
                        rowData: listData,
                        dataTableRevision: dataTableRevision,
                        dataForRevision: rowDataTableFinance,
                        dataTableRevisionCAT: dataTableRevisionCAT,
                        dataForRevisionCAT: rowDataTableCAT,
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        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' })
            }
        })
    }

    getCompanyActive() {
        api.create().getPerusahaanActive().then((response) => {
            if (response.data) {
                if (response.data.status === 'success') {
                    let data = response.data.data
                    let companyData = data.map((item) => {
                        return {
                            company_id: item.company_id,
                            company_name: item.company_name,
                        }
                    })
                    let defaultProps = {
                        options: companyData,
                        getOptionLabel: (option) => titleCase(option.company_name),
                    };
                    this.setState({ listCompany: defaultProps, company: companyData[0], company_active: defaultProps }, () => {
                        this.getMonth()
                        this.getCurrency(this.state.company.company_id)
                        // console.log(this.state.company_active)
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        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.data.message, tipeAlert: 'error' })
            }
        })
    }

    getMonth() {
        api.create().getMonthTransaction().then(response => {
            let dateNow = new Date()
            dateNow.setMonth(dateNow.getMonth() - 1);
            let month = format(dateNow, 'MMMM')
            console.log(response);
            if (response.data) {
                if (response.data.status === "success") {
                    console.log(response);
                    let data = response.data.data
                    let monthData = data.map((item) => {
                        return {
                            month_id: item.id,
                            month_value: String(item.month_name).substr(0, 3)
                        }
                    })
                    let defaultProps = {
                        options: monthData,
                        getOptionLabel: (option) => option.month_value,
                    };
                    let index = data.findIndex((val) => val.month_name == month)
                    console.log(index);
                    let indexMonthHome = -1
                    if (this.state.monthHome != null) {
                        indexMonthHome = monthData.findIndex((val) => val.month_id == this.state.monthHome.month_id)
                    }
                    console.log(indexMonthHome)
                    this.setState({ listMonth: defaultProps, month: indexMonthHome == -1 ? (index == -1 ? monthData[0] : monthData[index]) : monthData[indexMonthHome] }, () => {
                        // if (this.state.isApprover === true) {
                        //     if (this.state.submittedOnly) {
                        //         console.log('masuk cuk')
                        //         this.getPeriode()
                        //     } else {
                        //         this.getLastPeriod()
                        //     }
                        // } else {
                        // this.getLastPeriod()
                        this.getPeriode()
                        // }
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        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.data.message, tipeAlert: 'error' })
            }
        })
    }

    getLastPeriod() {
        api.create().getLastPeriodMonthly(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 => {
            console.log(response)
            let currentYear = new Date().getFullYear()
            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)
                            // }
                            if ((item >= 2000) && (item == currentYear || item <= currentYear)) {
                                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)) : this.state.lastPeriod === undefined ? String(Number(currentYear)) : this.state.lastPeriod)
                    let dateNow = new Date()
                    dateNow.setMonth(dateNow.getMonth() - 1);
                    let yearNow = dateNow.getFullYear()
                    // let indexMonthMR = MR.findIndex((val) => val.value == yearNow)
                    // console.log(yearNow)
                    let index = data.sort((a, b) => a - b).findIndex((val) => val == yearNow)
                    // console.log(data)
                    // console.log(this.state.lastPeriod)
                    // console.log(periodeData)
                    // console.log(index)
                    this.setState({ listPeriode: defaultProps, periode: index === -1 ? periodeData[0] : periodeData[index] }, () => {
                        // if (this.state.isApprover === true && this.state.submittedOnly) {
                        this.getDetailUser()
                        // this.getCompanySubmitted()
                        //     console.log('masuk')
                        // } else {
                        // this.getRevision()
                        // }
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        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.data.message, tipeAlert: 'error' })
            }
        })
    }

    getCurrency(companyID) {
        console.log(companyID);
        api.create().getDetailPerusahaan(companyID).then(response => {
            console.log(response);
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === "success") {
                        let data = response.data.data
                        let datas = []
                        if (response.data.data.currency.length > 0) {
                            response.data.data.currency.map((item) => {
                                // console.log(item);
                                datas.push({
                                    id: item.currencyId,
                                    value: item.currencyName
                                })

                            })
                        }
                        let index = datas.findIndex((val) => val.id == response.data.data.default_currency)
                        this.setState({
                            defaultCurrencyID: response.data.data.default_currency,
                            currency: datas,
                            defaultCurrency: index == -1 ? null : datas[index]
                        })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            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.data.message, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }

        })
    }

    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.getRole(response.data.data.role_id)
                        this.setState({ userCompany: response.data.data.company }, () => {
                            this.getCompanySubmitted()
                        })
                    }
                }
            }
        })
    }

    getRole(id) {
        api.create().getDetailRole(id).then((response) => {
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === 'success') {
                        // this.setState({ tempData: response.data.data, privileges: response.data.data.privileges })
                        // // // console.log(response.data.data)
                        if (String(response.data.data.role_name).toLocaleLowerCase() == 'superadmin') {
                            this.setState({ isAdmin: true })
                        }
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            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.data.message, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    getCompanySubmitted() {
        let selectedStatus = this.state.selectedStatus.map((item) => {
            return item.value
        })
        let body = {
            "periode": this.state.periode.periode,
            "months": this.state.month.month_id,
            "status": selectedStatus
        }
        // this.setState({ isApprovedMB: true })
        api.create().getCompanySubmittedMonthly(body).then(response => {
            console.log(response);
            if (response.data) {
                if (response.data.status === 'success') {
                    if (response.data.data.length > 0) {
                        let data = response.data.data
                        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])
                            }
                        })

                        if (arrayBaru.length > 0) {
                            arrayBaru = arrayBaru.sort((a, b) => a.company_name.localeCompare(b.company_name))
                        }
                        let defaultProps = {
                            options: arrayBaru,
                            getOptionLabel: (option) => titleCase(option.company_name),
                        }
                        let indexID = null
                        if (this.state.rawData !== undefined) {
                            indexID = arrayBaru.findIndex((val) => val.company_id == this.state.rawData.company_id)
                        }
                        // console.log(response.data.data.length)
                        this.setState({ listCompany: defaultProps, company: indexID == null ? arrayBaru[0] : arrayBaru[indexID], company_submit: defaultProps }, () => {
                            console.log(this.state.company)
                            if (response.data.data.length > 0) {
                                this.getRevision()
                                this.getCurrency(this.state.company.company_id)
                            } else {
                                // console.log(this.state.listCompany)
                                // console.log(this.state.company_submit)
                                this.setState({ listRevision: null, revision: null, dataTable: [], dataTableCAT: [], lastRevision: "", visibleTableHistory: false, visibleTableHistoryCAT: false })
                            }
                            //
                        })
                    } else {
                        this.setState({ listRevision: null, revision: null, listCompany: null, company: null, dataTable: [], dataTableCAT: [], lastRevision: "", visibleTableHistory: false, visibleTableHistoryCAT: false, loading: false }, () => {
                            document.body.style.overflow = 'unset';
                        })
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        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', listCompany: null, company: null })
            }
        })
    }

    onClickClose() {
        this.setState({})
    }

    getRevision() {
        this.setState({ selectReport: [], isCheckAll: false }, () => {
            let payload = {
                "company_id": this.state.company.company_id,
                "periode": this.state.periode.periode
            }
            api.create().getRevision(payload).then(response => {
                console.log(response);
                if (response.data) {
                    if (response.data.status === "success") {
                        let data = response.data.data
                        let revisionData = data.map((item) => {
                            return {
                                revision: item,
                            }
                        })
                        let defaultProps = {
                            options: revisionData,
                            getOptionLabel: (option) => option.revision,
                        };
                        this.setState({ listRevision: defaultProps, revision: revisionData[0] }, () => {
                            this.getMonthlyReportID()
                        })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            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.data.message, tipeAlert: 'error' })
                }
            })
        })
    }

    getMonthlyReportID(type) {
        this.setState({ selectReport: [], isCheckAll: false }, () => {
            const _lastStatus = this.getLastStatus()
            let payload = {
                "company_id": this.state.company.company_id,
                "periode": this.state.periode.periode,
                "months": this.state.month.month_id,
                "is_approver": this.state.isAdmin && _lastStatus === 'WAITING FOR APPROVAL' ? false : this.state.isApprover
            }
            this.setState({ visibleTableHistory: false })
            api.create().getMonthlyReportID(payload).then(response => {
                console.log(response);
                if (response.data) {
                    if (response.data.status === 'success') {
                        const uniqueTypeIds =
                        this.state.rowData?.length
                            ? [...new Set(this.state.rowData.map(item => item.master_report_type_id))]
                            : [1, 2];
                        this.setState({
                            submitter: response.data.data.submitter_finance,
                            submitterCAT: response.data.data.submitter_cat,
                            approverID: response.data.data.finance_approve_id,
                            approverIDCAT: response.data.data.cat_approve_id,
                            pic: response.data.data.approver_finance == null ? '' : response.data.data.approver_finance,
                            picCAT: response.data.data.approver_cat == null ? '' : response.data.data.approver_cat,
                            lastStatus: response.data.data.last_status_finance === null ? 'SUBMIT' : response.data.data.last_status_finance,
                            lastStatusCat: response.data.data.last_status_cat === null ? 'SUBMIT' : response.data.data.last_status_cat,
                            lastRevision: response.data.data.last_revision,
                            btnApprove: response.data.data.is_submit_finance,
                            btnApproveCAT: response.data.data.is_submit_cat,
                            monthlyReportId: response.data.data ? response.data.data.monthly_report_id : null,
                            isApprovedMB: response.data.data.is_approved_master_budget,
                            textRevision: response.data.data.text_revision,
                            listReportTypeId: uniqueTypeIds
                        }, () => {
                            // // console.log(this.state.lastStatus);
                            this.historyApproval()
                            this.getLatestPeriodSubmit()
                            if (this.state.isAdmin) {
                                console.log('masuk')
                                api.create().getListApprover('monthly_report', this.state.monthlyReportId).then((response) => {
                                    console.log(response)
                                    if (response.data.data) {
                                        let dataListApprover = []
                                        response.data.data.map((item, index) => {
                                            dataListApprover.push({ userId: item.user_id, fullname: item.fullname })
                                        })
                                        let defaultProps = {
                                            options: dataListApprover,
                                            getOptionLabel: (option) => option.fullname,
                                        };
                                        this.setState({ listApprover: defaultProps })
                                    }
                                })
                            }
                            // this.getPL(type)
                            if (type != undefined && type == 'PL') {
                                this.getPL(type)
                            } else if (type != undefined && type == 'LOCF') {
                                let bodyRatioLocf = {
                                    "report": 'ratio',
                                    "monthlyReportId": this.state.monthlyReportId,
                                    "periode": this.state.periode.periode,
                                    "companyId": this.state.company.company_id,
                                    "months": this.state.month.month_id,
                                    "currency_id": this.state.defaultCurrency.id
                                }
                                api.create().triggerHistoricalRatio(bodyRatioLocf).then((res) => {
                                    console.log(res)
                                    this.setState({ loading: false })
                                })
                            } else if (type != undefined && type == 'BS') {
                                let bodyRatioBs = {
                                    "report": 'ratio',
                                    "monthlyReportId": this.state.monthlyReportId,
                                    "periode": this.state.periode.periode,
                                    "companyId": this.state.company.company_id,
                                    "months": this.state.month.month_id,
                                    "currency_id": this.state.defaultCurrency.id
                                }
                                api.create().triggerRatioFromLOCF(bodyRatioBs).then((res) => {
                                    console.log(res)
                                    this.setState({ loading: false })
                                })
                            } else {
                                this.setState({ loading: false })
                            }
                            // this.getFR(type)
                            // this.getReport()
                            // this.getReportAttachment()
                            api.create().checkApproverMonthly().then(response => {
                                console.log(response)
                                if (this.state.btnCreate === true && this.state.btnEdit === true) {
                                    console.log('editable');
                                    this.setState({ isApprover: this.state.approverTrue ? true : false, checkApprover: this.state.approverTrue ? true : false, isApproverFinance: response.data.data.is_finance, isApproverCAT: response.data.data.is_cat, })
                                } else {
                                    console.log('just view');
                                    this.setState({ isApprover: true, checkApprover: true, isApproverFinance: true, isApproverCAT: true })
                                }
                            })
                        })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            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.data.message, tipeAlert: 'error' })
                }
            })
        })
    }

    getLatestPeriodSubmit() {
        let body = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "months": this.state.month.month_id
        }
        api.create().getSubmitMonthlyReport(body).then(response => {
            console.log(response);
            if (response.data) {
                if (response.data.status === "success") {
                    this.setState({ isSubmit: response.data.data.is_can_submit }, () => {
                        this.getReport()
                        this.getReportAttachment()
                    })
                }
            }
        })
    }

    historyApproval() {
        this.state.listReportTypeId.forEach((master_report_type_id) => {
            let body = {
                "company_id": this.state.company.company_id,
                "periode": this.state.periode.periode,
                "months": this.state.month.month_id,
                master_report_type_id
            }
            api.create().historyApprovalMonthly(body).then(response => {
                console.log(response);
                if (response.data.data) {
                    if (response.data.data.length > 0) {
                        let dataTable = response.data.data.map(item => {
                            let indexC = String(item.status_approval).toLocaleUpperCase().indexOf('C')
                            let status_approv = ''
                            if (String(item.status_approval).toLocaleUpperCase().includes('CC')) {
                                status_approv = `${String(item.status_approval).substr(0, indexC)}${String(item.status_approval).substr(indexC + 1, String(item.status_approval).length)}`
                            } else {
                                status_approv = String(item.status_approval)
                            }
                            return [
                                item.pic,
                                status_approv,
                                item.remarks,
                                item.item_revision,
                                item.history_approval_date
                            ]
                        })
                        if (master_report_type_id === 2) {
                            this.setState({ dataTableHistoryCAT: dataTable, visibleTableHistoryCAT: true })
                        } else {
                            this.setState({ dataTableHistory: dataTable, visibleTableHistory: true })
                        }
                    }
                }
            })
        })
    }

    saveToMonthlyReport(type) {
        this.setState({
            visibleMonthlyReport: true,
            loading: true,
            visibleBS: false,
            visiblePL: false,
            visibleCAT: false,
            visibleCF: false,
            visibleFAM: false,
            visibleTP: false,
            visibleLOCF: false,
            visibleOI: false,
        }, () => {
            this.getMonthlyReportID(type)
        })
    }

    clickDetail(item, id, revision, status, tableKey) {
        let items = ''
        let PLBSFAMSubmitted = 0
        if (item === 'Corporate Annual Target') {
            items = 'CAT'
        } else {
            items = item
        }
        const listTable = tableKey === 'CAT' ? this.state.dataForRevisionCAT : this.state.dataForRevision
        listTable.map(i => {
            if (i.report_name === items) {
                if (i.revision == revision) {
                    this.setState({ prevRevision: true })
                } else {
                    this.setState({ prevRevision: false })
                }
            }
            if (String(i.report_name).toLocaleLowerCase() == "profit loss" || String(i.report_name).toLocaleLowerCase() == "balance sheet" || String(i.report_name).toLocaleLowerCase() == "fixed assets movement") {
                if (String(i.current_status).toLocaleLowerCase() == "submitted") {
                    PLBSFAMSubmitted += 1
                }
            }
        })
        this.setState({
            report_id: id,
            revisionTable: revision,
            status: status,
            tableKey
        }, () => {
            console.log(status)
            console.log(this.state.prevRevision)
            if (item === 'Balance Sheet') {
                this.setState({
                    visibleMonthlyReport: false,
                    visibleBS: true,
                    visiblePL: false,
                    visibleCAT: false,
                    visibleFAM: false,
                    visibleTP: false,
                    visibleLOCF: false,
                    visibleOI: false,
                    visibleCF: false,
                })
            } else if (item === 'Profit Loss') {
                this.setState({
                    visibleMonthlyReport: false,
                    visibleBS: false,
                    visiblePL: true,
                    visibleCAT: false,
                    visibleFAM: false,
                    visibleTP: false,
                    visibleLOCF: false,
                    visibleOI: false,
                    visibleCF: false,
                })
            } else if (item === 'Tax Planning') {
                this.setState({
                    visibleMonthlyReport: false,
                    visibleBS: false,
                    visiblePL: false,
                    visibleCAT: false,
                    visibleFAM: false,
                    visibleTP: true,
                    visibleLOCF: false,
                    visibleOI: false,
                    visibleCF: false,
                })
            } else if (item === 'Fixed Assets Movement') {
                this.setState({
                    visibleMonthlyReport: false,
                    visibleBS: false,
                    visiblePL: false,
                    visibleCAT: false,
                    visibleFAM: true,
                    visibleTP: false,
                    visibleLOCF: false,
                    visibleOI: false,
                })
            } else if (item === 'Corporate Annual Target') {
                this.setState({
                    visibleMonthlyReport: false,
                    visibleBS: false,
                    visiblePL: false,
                    visibleCAT: true,
                    visibleFAM: false,
                    visibleTP: false,
                    visibleLOCF: false,
                    visibleOI: false,
                    visibleCF: false,
                })
            } else if (item === 'List Of Credit Facilities and Investment') {
                this.setState({
                    visibleMonthlyReport: false,
                    visibleBS: false,
                    visiblePL: false,
                    visibleCAT: false,
                    visibleFAM: false,
                    visibleTP: false,
                    visibleLOCF: true,
                    visibleOI: false,
                    visibleCF: false,
                })
            } else if (item === 'Operating Indicator') {
                this.setState({
                    visibleMonthlyReport: false,
                    visibleBS: false,
                    visiblePL: false,
                    visibleCAT: false,
                    visibleFAM: false,
                    visibleTP: false,
                    visibleLOCF: false,
                    visibleOI: true,
                    visibleCF: false,
                })
            } else if (item === 'Cash Flow') {
                this.setState({
                    visibleMonthlyReport: false,
                    visibleBS: false,
                    visiblePL: false,
                    visibleCAT: false,
                    visibleFAM: false,
                    visibleTP: false,
                    visibleLOCF: false,
                    visibleOI: false,
                    visibleCF: true,
                    PLBSFAMSubmitted: PLBSFAMSubmitted == 3 ? true : false
                })
            }
        })
    }

    handleChange(value, tableMeta, tableKey) {
        let data = tableKey === 'CAT' ? this.state.dataTableCAT : this.state.dataTable
        data[tableMeta.rowIndex][tableMeta.columnIndex] = value
    }

    fileHandler = (event) => {
        let fileObj = event
        ExcelRenderer(fileObj, (err, resp) => {
            // console.log(resp)
            if (err) {
                console.log(err);
            }
            else {
                const formData = new FormData();
                formData.append("revision", Number(this.state.lastRevision));
                formData.append("companyId", this.state.company.company_id);
                formData.append("periode", Number(this.state.periode.periode));
                formData.append("master_report_type_id", this.state.currentMasterReportTypeId);
                formData.append("file", event);
                formData.append("months", this.state.month.month_id)
                this.setState({ formData })
            }
        })
    }

    uploadAttachment(formData) {
        api.create().uploadAttachmentMonthly(formData).then(response => {
            console.log(response);
            if (response.data) {
                if (response.data.status === "success") {
                    this.setState({ visibleUpload: false, currentMasterReportTypeId: null }, () => {
                        this.getReport()
                        this.getReportAttachment()
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        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' })
            }
            // console.log(response)
        })
    }

    deleteAttachment(item) {
        api.create().deleteAttachmentMonthly(item.attachment_id).then(response => {
            // // console.log(response);
            if (response.data) {
                if (response.data.status === "success") {
                    this.getMonthlyReportID()
                }
            }
        })
    }

    async downloadAttachment(fileurl, name) {
        let length = name.split(".").length
        let fileType = name.split(".")[length - 1]
        // // console.log(fileType);
        let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/monthly_report/download_attachment?fileName=${fileurl}&&fileType=${fileType}`
        // // console.log(url);
        let res = await fetch(
            `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/monthly_report/download_attachment?fileName=${fileurl}&&fileType=${fileType}`
        )
        res = await res.blob()
        this.setState({ loading: false }, () => {
            document.body.style.overflow = 'unset';
        })
        if (res.size > 0) {
            let url = window.URL.createObjectURL(res);
            let a = document.createElement('a');
            a.href = url;
            a.download = 'Monthly Report Attachment.xlsx';
            a.click();
        }
    }

    closeAlert() {
        this.setState({ alert: false })
    }

    validate(master_report_type_id) {
        this.setState({ loading: true, selectedStatus: this.state.listStatus }, () => {
            // document.body.style.overflow = 'hidden';
        })
        let array = []
        let canSubmit = true
        const listTable = master_report_type_id === 1 ? this.state.dataTable : this.state.dataTableCAT
        listTable.map(item => {
            // if (item[1] !== 'Cash Flow') {
            if (item[3] !== "submitted" && item[3] !== 'approved') {
                canSubmit = false
                array.push(item[3])
            }
            // }
            // if (item[3].includes("not-yet") || item[3].includes("draft")) {
            //     array.push(item[3])
            // } else {
            //     array.push(item[3])
            // }
        })
        if (canSubmit === true) {
            let body = {
                monthly_report_id: this.state.monthlyReportId,
                master_report_type_id
            }
            api.create().submitMonthlyReport(body).then(response => {
                console.log(response);
                if (response.data) {
                    if (response.data.status === "success") {
                        this.getMonthlyReportID()
                    }
                }
            })
        } else {
            this.setState({ alert: true, messageAlert: 'Data Is Not Complete', tipeAlert: 'warning', loading: false }, () => {
                document.body.style.overflow = 'unset';
            })
        }
        // if (array.includes("not-yet" || "draft")) {
        //     // // console.log('gagal');
        // } else {
        //     // // console.log('masuk');
        // }

    }

    validateRevision(master_report_type_id) {
        // this.scrollToMyRef()
        let arrayRevisi = this.state.detailRevisiCheck
        let remarksKosong = 0
        arrayRevisi.map((item, index) => {
            if (item.remarks == "") {
                remarksKosong += 1
            }
        })
        // // console.log(arrayRevisi)
        if (arrayRevisi.length == 0 || remarksKosong > 0) {
            this.setState({ alert: true, messageAlert: 'Remarks Cannot be Empty', tipeAlert: 'error' })
        } else {
            this.setState({ visibleRevision: false }, () => this.approvalSubmission('revision', master_report_type_id))
        }
    }

    async setHeaderTokenSuperadmin(type, master_report_type_id) {
        let realToken = await localStorage.getItem(Constant.TOKEN)
        api.create().getIdToken(this.state.approver.userId).then((response) => {
            console.log(response.data.data.token)
            localStorage.setItem(Constant.TOKEN, response.data.data.token)
            this.approvalSubmission(type, master_report_type_id, realToken)
        })
    }

    approvalSubmission(type, master_report_type_id, realToken) {
        // this.scrollToMyRef()
        // if (this.state.isAdmin && type == 'approve') {
        //     api.create().getIdToken(this.state.approver.userId).then((response) => {
        //         localStorage.setItem(Constant.TOKEN, response.data.data.token)
        //     })
        // }
        this.setState({ loading: true, selectedStatus: this.state.listStatus }, () => {
            // document.body.style.overflow = 'hidden';
        })
        let body = {
            "approval_id": master_report_type_id === 2 ? this.state.approverIDCAT : this.state.approverID,
            "status": type,
            "months": this.state.month.month_id,
            "detail": this.state.detailRevisiCheck,
            "is_superadmin": this.state.isAdmin,
            "currency_id": this.state.defaultCurrency.id,
            master_report_type_id
        }
        let payload = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "months": this.state.month.month_id,
            "min_periode": moment(this.state.minDateRevision).format('YYYY-MM-DD'),
            "max_periode": moment(this.state.maxDateRevision).format('YYYY-MM-DD')
        }
        console.log(payload)
        // // console.log(this.props.location);
        // // console.log(body)
        setTimeout(() => {
            api.create().approvalMonthly(body).then((res) => {
                console.log(res)
                // this.setState({ loading: false }, () => {
                // })
                if (this.state.isAdmin && type == 'approve') {
                    localStorage.setItem(Constant.TOKEN, realToken)
                    this.setState({ visibleApproveSuperadmin: false, currentMasterReportTypeId: null })
                }
                setTimeout(() => {
                    if (type == 'revision') {
                        api.create().createPeriodeRevisionMonthly(payload).then((res))
                    }
                    this.getMonthlyReportID()
                }, 300);
            })
        }, 100);
    }

    getCashFlow(type) {
        let payload = {
            "report_id": 13,
            "revision": Number(this.state.lastRevision),
            "periode": this.state.periode.periode,
            "company_id": this.state.company.company_id,
            "monthly_report_id": this.state.monthlyReportId,
            "months": this.state.month.month_id,
            "get_for": "edit"
        }

        api.create().getHierarkiMontlyReportCF(payload).then(response => {
            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,
                            { value: item.cash_flow.actual, formula: item.cash_flow.actual_formula },
                            item.order,
                            false
                        ])
                    }
                    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,
                        { value: item.cash_flow.actual, formula: item.cash_flow.actual_formula },
                        item.order,
                        false
                    ])
                    if (item.children !== null) {
                        if (item.children.length > 0) {
                            item.children.map((items, indexs) => {
                                handlePushChild(items)
                            })
                        }
                    }
                })
                console.log(dataTable)
                this.setState({ dbCF: dataTable }, () => {
                    this.olahDataCashFlow(this.state.dbCF, type)
                })
            }
        })
    }

    handleValueFormula = (item, indexS) => {
        // loading = true
        // console.log(tableMeta);
        // "@44[M-1]#BS"
        let dbCF = this.state.dbCF
        let splitFormula = String(item[3]).split(/([()@])/)
        let baru = []
        let anjay = []
        // console.log(splitFormula);
        splitFormula.map((item, index) => {
            let items = String(item).substr(Number(String(item).length) - 1, 1)
            let subForm = String(item).substr(0, Number(String(item).length) - 1)
            // console.log(item);
            // console.log(items);
            // console.log(subForm);

            let re = /^[a-zA-Z0-9_]+$/;
            if (item !== "") {
                if (items == ']') {
                    baru.push(String(item))
                } else if (!re.test(items)) {
                    baru.push(subForm)
                    baru.push(items)
                } else {
                    baru.push(String(item))
                }
            }
        })

        // console.log(baru);
        let tambahan = false
        let opet = ""
        let itung2x = ''
        baru.map((item, index) => {
            if (item == 'X') {
                tambahan = true
            } else if (item == '-' || item == '+' || item == '/' || item == '*' || item == '(' || item == ')') {
                anjay.push(item)
            } else {
                if (String(item).includes('#')) {
                    if (String(item).includes('[M-1]')) {
                        let tst = '@' + String(item).replace('[M-1]', '[M1]')
                        // console.log(dbCF[tableMeta.rowIndex]);
                        // console.log(tableMeta);
                        // console.log(tst);
                        let indexID = dbCF[indexS][6].formula.findIndex((val) => val.item_formula == tst)
                        // console.log(indexID);

                        if (indexID !== -1) {
                            let valuezz = dbCF[indexS][6].formula[indexID].value
                            anjay.push(valuezz == "" ? 0 : valuezz)
                            // console.log(valuezz);
                        }
                    } else {
                        let data = dbCF[indexS][6].formula == null ? [] : dbCF[indexS][6].formula
                        // console.log(data)
                        let indexID = data.findIndex((val) => val.item_formula == String(`@${item}`))
                        if (indexID !== -1) {
                            let valuezz = data[indexID].value
                            anjay.push(valuezz == "" ? 0 : valuezz)
                        }
                    }
                } else {
                    if (String(item).includes('[M-1]')) {
                        let tst = String(item).replace('[M-1]', '')
                        let indexID = dbCF.findIndex((val) => val[7] == tst)
                        if (indexID !== -1) {
                            let valuezz = dbCF[indexID][8]
                            anjay.push(valuezz == "" ? 0 : valuezz)
                        }
                    } else {
                        let indexID = dbCF.findIndex((val) => val[7] == item)
                        if (item == 'X-1') {
                            anjay.push(-1)
                        } else if (tambahan) {
                            if (item == '-' || item == '+' || item == '/' || item == '*') {
                                opet = item
                            } else {
                                anjay.push(opet == '' ? Number(item) : Number(String(opet + String(item))))
                                tambahan = false
                                opet = ""
                            }
                        } else {
                            if (indexID !== -1) {
                                let valuezz = dbCF[indexID][6].value
                                if (item == dbCF[indexS][7]) {
                                    anjay.push(0)
                                } else {
                                    anjay.push(valuezz == "" ? 0 : valuezz)
                                }
                            } else {
                                if (item === '(-1)') {
                                    anjay.push(-1)
                                }
                            }
                        }
                    }
                }
            }
        })

        // console.log(item[5])
        // console.log(splitFormula)
        // console.log(baru)
        // console.log(anjay)
        let anjay2 = []
        let kurung = false
        let item1 = []
        anjay.map((item, index) => {
            if (item == "(") {
                kurung = true
            } else if (item == ")") {
                kurung = false
                anjay2.push(item1)
                item1 = []
            } else {
                if (kurung) {
                    item1.push(item)
                } else {
                    anjay2.push(item)
                }
            }
        })

        let total = 0
        let opt = ""
        let totalPrio = 0
        let optPrio = ""
        let prio = false
        anjay2.map((item, index) => {
            if (Array.isArray(item)) {
                prio = true
                item.map((items, indexs) => {
                    if (items == "+") {
                        optPrio = "tambah"
                    } else if (items == "-") {
                        optPrio = "kurang"
                    } else if (items == "*") {
                        optPrio = "kali"
                    } else if (items == "/") {
                        optPrio = "bagi"
                    } else {
                        if (optPrio == "tambah") {
                            totalPrio = Number(totalPrio) + Number(items)
                        } else if (optPrio == "kurang") {
                            totalPrio = Number(totalPrio) - Number(items)
                        } else if (optPrio == "kali") {
                            totalPrio = Number(totalPrio) * Number(items)
                        } else if (optPrio == "bagi") {
                            totalPrio = Number(totalPrio) / Number(items) == NaN ? 0 : Number(totalPrio) / Number(items)
                        } else {
                            totalPrio += Number(items)
                        }
                    }
                })

                if (index == anjay2.length - 1) {
                    if (opt == "tambah") {
                        total = Number(total) + Number(totalPrio)
                    } else if (opt == "kurang") {
                        total = Number(total) - Number(totalPrio)
                    } else if (opt == "kali") {
                        total = Number(total) * Number(totalPrio)
                    } else if (opt == "bagi") {
                        total = Number(total) / Number(totalPrio) == NaN ? 0 : Number(total) / Number(totalPrio)
                    } else {
                        total += Number(totalPrio)
                    }
                }
            } else {
                if (item == "+") {
                    opt = "tambah"
                    if (prio) {
                        total = Number(Number(totalPrio) + Number(total))
                        prio = false
                        totalPrio = 0
                        optPrio = ""
                    }
                } else if (item == "-") {
                    opt = "kurang"
                    if (prio) {
                        total = Number(Number(totalPrio) + Number(total))
                        prio = false
                        totalPrio = 0
                        optPrio = ""
                    }
                } else if (item == "*") {
                    opt = "kali"
                    if (prio) {
                        total = Number(Number(totalPrio) + Number(total))
                        prio = false
                        totalPrio = 0
                        optPrio = ""
                    }
                } else if (item == "/") {
                    opt = "bagi"
                    if (prio) {
                        total = Number(Number(totalPrio) + Number(total))
                        prio = false
                        totalPrio = 0
                        optPrio = ""
                    }
                } else {
                    if (opt == "tambah") {
                        total = Number(total) + Number(item)
                    } else if (opt == "kurang") {
                        total = Number(total) - Number(item)
                    } else if (opt == "kali") {
                        total = Number(total) * Number(item)
                    } else if (opt == "bagi") {
                        total = Number(total) / Number(item) == NaN ? 0 : Number(total) / Number(item)
                    } else {
                        total += Number(item)
                    }
                }
            }
        })

        // dataTable2[tableMeta.rowIndex][6].value = total

        return total
    }

    olahDataCashFlow(dbCF, type) {
        dbCF.map((item, index) => {
            if (item[0] == 5 || item[0] == 6) {
                item[6].value = this.handleValueFormula(item, index)
            }
        })
        console.log(dbCF)
        this.setState({ dbCF }, () => {
            this.payloadCF(type)
        })
    }

    payloadCF(type) {
        let listCF = []
        this.state.dbCF.map((item, index) => {
            if (item[6].value == "" || item[6].value == 0 || item[6].value == "0.0") {
                item[6].value = this.handleValueFormula(item, index)
                listCF.push({
                    "item_report_id": item[1],
                    "actual": item[0] == 1 ? "" : Number(item[6].value).toFixed(1)
                })
            } else {
                listCF.push({
                    "item_report_id": item[1],
                    "actual": item[0] == 1 ? "" : Number(item[6].value).toFixed(1)
                })
            }

        })

        console.log(this.state.dbCF)
        this.setState({ dbCF: listCF }, () => {
            if (type != undefined) {
                if (type == 'BS' || type == 'FAM' || type == 'PL') {
                    console.log('tarik sis')
                    this.createCashFlow()
                }
            }
        })
    }

    createCashFlow(payload) {
        console.log(JSON.stringify(payload))
        api.create().createMonthlyReportCF(payload).then((res) => {
            if (res.data.status === "success") {
                this.saveToMonthlyReport()
                console.log(res)
            } else {
                if (res.data?.message == "Please Set Up Rate Currency First") {
                    this.setState({ visibleAlertSave: true })
                } else {
                    this.setState({ alert: true, messageAlert: res.data.message, tipeAlert: 'warning', loading: false, handleDoubleClick: 0 }, () => {
                        if (res.data.message.includes("Someone Logged In") || res.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            }
        })
    }

    getPL(type) {
        let PLID = null
        let payloadID = {
            "periode": this.state.periode.periode,
            "company_id": this.state.company.company_id,
            "currency_id": this.state.defaultCurrency.id
        }
        console.log(payloadID);
        api.create().getPLID(payloadID).then(response => {
            console.log(response);
            if (response) {
                PLID = response.data.data == null ? null : response.data.data.profit_loss_id
            } else {
                PLID = null
            }
            this.setState({ PLID }, () => {
                let payload = {
                    "revision": Number(this.state.lastRevision),
                    "periode": this.state.periode.periode,
                    "company_id": this.state.company.company_id,
                    "months": this.state.month.month_id,
                    "quarter": 0,
                    "report_id": 28,
                    "submission_id": this.state.PLID,
                    "currency_id": this.state.defaultCurrency.id
                }

                api.create().getHierarkiCreateReportPLMR(payload).then((response) => {
                    console.log(response)
                    let dataTable = []
                    let err = false

                    if (response.data) {
                        if (response.data.status === 'success') {
                            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,
                                        this.state.month.month_id == 1 ?
                                            { value: item.profit_detail.january, formula: item.profit_detail.january_formula, value_ro: 0 } :
                                            this.state.month.month_id == 2 ?
                                                { value: item.profit_detail.february, formula: item.profit_detail.february_formula, value_ro: 0 } :
                                                this.state.month.month_id == 3 ?
                                                    { value: item.profit_detail.march, formula: item.profit_detail.march_formula, value_ro: 0 } :
                                                    this.state.month.month_id == 4 ?
                                                        { value: item.profit_detail.april, formula: item.profit_detail.april_formula, value_ro: 0 } :
                                                        this.state.month.month_id == 5 ?
                                                            { value: item.profit_detail.may, formula: item.profit_detail.may_formula, value_ro: 0 } :
                                                            this.state.month.month_id == 6 ?
                                                                { value: item.profit_detail.june, formula: item.profit_detail.june_formula, value_ro: 0 } :
                                                                this.state.month.month_id == 7 ?
                                                                    { value: item.profit_detail.july, formula: item.profit_detail.july_formula, value_ro: 0 } :
                                                                    this.state.month.month_id == 8 ?
                                                                        { value: item.profit_detail.august, formula: item.profit_detail.august_formula, value_ro: 0 } :
                                                                        this.state.month.month_id == 9 ?
                                                                            { value: item.profit_detail.september, formula: item.profit_detail.september_formula, value_ro: 0 } :
                                                                            this.state.month.month_id == 10 ?
                                                                                { value: item.profit_detail.october, formula: item.profit_detail.october_formula, value_ro: 0 } :
                                                                                this.state.month.month_id == 11 ?
                                                                                    { value: item.profit_detail.november, formula: item.profit_detail.november_formula, value_ro: 0 } :
                                                                                    { value: item.profit_detail.december, formula: item.profit_detail.december_formula, value_ro: 0 },
                                        item.order,
                                        item.profit_detail.notes
                                    ])
                                }
                                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,
                                    this.state.month.month_id == 1 ?
                                        { value: item.profit_detail.january, formula: item.profit_detail.january_formula, value_ro: 0 } :
                                        this.state.month.month_id == 2 ?
                                            { value: item.profit_detail.february, formula: item.profit_detail.february_formula, value_ro: 0 } :
                                            this.state.month.month_id == 3 ?
                                                { value: item.profit_detail.march, formula: item.profit_detail.march_formula, value_ro: 0 } :
                                                this.state.month.month_id == 4 ?
                                                    { value: item.profit_detail.april, formula: item.profit_detail.april_formula, value_ro: 0 } :
                                                    this.state.month.month_id == 5 ?
                                                        { value: item.profit_detail.may, formula: item.profit_detail.may_formula, value_ro: 0 } :
                                                        this.state.month.month_id == 6 ?
                                                            { value: item.profit_detail.june, formula: item.profit_detail.june_formula, value_ro: 0 } :
                                                            this.state.month.month_id == 7 ?
                                                                { value: item.profit_detail.july, formula: item.profit_detail.july_formula, value_ro: 0 } :
                                                                this.state.month.month_id == 8 ?
                                                                    { value: item.profit_detail.august, formula: item.profit_detail.august_formula, value_ro: 0 } :
                                                                    this.state.month.month_id == 9 ?
                                                                        { value: item.profit_detail.september, formula: item.profit_detail.september_formula, value_ro: 0 } :
                                                                        this.state.month.month_id == 10 ?
                                                                            { value: item.profit_detail.october, formula: item.profit_detail.october_formula, value_ro: 0 } :
                                                                            this.state.month.month_id == 11 ?
                                                                                { value: item.profit_detail.november, formula: item.profit_detail.november_formula, value_ro: 0 } :
                                                                                { value: item.profit_detail.december, formula: item.profit_detail.december_formula, value_ro: 0 },
                                    item.order,
                                    item.profit_detail.notes
                                ])
                                if (item.children !== null) {
                                    if (item.children.length > 0) {
                                        item.children.map((items, indexs) => {
                                            handlePushChild(items)
                                        })
                                    }
                                }
                            })
                            console.log(JSON.stringify(dataTable))
                            console.log(dataTable)
                            this.setState({ dbPL: dataTable }, () => {
                                this.olahDataPL(this.state.dbPL, type)
                            })
                        } else {
                            this.setState({ loading: false, alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                                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, loading: false, buttonError: true, saveDraft: true, refresh: false })
                    }
                    // console.log(dataTable);
                })
            })
        })

    }

    handleValueFormulaDBPLMR = (value, tableMeta, column, typeRO) => {
        let splitFormula = String(tableMeta[3]).split(/([()@])/)
        // let splitFormula = String(tableMeta.rowData[3]).split('@')
        let baru = []
        let anjay = []
        // let colIndex = tableMeta.columnIndex + column
        let dataTable2 = this.state.dbPL
        // if (forecast !== undefined) {
        //     console.log(tableMeta)
        // }

        splitFormula.map((item, index) => {
            let items = String(item).substr(Number(String(item).length) - 1, 1)
            let subForm = String(item).substr(0, Number(String(item).length) - 1)
            let re = /^[a-zA-Z0-9_]+$/;
            let asd = ''
            if (item !== "") {
                if (!re.test(items)) {
                    baru.push(subForm)
                    baru.push(items)
                } else {
                    baru.push(String(item))
                }
            }
        })

        baru.map((item, index) => {
            if (item == '-' || item == '+' || item == '/' || item == '*' || item == '(' || item == ')') {
                anjay.push(item)
            } else {
                if (String(item).includes('#')) {
                    // if (typeRO !== undefined) {
                    // let forecastt = 0
                    // val.item_formula
                    // forecast.map((items, index) => {
                    //     if (items.periode == periode) {
                    //         forecastt += Number(items.value)
                    //     }
                    // })
                    // anjay.push(forecastt)
                    // } else {
                    if (String(item).includes('[M-1]')) {
                        // let tst = String(item).replace('[M-1]', '')
                        // let data = column == 7 ? 18 : column - 1
                        // let period = data == 18 ? Number(this.props.periode) - 1 : this.props.periode
                        // let indexID = tableMeta.rowData[data].formula.findIndex((val) => val.item_formula == String(`@${tst}`) && val.periode == period)

                        // if (indexID !== -1) {
                        //     let valuezz = tableMeta.rowData[data].formula[indexID].value
                        //     anjay.push(valuezz == "" ? 0 : valuezz)
                        // }
                    } else {
                        let indexID = value.formula.findIndex((val) => val.item_formula == String(`@${item}`) && val.periode == Number(this.state.periode.periode))
                        if (indexID !== -1) {
                            let valuezz = 0
                            if (typeRO != undefined) {
                                valuezz = value.formula[indexID].value_ro
                            } else {
                                valuezz = value.formula[indexID].value
                            }
                            anjay.push(valuezz == "" ? 0 : valuezz)
                        }
                    }
                    // }
                } else {
                    let indexID = dataTable2.findIndex((val) => val[7] == item)
                    if (indexID !== -1) {
                        let valuezz = 0
                        if (typeRO != undefined) {
                            valuezz = dataTable2[indexID][column].value_ro == undefined ? dataTable2[indexID][column] : dataTable2[indexID][column].value_ro
                        } else {
                            valuezz = dataTable2[indexID][column].value == undefined ? dataTable2[indexID][column] : dataTable2[indexID][column].value
                        }
                        anjay.push(valuezz == "" ? 0 : valuezz)
                    } else {
                        if (item === '(-1)') {
                            anjay.push(-1)
                        }
                    }
                }
            }
        })

        let anjay2 = []
        let kurung = false
        let item1 = []
        anjay.map((item, index) => {
            if (item == "(") {
                kurung = true
            } else if (item == ")") {
                kurung = false
                anjay2.push(item1)
                item1 = []
            } else {
                if (kurung) {
                    item1.push(item)
                } else {
                    anjay2.push(item)
                }
            }
        })

        // if (tableMeta.rowData[5] == "1.0 Cash inflow/ (outflow)  from Operating Activities") {
        //     console.log(anjay2)
        // }

        let total = 0
        let opt = ""
        let totalPrio = 0
        let optPrio = ""
        let prio = false
        anjay2.map((item, index) => {
            if (Array.isArray(item)) {
                prio = true
                item.map((items, indexs) => {
                    if (items == "+") {
                        optPrio = "tambah"
                    } else if (items == "-") {
                        optPrio = "kurang"
                    } else if (items == "*") {
                        optPrio = "kali"
                    } else if (items == "/") {
                        optPrio = "bagi"
                    } else {
                        if (optPrio == "tambah") {
                            totalPrio = Number(totalPrio) + Number(items)
                        } else if (optPrio == "kurang") {
                            totalPrio = Number(totalPrio) - Number(items)
                        } else if (optPrio == "kali") {
                            totalPrio = Number(totalPrio) * Number(items)
                        } else if (optPrio == "bagi") {
                            totalPrio = Number(totalPrio) / Number(items) == NaN ? 0 : Number(totalPrio) / Number(items)
                        } else {
                            totalPrio += Number(items)
                        }
                    }
                })

                if (index == anjay2.length - 1) {
                    if (opt == "tambah") {
                        total = Number(total) + Number(totalPrio)
                    } else if (opt == "kurang") {
                        total = Number(total) - Number(totalPrio)
                    } else if (opt == "kali") {
                        total = Number(total) * Number(totalPrio)
                    } else if (opt == "bagi") {
                        total = Number(total) / Number(totalPrio) == NaN ? 0 : Number(total) / Number(totalPrio)
                    } else {
                        total += Number(totalPrio)
                    }
                }
            } else {
                // console.log(item.length)
                if (item == "+") {
                    opt = "tambah"
                    if (prio) {
                        total = Number(Number(totalPrio) + Number(total))
                        prio = false
                        totalPrio = 0
                        optPrio = ""
                    }
                } else if (item == "-") {
                    opt = "kurang"
                    if (prio) {
                        total = Number(Number(totalPrio) + Number(total))
                        prio = false
                        totalPrio = 0
                        optPrio = ""
                    }
                } else if (item == "*") {
                    opt = "kali"
                    if (prio) {
                        total = Number(Number(totalPrio) + Number(total))
                        prio = false
                        totalPrio = 0
                        optPrio = ""
                    }
                } else if (item == "/") {
                    opt = "bagi"
                    if (prio) {
                        total = Number(Number(totalPrio) + Number(total))
                        prio = false
                        totalPrio = 0
                        optPrio = ""
                    }
                } else {
                    if (opt == "tambah") {
                        total = Number(total) + Number(item)
                    } else if (opt == "kurang") {
                        total = Number(total) - Number(item)
                    } else if (opt == "kali") {
                        total = Number(total) * Number(item)
                    } else if (opt == "bagi") {
                        total = Number(total) / Number(item) == NaN ? 0 : Number(total) / Number(item)
                    } else {
                        total += Number(item)
                    }
                }
            }
        })

        // if (tableMeta[5] == "Direct Material" && typeRO != undefined) {
        //     console.log(splitFormula)
        //     console.log(baru)
        //     console.log(anjay)
        //     console.log(anjay2)
        //     console.log(total)
        // }

        total = R.equals(total, NaN) ? "0.0" : total
        return total

    }

    olahDataPL(dbPL, type) {
        dbPL.map((item, index) => {
            if (item[0] == 5 || item[0] == 6) {
                item[6].value = this.handleValueFormulaDBPLMR(item[6], item, 6)
                item[6].value_ro = this.handleValueFormulaDBPLMR(item[6], item, 6, 'ro')
            }
        })
        // console.log(dbPL)
        this.setState({ dbPL }, () => {
            this.payloadPL(type)
        })
    }

    payloadPL(type) {
        let listPL = []
        this.state.dbPL.map((item, index) => {
            // if (item[6].value == "" || item[6].value == 0 || item[6].value == "0.0") {
            item[6].value = this.handleValueFormulaDBPLMR(item[6], item, 6)
            item[6].value_ro = this.handleValueFormulaDBPLMR(item[6], item, 6, 'ro')
            listPL.push({
                "item_report_id": item[1],
                "actual": item[0] == 1 ? "" : Number(item[6].value).toFixed(1),
                "rolling_outlook": item[0] == 1 ? "" : Number(item[6].value_ro).toFixed(1),
                "notes": item[8]
            })
            // } else {
            //     item[6].value = this.handleValueFormulaDBPLMR(item[6], item, 6)
            //     listPL.push({
            //         "item_report_id": item[1],
            //         "actual": item[0] == 1 ? "" : Number(item[6].value).toFixed(1),
            //         "rolling_outlook": item[0] == 1 ? "" : Number(item[6].value_ro).toFixed(1),
            //         "notes": item[8]
            //     })
            // }
        })
        // console.log(this.state.dbPL)
        this.setState({ dbPL: listPL }, () => {
            if (type != undefined) {
                if (type == 'PL') {
                    // console.log(this.state.dbPL)
                    // this.setState({ loading: false })
                    console.log('tarik sis')
                    this.createPL()
                }
            }
        })
    }

    createPL() {
        console.log();
        let payload = {
            // "monthly_report_id": this.state.monthlyReportId,
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "report_id": 28,
            "status": "submitted",
            "months": this.state.month.month_id,
            "quarter": 0,
            "profit_loss_id": this.state.PLID,
            "profit_loss_mr": this.state.dbPL,
            "currency_id": this.state.defaultCurrency.id
        }
        api.create().createReportPLMR(payload).then((res) => {
            console.log(res)
            // console.log(this.state.dbPL)
            this.setState({ loading: false })
            // if (response.data) {
            //     if (response.data.status === "success") {
            //         this.props.saveToMonthlyReport()
            //     } else {
            //         this.setState({ loading: false }, () => {
            //             this.props.saveToMonthlyReport()
            //         })
            //     }
            // } else {
            //     this.setState({ loading: false }, () => {
            //         // this.getSubmission()
            //         document.body.style.overflow = 'unset';
            //     })
            // }
        })
    }

    getFR(type) {
        let FRID = null
        let payloadID = {
            "periode": this.state.periode.periode,
            "company_id": this.state.company.company_id
        }
        console.log(payloadID);
        api.create().getFRID(payloadID).then(response => {
            console.log(response);
            if (response) {
                FRID = response.data.data == null ? null : response.data.data.ratio_id
            } else {
                FRID = null
            }
            this.setState({ FRID }, () => {
                let payload = {
                    "report_id": 29,
                    "revision": Number(this.state.lastRevision),
                    "periode": this.state.periode.periode,
                    "company_id": this.state.company.company_id,
                    "submission_id": this.state.FRID,
                    "months": this.state.month.month_id
                }
                api.create().getHierarkiCreateReportFRMR(payload).then(response => {
                    // console.log(response);
                    let dataTable = []
                    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.uom,
                                // "",
                                // item.ratio.total_actual_before === null ? "0.0" : item.ratio.total_actual_before === "" ? "0.0" : item.ratio.total_actual_before,
                                Number(item.ratio.monthly_january).toFixed(2),
                                Number(item.ratio.monthly_february).toFixed(2),
                                Number(item.ratio.monthly_march).toFixed(2),
                                Number(item.ratio.monthly_april).toFixed(2),
                                Number(item.ratio.monthly_may).toFixed(2),
                                Number(item.ratio.monthly_june).toFixed(2),
                                Number(item.ratio.monthly_july).toFixed(2),
                                Number(item.ratio.monthly_august).toFixed(2),
                                Number(item.ratio.monthly_september).toFixed(2),
                                Number(item.ratio.monthly_october).toFixed(2),
                                Number(item.ratio.monthly_november).toFixed(2),
                                Number(item.ratio.monthly_december).toFixed(2),
                            ])

                            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.uom,
                                // "",
                                // 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(2),
                                Number(item.ratio.february).toFixed(2),
                                Number(item.ratio.march).toFixed(2),
                                Number(item.ratio.april).toFixed(2),
                                Number(item.ratio.may).toFixed(2),
                                Number(item.ratio.june).toFixed(2),
                                Number(item.ratio.july).toFixed(2),
                                Number(item.ratio.august).toFixed(2),
                                Number(item.ratio.september).toFixed(2),
                                Number(item.ratio.october).toFixed(2),
                                Number(item.ratio.november).toFixed(2),
                                Number(item.ratio.december).toFixed(2),
                                Number(item.ratio.total_next_year).toFixed(2),
                                Number(item.ratio.total_more_year).toFixed(2),
                            ])
                            if (item.children !== null) {
                                if (item.children.length > 0) {
                                    item.children.map((items, indexs) => {
                                        handlePushChild(items)
                                    })
                                }
                            }
                        })
                        console.log(dataTable)
                        this.setState({ dbFR: dataTable, loading: false }, () => {
                            this.olahDataFR(this.state.dbFR, type)
                        })
                    } else {
                        this.setState({ dataTable: [], previewTable: false, loading: false, previewDownload: false })
                    }


                })
            })
        })


    }

    handleFormulaRatio = (value, tableMeta, month) => {
        // console.log(dataTable2)
        let dataTable2 = this.state.dbFR
        let total = 0
        if (month > 12) {
            total = Number(dataTable2[35][6 + month])
        } else {
            for (let index = 0; index < month; index++) {
                total += Number(dataTable2[35][7 + index])
                // console.log(index);
            }
            total = total / month
        }
        let hasil = Number(value) / total
        // console.log(hasil, value, total);
        return Number(hasil).toFixed(2)
    }

    olahDataFR(dbFR, type) {
        dbFR.map((item, index) => {
            if (item[0] != 4 || item[0] != 1) {
                if (item[5] === "Return on Invested Capital - YTD (ROIC)") {
                    item[7] = this.handleFormulaRatio(item[7], item, 1)
                    item[8] = this.handleFormulaRatio(item[8], item, 2)
                    item[9] = this.handleFormulaRatio(item[9], item, 3)
                    item[10] = this.handleFormulaRatio(item[10], item, 4)
                    item[11] = this.handleFormulaRatio(item[11], item, 5)
                    item[12] = this.handleFormulaRatio(item[12], item, 6)
                    item[13] = this.handleFormulaRatio(item[13], item, 7)
                    item[14] = this.handleFormulaRatio(item[14], item, 8)
                    item[15] = this.handleFormulaRatio(item[15], item, 9)
                    item[16] = this.handleFormulaRatio(item[16], item, 10)
                    item[17] = this.handleFormulaRatio(item[17], item, 11)
                    item[18] = this.handleFormulaRatio(item[18], item, 12)
                }
            }
        })
        this.setState({ dbFR }, () => {
            this.payloadFR(type)
        })
    }

    payloadFR(type) {
        let listFR = []
        console.log(this.state.dbFR)
        this.state.dbFR.map((item, index) => {
            if (item[0] != 4 || item[0] != 1) {
                // if (item[5] === "Return on Invested Capital - YTD (ROIC)" ) {
                //     item[7] = this.handleFormulaRatio(item[7],item,1)
                //     item[8] = this.handleFormulaRatio(item[8],item,2)
                //     item[9] = this.handleFormulaRatio(item[9],item,3)
                //     item[10] = this.handleFormulaRatio(item[10],item,4)
                //     item[11] = this.handleFormulaRatio(item[11],item,5)
                //     item[12] = this.handleFormulaRatio(item[12],item,6)
                //     item[13] = this.handleFormulaRatio(item[13],item,7)
                //     item[14] = this.handleFormulaRatio(item[14],item,8)
                //     item[15] = this.handleFormulaRatio(item[15],item,9)
                //     item[16] = this.handleFormulaRatio(item[16],item,10)
                //     item[17] = this.handleFormulaRatio(item[17],item,11)
                //     item[18] = this.handleFormulaRatio(item[18],item,12)
                // } 
            }


            listFR.push(
                {
                    "item_report_id": item[1],
                    "actual": this.state.month.month_id == 1 ?
                        String(item[7] == undefined || item[7] == 'Infinity' || item[7] == '-Infinity' ? "0.0" : Number(item[7]).toFixed(2)) :
                        this.state.month.month_id == 2 ?
                            String(item[8] == undefined || item[8] == 'Infinity' || item[8] == '-Infinity' ? "0.0" : Number(item[8]).toFixed(2)) :
                            this.state.month.month_id == 3 ?
                                String(item[9] == undefined || item[9] == 'Infinity' || item[9] == '-Infinity' ? "0.0" : Number(item[9]).toFixed(2)) :
                                this.state.month.month_id == 4 ?
                                    String(item[10] == undefined || item[10] == 'Infinity' || item[10] == '-Infinity' ? "0.0" : Number(item[10]).toFixed(2)) :
                                    this.state.month.month_id == 5 ?
                                        String(item[11] == undefined || item[11] == 'Infinity' || item[11] == '-Infinity' ? "0.0" : Number(item[11]).toFixed(2)) :
                                        this.state.month.month_id == 6 ?
                                            String(item[12] == undefined || item[12] == 'Infinity' || item[12] == '-Infinity' ? "0.0" : Number(item[12]).toFixed(2)) :
                                            this.state.month.month_id == 7 ?
                                                String(item[13] == undefined || item[13] == 'Infinity' || item[13] == '-Infinity' ? "0.0" : Number(item[13]).toFixed(2)) :
                                                this.state.month.month_id == 8 ?
                                                    String(item[14] == undefined || item[14] == 'Infinity' || item[14] == '-Infinity' ? "0.0" : Number(item[14]).toFixed(2)) :
                                                    this.state.month.month_id == 9 ?
                                                        String(item[15] == undefined || item[15] == 'Infinity' || item[15] == '-Infinity' ? "0.0" : Number(item[15]).toFixed(2)) :
                                                        this.state.month.month_id == 10 ?
                                                            String(item[16] == undefined || item[16] == 'Infinity' || item[16] == '-Infinity' ? "0.0" : Number(item[16]).toFixed(2)) :
                                                            this.state.month.month_id == 11 ?
                                                                String(item[17] == undefined || item[17] == 'Infinity' || item[17] == '-Infinity' ? "0.0" : Number(item[17]).toFixed(2)) :
                                                                String(item[18] == undefined || item[18] == 'Infinity' || item[18] == '-Infinity' ? "0.0" : Number(item[18]).toFixed(2))
                    // "january": String(item[7] == undefined? item[7] : Number(item[7]).toFixed(1)),
                    // "february": String(item[8] == undefined? item[8] : Number(item[8]).toFixed(1)),
                    // "march": String(item[9] == undefined? item[9] : Number(item[9]).toFixed(1)),
                    // "april": String(item[10] == undefined? item[10] : Number(item[10]).toFixed(1)),
                    // "may": String(item[11] == undefined? item[11] : Number(item[11]).toFixed(1)),
                    // "june": String(item[12] == undefined? item[12] : Number(item[12]).toFixed(1)),
                    // "july": String(item[13] == undefined? item[13] : Number(item[13]).toFixed(1)),
                    // "august": String(item[14] == undefined? item[14] : Number(item[14]).toFixed(1)),
                    // "september": String(item[15] == undefined? item[15] : Number(item[15]).toFixed(1)),
                    // "october": String(item[16] == undefined? item[16] : Number(item[16]).toFixed(1)),
                    // "november": String(item[17] == undefined? item[17] : Number(item[17]).toFixed(1)),
                    // "december": String(item[18] == undefined? item[18] : Number(item[18]).toFixed(1)),
                    // "total_next_year": String(item[19] != ''? Number(item[19]).toFixed(1) : item[19]),
                    // "total_more_year": String(item[20] != ''? Number(item[20]).toFixed(1) : item[20]),
                }
            )

        })

        console.log(listFR)
        console.log('subOD', this.state.submissionID)
        this.setState({ dbFR: listFR }, () => {
            if (this.state.monthlyReportId != null) {
                this.createDBFR()
            }
        })
    }

    createDBFR() {
        let payload = {
            // "submission_id": this.state.submissionID,
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "report_id": 29,
            "status": "submitted",
            "ratio_id": this.state.FRID,
            "ratio_mr": this.state.dbFR,
            "months": this.state.month.month_id,
        }
        // console.log(this.state.dbCF)
        console.log(JSON.stringify(payload))
        api.create().createReportFRMR(payload).then((res) => {
            console.log(res)
            // if (response.data) {
            //     if (response.data.status === "success") {
            //         this.props.saveToMonthlyReport()
            //     } else {
            //         this.setState({ loading: false }, () => {
            //             this.props.saveToMonthlyReport()
            //         })
            //     }
            // } else {
            //     this.setState({ loading: false }, () => {
            //         // this.getSubmission()
            //         document.body.style.overflow = 'unset';
            //     })
            // }
        })
    }

    handleApproveAdmin(master_report_type_id) {
        this.setState({ visibleApproveSuperadmin: true, currentMasterReportTypeId: master_report_type_id })
    }

    handleSelectAll(data) {
        if (this.state.isCheckAll) {
            let checkAll = []
            this.setState({ selectReport: checkAll, isCheckAll: false })
        } else {
            let checkAll = this.state.selectReport
            let isAllDetail = true
            // console.log(checkAll, this.state.selectReport, data);
            data.map((item, index) => {
                if (item[5] === true || this.state.periode.periode <= 2022) {
                    if (!this.state.selectReport.includes(item[4])) {
                        checkAll.push(item[4])
                    }
                } else {
                    isAllDetail = false
                    checkAll.splice(index, 1)
                }
            })
            console.log(checkAll);
            this.setState({ selectReport: checkAll, isCheckAll: isAllDetail })
        }
    }

    handleItemChecked(item) {
        let indexID = this.state.selectReport.findIndex((val) => val === item.rowData[4])
        return indexID === -1 ? false : true
    }

    handleItemClick(item) {
        let indexID = this.state.selectReport.findIndex((val) => val === item.rowData[4])
        let selectReport = this.state.selectReport
        if (indexID === -1) {
            selectReport.push(item.rowData[4])
        } else {
            selectReport.splice(indexID, 1)
        }
        let isCheckAll = selectReport.length === this.state.dataTable.length
        this.setState({ selectReport, isCheckAll })
        console.log(selectReport);
    }

    handleDownloadReport(tableMeta) {
        let { selectReport, company, periode, month, defaultCurrency } = this.state
        let payload = {
            "company_id": company.company_id,
            "year": periode.periode,
            "report_id": selectReport,
            "month": month ? String(month.month_id).toString() : "",
            "quartal": "",
            "type_report_name": "Monthly Report",
            "currency_id": defaultCurrency.id
        }
        console.log(payload);
        api.create().createDownloadFile(payload).then((response) => {
            console.log(response)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === 'success') {
                        let data = response.data.data
                        this.setState({ downloadedFileReportId: data.downloadedFileReportId, popupDownload: true }, () => this.handleGenerateReport(tableMeta))
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            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.data.message, tipeAlert: 'error' })
                }
            } else {
                // this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error'})
                alert(response.problem)
            }
        })
    }

    // componentDidUpdate = (prevProps, prevState) => {
    //     if (this.state.selectReport.length > 0 && (this.state.arrayReport.length == this.state.selectReport.length)) {
    //         setTimeout(() => {
    //             this.handleZip()
    //         }, 200);
    //     }
    // }

    async handleGenerateReport(data) {
        let { selectReport, monthlyReportId, company, periode, revisionTable, month, downloadedFileReportId, defaultCurrency } = this.state
        if (selectReport.length > 0) {
            let result = []
            console.log('mulai hit')
            for (const items of selectReport) {
                let urlReport = items === 8 ? "profit_loss" : items === 12 ? "tax_planning" : items === 7 ? "balance_sheet" : items === 9 ? "fam" : items === 13 ? "cash_flow" : items === 10 ? "cat" : null
                let datas = data.findIndex((val) => val[4] == items)
                let report = data[datas]
                if (items !== 11) {
                    try {
                        let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/${urlReport}/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}&&currency_id=${defaultCurrency.id}`
                        let res = await fetch(
                            `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/${urlReport}/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId === null ? "" : monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}&&currency_id=${defaultCurrency.id}`
                        )
                        if (res.status === 200) {
                            result = [...result, res];
                        }
                    } catch (error) {
                        alert(error)
                    }
                } else {
                    try {
                        let res1 = await fetch(
                            `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/locf/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId === null ? "" : monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}&&currency_id=${defaultCurrency.id}`
                        )
                        if (res1.status === 200) {
                            let res2 = await fetch(
                                `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/lov/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId === null ? "" : monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}&&currency_id=${defaultCurrency.id}`
                            )
                            if (res2.status === 200) {
                                result = [...result, res2];
                            }
                        }
                    } catch (error) {
                        alert(error)
                    }
                }
            }

            console.log('ini result', result);
            // every untuk cek ke setiap result di dalam array
            if (result.every((e) => e.status == 200)) {
                this.handleZip();
            }

            // selectReport.map(async (items) => {

            // if (items === 8) {
            //     let datas = data.findIndex((val) => val[4] == items)
            //     let report = data[datas]
            //     let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/profit_loss/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}`
            //     console.log(url);
            //     let res = await fetch(
            //         `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/profit_loss/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId === null ? "" : monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}`
            //     )
            //     console.log(res);
            //     if (res.status === 200) {
            //         this.setState({ arrayReport: [...this.state.arrayReport, items] })
            //     }
            // } else if (items === 12) {
            //     let datas = data.findIndex((val) => val[4] == items)
            //     let report = data[datas]
            //     let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/tax_planning/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}`
            //     console.log(url);
            //     let res = await fetch(
            //         `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/tax_planning/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId === null ? "" : monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}`
            //     )
            //     console.log(res);
            //     if (res.status === 200) {
            //         this.setState({ arrayReport: [...this.state.arrayReport, items] })
            //     }
            // } else if (items === 7) {
            //     let datas = data.findIndex((val) => val[4] == items)
            //     let report = data[datas]
            //     let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/balance_sheet/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}`
            //     console.log(url);
            //     let res = await fetch(
            //         `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/balance_sheet/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId === null ? "" : monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}`
            //     )
            //     console.log(res);
            //     if (res.status === 200) {
            //         this.setState({ arrayReport: [...this.state.arrayReport, items] })
            //     }
            // } else if (items === 9) {
            //     let datas = data.findIndex((val) => val[4] == items)
            //     let report = data[datas]
            //     let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/fam/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}`
            //     console.log(url);
            //     let res = await fetch(
            //         `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/fam/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId === null ? "" : monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}`
            //     )
            //     console.log(res);
            //     if (res.status === 200) {
            //         this.setState({ arrayReport: [...this.state.arrayReport, items] })
            //     }
            // } else if (items === 13) {
            //     let datas = data.findIndex((val) => val[4] == items)
            //     let report = data[datas]
            //     let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/cash_flow/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}`
            //     console.log(url);
            //     let res = await fetch(
            //         `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/cash_flow/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId === null ? "" : monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}`
            //     )
            //     console.log(res);
            //     if (res.status === 200) {
            //         this.setState({ arrayReport: [...this.state.arrayReport, items] })
            //     }
            // } else if (items === 11) {
            //     let datas = data.findIndex((val) => val[4] == items)
            //     let report = data[datas]
            //     let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/locf/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}`
            //     console.log(url);
            //     let res = await fetch(
            //         `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/locf/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId === null ? "" : monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}`
            //     )
            //     console.log(res);
            //     if (res.status === 200) {
            //         this.setState({ arrayReport: [...this.state.arrayReport, items] })
            //     }
            // } else if (items === 10) {
            //     let datas = data.findIndex((val) => val[4] == items)
            //     let report = data[datas]
            //     let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/cat/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}`
            //     console.log(url);
            //     let res = await fetch(
            //         `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/cat/monthly_report/export_monthly_report?monthly_report_id=${monthlyReportId === null ? "" : monthlyReportId}&&report_id=${report[4]}&&company_id=${company.company_id}&&year=${periode.periode}&&revision=${report[2]}&&months=${month.month_id}&&download_file_report_id=${downloadedFileReportId}`
            //     )
            //     console.log(res);
            //     if (res.status === 200) {
            //         this.setState({ arrayReport: [...this.state.arrayReport, items] })
            //     }
            // }

            // })
        } else {
            alert("Anda harus memilih report yang ingin di download terlebih dahulu!")
            this.setState({ popupDownload: false })
        }
    }

    async handleZip() {
        console.log('mulai zip')
        api.create().createZipReport(this.state.downloadedFileReportId).then((response) => {
            console.log(response)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === 'success') {
                        this.setState({ arrayReport: [] })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            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.data.message, tipeAlert: 'error' })
                }
            } else {
                // this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error'})
                alert(response.problem)
            }
        })
    }

    getLastStatus = () => {
        const { tableKey, lastStatus, lastStatusCat } = this.state
        return tableKey === 'CAT' ? lastStatusCat : lastStatus
    }

    getActiveMasterReportTypeId = () => {
        const { tableKey, rowDataFinance, rowDataCAT } = this.state
        const mstIdFinance = rowDataFinance?.length > 0 && rowDataFinance[0]?.master_report_type_id
        const mstIdCAT = rowDataCAT?.length > 0 && rowDataCAT[0]?.master_report_type_id
        return tableKey === 'CAT' ? mstIdCAT : mstIdFinance
    }

    getSubmissionObj = (tableKeyParam) => {
        const {
            tableKey,
            btnApprove,
            btnApproveCAT,
            lastStatus,
            lastStatusCat,
            submitter,
            submitterCAT,
            pic,
            picCAT,
            listAttachment,
            listAttachmentCAT
        } = this.state;

        const key = tableKeyParam ?? tableKey;

        return key === 2
            ? { btnApprove: btnApproveCAT, lastStatus: lastStatusCat, submitter: submitterCAT, pic: picCAT, listAttachment: listAttachmentCAT }
            : { btnApprove, lastStatus, submitter, pic, listAttachment };
    };

    renderFilter = () => {
        return (
            <div>
                <div style={{ display: 'flex' }}>
                    {/* {this.state.isApprover? 
                                            <div className="grid grid-2x" style={{}}>
                                                <div className="col-1" style={{ display: 'flex', maxWidth: '100%', paddingLeft: 0}}> 
                                                    <Autocomplete
                                                        {...this.state.listMonth}
                                                        id="month"
                                                        onChange={(event, newInputValue) => this.setState({ month: newInputValue, loading: true }, () => {
                                                            if (this.state.isApprover === true) {
                                                                    this.getCompanySubmitted()
                                                            } else {
                                                                this.setState({ visibleTableHistory: false })
                                                                this.getRevision()
                                                            }
                                                        })}
                                                        disableClearable
                                                        style={{ width: 250, marginRight: 20 }}
                                                        renderInput={(params) => <TextField {...params} label="Month" margin="normal" style={{ marginTop: 7 }} />}
                                                        value={this.state.month}
                                                    />
                                                    <Autocomplete
                                                        {...this.state.listPeriode}
                                                        id="periode"
                                                        onChange={(event, newInputValue) => this.setState({ periode: newInputValue, loading: true }, () => {
                                                            if (this.state.isApprover === true) {
                                                                this.getCompanySubmitted()
                                                            } else {
                                                                this.setState({ visibleTableHistory: false })
                                                                this.getRevision()
                                                            }
                                                        })}
                                                        disableClearable
                                                        style={{ width: 250 }}
                                                        renderInput={(params) => <TextField {...params} label="Period" margin="normal" style={{ marginTop: 7 }} />}
                                                        value={this.state.periode}
                                                    />
                                                </div>
                                                <div className="col-2" style={{ display: 'flex', justifyContent: 'flex-end', maxWidth: '100%', alignSelf: 'flex-end'}}>
                                                    <FormControlLabel
                                                        style={{ margin: 0 }}
                                                        value={this.state.submittedOnly}
                                                        control={
                                                            <Checkbox
                                                            checked={this.state.submittedOnly}
                                                            onClick={() => this.setState({submittedOnly: !this.state.submittedOnly, loading: true}, () => {
                                                                this.getChecApprover()
                                                                // console.log(this.state.company)
                                                                // this.setState({listCompany: this.state.submittedOnly? this.state.company_submit : this.state.company_active, company: this.state.listCompany != null? this.state.listCompany.options[0] : null})
                                                                // console.log(this.state.company_active)
                                                                // console.log(this.state.company_submit)
                                                                // console.log(this.state.company)
                                                                // console.log(this.state.submittedOnly)
                                                                // if (this.state.submittedOnly) {
                                                                //     this.getCompanySubmitted()
                                                                // } else {
                                                                //     this.getCompanyActive()
                                                                // }
                                                            })} />
                                                        }
                                                    />
                                                    <Typography style={{ fontSize: '16px', color: '#4b4b4b', fontWeight: 'bold', marginLeft: 5, alignSelf: 'center'}}>Submitted Only</Typography>
                                                </div>
                                            </div>
                                        :  */}
                    <div style={{ display: 'flex' }}>
                        <Autocomplete
                            {...this.state.listMonth}
                            id="month"
                            onChange={(event, newInputValue) => this.setState({ month: newInputValue, loading: true }, () => {
                                // if (this.state.isApprover === true) {
                                //     this.getCompanySubmitted()
                                // } else {
                                this.setState({ visibleTableHistory: false })
                                if (this.state.listCompany == null) {
                                    this.getCompanySubmitted()
                                } else {
                                    this.getRevision()
                                }
                                // }
                            })}
                            disableClearable
                            style={{ minWidth: 250, marginRight: 20 }}
                            renderInput={(params) => <TextField {...params} label="Month" margin="normal" style={{ marginTop: 7 }} />}
                            value={this.state.month}
                        />
                        <Autocomplete
                            {...this.state.listPeriode}
                            id="periode"
                            onChange={(event, newInputValue) => this.setState({ periode: newInputValue, loading: true }, () => {
                                // if (this.state.isApprover === true) {
                                //         this.getCompanySubmitted()
                                // } else {
                                this.setState({ visibleTableHistory: false })
                                if (this.state.listCompany == null) {
                                    this.getCompanySubmitted()
                                } else {
                                    this.getRevision()
                                }
                                // }
                            })}
                            disableClearable
                            style={{ width: 250 }}
                            renderInput={(params) => <TextField {...params} label="Period" margin="normal" style={{ marginTop: 7 }} />}
                            value={this.state.periode}
                        />
                    </div>

                    {/* } */}



                </div>
                <div style={{ display: 'flex', marginTop: 20 }}>
                    <Autocomplete
                        multiple
                        id="tags-standard"
                        options={this.state.listStatus}
                        getOptionLabel={(option) => option.name}
                        style={{ width: 250 }}
                        onChange={(event, newInputValue) => {
                            this.setState({ selectedStatus: newInputValue, loading: true }, () => {
                                console.log(newInputValue);
                                this.getCompanySubmitted()
                            })
                        }}
                        value={this.state.selectedStatus}
                        renderInput={(params) => <TextField {...params} label="Submission Status" margin="normal" style={{ marginTop: 7 }} />}
                    />

                    <Autocomplete
                        id="tipe"
                        disableClearable
                        options={this.state.currency}
                        getOptionLabel={(option) => option.value}
                        value={this.state.defaultCurrency}
                        // onChange={(event, newInputValue) => this.setState({ defaultCurrency: newInputValue })}
                        onChange={(event, newInputValue) => this.setState({ defaultCurrency: newInputValue }, () => {
                            this.getRevision()
                        })}
                        style={{ width: 250 }}
                        renderInput={(params) => <TextField {...params} label="Currency" margin="normal" style={{ marginTop: 7, marginLeft: 20 }} />}
                    // renderInput={(params) =>
                    //     <TextField
                    //         {...params}
                    //         variant="standard"
                    //         label="Currency"
                    //         margin="normal"
                    //         style={{ marginTop: 6 }}
                    //     // InputProps={{ ...params.InputProps, style: { fontSize: 11 } }}
                    //     // InputLabelProps={{ style: { fontSize: 11, color: '#7e8085' } }}
                    //     />
                    // }

                    />
                    {/* <Autocomplete
                                            {...this.state.listCompany}
                                            multiple
                                            id="company"
                                            disabled={this.state.listCompany === null ? true : false}
                                            onChange={(event, newInputValue) => this.setState({ company: newInputValue }, () => {
                                                this.getMonthlyReportID()
                                            })}
                                            style={{ width: 250 }}
                                            renderInput={(params) => <TextField {...params} label="Company" margin="normal" style={{ marginTop: 7 }} />}
                                            value={[this.state.listCompany[0]]}
                                        /> */}
                </div>
                <div style={{ marginTop: 20 }}>
                    <Autocomplete
                        {...this.state.listCompany}
                        id="company"
                        disabled={this.state.listCompany === null ? true : false}
                        onChange={(event, newInputValue) => this.setState({ company: newInputValue, loading: true }, () => {
                            this.getMonthlyReportID()
                            this.getCurrency(newInputValue.company_id)
                        })}
                        disableClearable
                        style={{ width: 250 }}
                        renderInput={(params) => <TextField {...params} label="Company" margin="normal" style={{ marginTop: 7 }} />}
                        value={this.state.company}
                    />
                </div>
                <div style={{ marginTop: 20 }}>
                    {/* <Autocomplete
                                            {...this.state.listRevision}
                                            id="revision"
                                            onChange={(event, newInputValue) => this.setState({ revision: newInputValue }, () => {
                                                this.getReport()
                                                this.getReportAttachment()
                                            })}
                                            debug
                                            disableClearable
                                            style={{ width: 250 }}
                                            renderInput={(params) => <TextField {...params} label="Revision" margin="normal" style={{ marginTop: 7 }} />}
                                            value={this.state.revision}
                                        /> */}
                    <TextField disabled={true} label="Revision" margin="normal" style={{ marginTop: 7, width: 250 }} value={this.state.lastRevision} />
                </div>
            </div>
        )
    }

    renderAttachment = (master_report_type_id) => {
        const _lastStatus = this.getLastStatus()
        const obj = this.getSubmissionObj(master_report_type_id)
        return (
            <>
                <div style={{ display: 'flex', marginTop: 20 }}>
                    <div style={{ width: '50%' }}>
                        <Typography style={{ fontSize: '16px', color: '#4b4b4b', fontWeight: 'bold' }}>Attachment: </Typography>
                    </div>
                    {!this.state.checkApprover && (_lastStatus === 'SUBMIT' || _lastStatus === 'REVISION') && (
                        <div style={{ width: '50%' }}>
                            <button
                                style={{
                                    backgroundColor: 'transparent',
                                    cursor: this.state.isSubmit === false ? 'default' : 'pointer',
                                    borderColor: 'transparent',
                                    outline: 'none'
                                }}
                                onClick={() => this.state.isSubmit === false ? null : this.setState({ visibleUpload: true, currentMasterReportTypeId: master_report_type_id })}
                            >
                                <Typography style={{ fontSize: '16px', color: this.state.isSubmit === false ? 'GrayText' : '#5198ea' }}>Upload File</Typography>
                            </button>
                        </div>
                    )}
                </div>
                <div style={{ display: 'flex', marginTop: 10 }}>
                    <div style={{ width: '50%', paddingLeft: 20 }}>
                        {obj.listAttachment.length > 0 ?
                            obj.listAttachment.map((item, index) => {
                                return (
                                    <div style={{ display: 'flex' }}>
                                        <Typography style={{ fontSize: '13px', color: '#4b4b4b', width: 25 }}>{index + 1}. </Typography>

                                        <button
                                            style={{
                                                backgroundColor: 'transparent',
                                                cursor: 'pointer',
                                                borderColor: 'transparent',
                                                outline: 'none',
                                                display: 'grid'
                                            }}
                                            onClick={() => {
                                                this.downloadAttachment(item.attachment_url, item.attachment_name)
                                            }}
                                        >
                                            <div>
                                                <Typography style={{ fontSize: '13px', color: '#5198ea' }}> {item.attachment_name}</Typography>
                                            </div>
                                        </button>
                                    </div>
                                )
                            })
                            : null
                        }
                    </div>
                    {!this.state.checkApprover && (_lastStatus === 'SUBMIT' || _lastStatus === 'REVISION') && (
                        <div style={{ width: '50%' }}>
                            {
                                obj.listAttachment.length > 0 ?
                                    obj.listAttachment.map((item) => {
                                        return (
                                            <button
                                                style={{
                                                    backgroundColor: 'transparent',
                                                    cursor: this.state.isSubmit === false ? 'default' : 'pointer',
                                                    borderColor: 'transparent',
                                                    outline: 'none',
                                                    display: 'grid'
                                                }}
                                                onClick={() => this.state.isSubmit === false ? null : this.deleteAttachment(item)}
                                            >
                                                <Typography style={{ fontSize: '13px', color: this.state.isSubmit === false ? 'GrayText' : '#ff3939' }}>Delete</Typography>
                                            </button>
                                        )
                                    })
                                    : null
                            }
                        </div>
                    )}
                </div>
            </>
        )
    }

    renderHistoryInfo = (master_report_type_id) => {
        const obj = this.getSubmissionObj(master_report_type_id)
        return (
            this.state.approverTrue === true ?
                obj.lastStatus === 'WAITING FOR REVIEW' ?
                    <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                        <span>{obj.lastStatus}</span>
                    </div> : obj.lastStatus === 'WAITING FOR YOUR APPROVAL' ?
                        <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                            <span>{obj.lastStatus}</span>
                        </div> : obj.lastStatus === 'WAITING FOR APPROVAL' ?
                            <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                                <span>{`${obj.lastStatus} - ${obj.pic}`}</span>
                            </div> : obj.lastStatus === 'REVISION' ?
                                <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                                    <span>{this.state.textRevision}</span>
                                </div> : obj.lastStatus === 'APPROVED' ?
                                    <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                                        <span>{`${obj.lastStatus}`}</span>
                                    </div> : null
                :
                obj.lastStatus === 'SUBMITTED' ?
                    <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                        <span>{obj.lastStatus}</span>
                    </div> :
                    obj.lastStatus === 'WAITING FOR APPROVAL' ?
                        <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                            <span>{`${obj.lastStatus} - ${obj.pic}`}</span>
                        </div> :
                        obj.lastStatus === 'REVISION' ?
                            <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                                <span>{this.state.textRevision}</span>
                            </div> :
                            obj.lastStatus === 'APPROVED' ?
                                <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                                    <span>APPROVED</span>
                                </div> : null

        )
    }

    renderBtnSubmit = (master_report_type_id) => {
        const obj = this.getSubmissionObj(master_report_type_id)
        return (
            this.state.isAdmin && obj.lastStatus === 'APPROVED' ?
                <div className="grid grid-2x" style={{ borderTop: 'solid 1px #c4c4c4', padding: 10, backgroundColor: '#f5f5f5', width: '100%', }}>
                    <div className="col-1" />
                    <div className="col-2" style={{ display: 'flex', justifyContent: 'flex-end', maxWidth: '100%' }}>
                        <button
                            style={{
                                backgroundColor: 'transparent',
                                cursor: 'pointer',
                                borderColor: 'transparent',
                                outline: 'none',
                                marginRight: 20
                            }}
                            onClick={() => this.setState({ visibleRevision: true, currentMasterReportTypeId: master_report_type_id })}
                        >
                            <div style={{ backgroundColor: '#019ce5', width: 105, height: 25, borderRadius: 3, justifyContent: 'center', display: 'flex', alignItems: 'center' }}>
                                <Typography style={{ fontSize: '11px', color: '#fff', textAlign: 'center' }}>Revision</Typography>
                            </div>
                        </button>
                        {/* <button
                                                style={{
                                                    backgroundColor: 'transparent',
                                                    cursor: 'pointer',
                                                    borderColor: 'transparent',
                                                    outline: 'none',
                                                }}
                                                onClick={() => this.approvalSubmission('approve')}
                                            >
                                                <div style={{ backgroundColor: '#354960', width: 105, height: 25, borderRadius: 3, justifyContent: 'center', display: 'flex', alignItems: 'center' }}>
                                                    <Typography style={{ fontSize: '11px', color: '#fff', textAlign: 'center' }}>Approve</Typography>
                                                </div>
                                            </button> */}
                    </div>
                </div>
                :
                this.state.isAdmin && (obj.lastStatus === 'WAITING FOR YOUR APPROVAL' || obj.lastStatus === 'WAITING FOR APPROVAL') ?
                    <div className="grid grid-2x" style={{ borderTop: 'solid 1px #c4c4c4', padding: 10, backgroundColor: '#f5f5f5', width: '100%', }}>
                        <div className="col-1" />
                        <div className="col-2" style={{ display: 'flex', justifyContent: 'flex-end', maxWidth: '100%' }}>
                            <button
                                style={{
                                    backgroundColor: 'transparent',
                                    cursor: 'pointer',
                                    borderColor: 'transparent',
                                    outline: 'none',
                                }}
                                onClick={() => this.handleApproveAdmin(master_report_type_id)}
                            >
                                <div style={{ backgroundColor: '#354960', width: 105, height: 25, borderRadius: 3, justifyContent: 'center', display: 'flex', alignItems: 'center' }}>
                                    <Typography style={{ fontSize: '11px', color: '#fff', textAlign: 'center' }}>Approve</Typography>
                                </div>
                            </button>
                        </div>
                    </div>
                    :
                    this.state.checkApprover ?
                        obj.lastStatus === 'WAITING FOR REVIEW' ?
                            <div style={{ borderTop: 'solid 1px #c4c4c4', padding: 10, backgroundColor: '#f5f5f5', width: '100%', display: 'flex', justifyContent: 'flex-end' }} >
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent',
                                        outline: 'none',
                                    }}
                                    onClick={() =>
                                        this.approvalSubmission('review', master_report_type_id)
                                    }
                                >
                                    <div style={{ backgroundColor: '#354960', width: 105, height: 25, borderRadius: 3, justifyContent: 'center', display: 'flex', alignItems: 'center' }}>
                                        <Typography style={{ fontSize: '11px', color: '#fff', textAlign: 'center' }}>Review</Typography>
                                    </div>
                                </button>
                            </div> : (obj.lastStatus === 'WAITING FOR YOUR APPROVAL' && obj.btnApprove) ?
                                <div className="grid grid-2x" style={{ borderTop: 'solid 1px #c4c4c4', padding: 10, backgroundColor: '#f5f5f5', width: '100%', }}>
                                    <div className="col-1" />
                                    <div className="col-2" style={{ display: 'flex', justifyContent: 'flex-end', maxWidth: '100%' }}>
                                        <button
                                            style={{
                                                backgroundColor: 'transparent',
                                                cursor: 'pointer',
                                                borderColor: 'transparent',
                                                outline: 'none',
                                                marginRight: 20
                                            }}
                                            onClick={() => this.setState({ visibleRevision: true, currentMasterReportTypeId: master_report_type_id })}
                                        >
                                            <div style={{ backgroundColor: '#019ce5', width: 105, height: 25, borderRadius: 3, justifyContent: 'center', display: 'flex', alignItems: 'center' }}>
                                                <Typography style={{ fontSize: '11px', color: '#fff', textAlign: 'center' }}>Revision</Typography>
                                            </div>
                                        </button>
                                        <button
                                            style={{
                                                backgroundColor: 'transparent',
                                                cursor: 'pointer',
                                                borderColor: 'transparent',
                                                outline: 'none',
                                            }}
                                            onClick={() => this.approvalSubmission('approve', master_report_type_id)}
                                        >
                                            <div style={{ backgroundColor: '#354960', width: 105, height: 25, borderRadius: 3, justifyContent: 'center', display: 'flex', alignItems: 'center' }}>
                                                <Typography style={{ fontSize: '11px', color: '#fff', textAlign: 'center' }}>Approve</Typography>
                                            </div>
                                        </button>
                                    </div>
                                </div> : null
                        :
                        (obj.lastStatus === 'SUBMIT' || obj.lastStatus === 'REVISION') && this.state.isSubmit ?
                            <div style={{ borderTop: 'solid 1px #c4c4c4', padding: 10, backgroundColor: '#f5f5f5', width: '100%', display: 'flex', justifyContent: 'flex-end' }} >
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent',
                                        outline: 'none',
                                    }}
                                    onClick={() => this.validate(master_report_type_id)}
                                >
                                    <div style={{ backgroundColor: '#354960', width: 105, height: 25, borderRadius: 3, justifyContent: 'center', display: 'flex', alignItems: 'center' }}>
                                        <Typography style={{ fontSize: '11px', color: '#fff', textAlign: 'center' }}>Submit</Typography>
                                    </div>
                                </button>
                            </div> :
                            obj.lastStatus === 'SUBMITTED' && obj.submitter ?
                                <div style={{ borderTop: 'solid 1px #c4c4c4', padding: 10, backgroundColor: '#f5f5f5', width: '100%', display: 'flex', justifyContent: 'flex-end' }} >
                                    <button
                                        style={{
                                            backgroundColor: 'transparent',
                                            cursor: 'pointer',
                                            borderColor: 'transparent',
                                            outline: 'none',
                                        }}
                                        onClick={() => this.approvalSubmission('cancel', master_report_type_id)}
                                    >
                                        <div style={{ backgroundColor: 'gray', width: 105, height: 25, borderRadius: 3, justifyContent: 'center', display: 'flex', alignItems: 'center' }}>
                                            <Typography style={{ fontSize: '11px', color: '#fff', textAlign: 'center' }}>Cancel</Typography>
                                        </div>
                                    </button>
                                </div> : null

        )
    }

    renderApproveMB = (master_report_type_id) => {
        if (this.state.isApprovedMB) return null
        return (
            <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                <span>Master Budget Has Not Been Approved</span>
            </div>
        )
    }

    render() {
        const columns = (tableKey) => ["#", "Report Type",
            {
                name: "Revision",
                options: {
                    customBodyRender: (val, tableMeta, updateValue) => {
                        var list = [];
                        for (var i = 0; i <= tableMeta.rowData[6]; i++) {
                            list.push(i);
                        }
                        return (
                            <div style={{ display: 'flex' }}>
                                <FormControlLabel
                                    style={{ margin: 0 }}
                                    value={val}
                                    control={
                                        <Select
                                            value={val}
                                            onChange={event => {
                                                // console.log(event.target)
                                                updateValue(event.target.value)
                                                this.handleChange(event.target.value, tableMeta, tableKey)
                                            }}
                                            autoWidth
                                        >
                                            {list.map((item, index) =>
                                                <MenuItem key={index} value={item}>{item}</MenuItem>
                                            )}
                                        </Select>
                                    }
                                />
                            </div >
                        );
                    }
                }
            }, {
                name: "Status",
                options: {
                    customBodyRender: (val, tableMeta) => {
                        return (
                            <div style={{ display: 'flex' }}>
                                {val === "submitted" || val === "approved" ?
                                    <span>COMPLETED</span> :
                                    val === "draft" ?
                                        <span>DRAFT</span> :
                                        val === "incomplete" ?
                                            <span>INCOMPLETE</span> :
                                            val === "revision" ?
                                                <span>REVISION</span> :
                                                val === "approval_process" ?
                                                    <span>APPROVAL PROCCESS</span> :
                                                    val === "approval_review" ?
                                                        <span>APPROVAL REVIEW</span> :
                                                        val === "not-yet" ?
                                                            <span>OPEN</span> :
                                                            val === "CLOSED" ?
                                                                <span>CLOSED</span> :
                                                                <img src={Images.cross} style={{ width: 31, height: 24 }} />
                                }
                            </div >
                        );
                    }
                }
            },
            {
                name: "Action",
                options: {
                    customBodyRender: (val, tableMeta) => {
                        return (
                            <div style={{ display: 'flex' }}>
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: tableMeta.rowData[5] ? 'pointer' : 'default',
                                        borderColor: 'transparent'
                                    }}
                                    onClick={() => {
                                        const { periode } = this.state.periode;
                                        const { rowData } = tableMeta;

                                        const canOpen =
                                            periode <= 2020 || rowData[5];

                                        if (canOpen) {
                                            this.clickDetail(
                                                rowData[1],
                                                rowData[4],
                                                rowData[2],
                                                rowData[3],
                                                tableKey
                                            );
                                        }
                                    }}
                                >
                                    <Typography style={{ color: this.state.periode.periode <= 2020 || tableMeta.rowData[5] ? '#5198ea' : 'GrayText', fontSize: 12, }}>Detail</Typography>
                                </button>
                            </div >
                        );
                    }
                }
            }, {
                name: "Download",
                options: {
                    customBodyRender: (val, tableMeta) => {
                        // console.log(tableMeta);
                        return (
                            <div style={{ display: 'flex' }}>
                                <CustomCheckbox
                                    checked={this.handleItemChecked(tableMeta)}
                                    onChange={() => this.state.periode.periode <= 2020 ? this.handleItemClick(tableMeta) : (tableMeta.rowData[5] ? this.handleItemClick(tableMeta) : null)}
                                    disabled={this.state.periode.periode <= 2020 ? false : (tableMeta.rowData[5] ? false : true)}
                                />
                            </div >
                        );
                    }
                }
            }, {
                name: "",
                options: { display: false }
            }, {
                name: "",
                options: { display: false }
            }]

        const columnsHistory = [
            "Name", "Status", "Remarks", "Revision Item", "Date"
        ]

        const options = {
            filter: false,
            sort: false,
            responsive: "scroll",
            print: false,
            download: false,
            selectableRows: false,
            viewColumns: false,
            pagination: false,
            search: false
        }

        const optionsHistory = {
            filter: false,
            sort: false,
            responsive: "scroll",
            print: false,
            download: false,
            selectableRows: false,
            viewColumns: false,
            pagination: true,
            search: false,
            rowsPerPage: 5
        }

        const optionsRevision = {
            filter: false,
            sort: false,
            responsive: "scroll",
            print: false,
            download: false,
            selectableRows: false,
            viewColumns: false,
            pagination: false,
            search: false
        }

        const handleMaxDate = () => {
            let handleDate = Number(moment(this.state.maxDateRevision).format('YYYYMMDD')) - Number(moment(this.state.minDateRevision).format('YYYYMMDD'))
            return handleDate < 0 ? moment(this.state.minDateRevision).format('YYYY/MM/DD') : moment(this.state.maxDateRevision).format('YYYY/MM/DD')
        }

        const handleChangeText = (value, tableMeta, master_report_type_id) => {
            const listTableRevision = master_report_type_id === 2 ? this.state.dataTableRevisionCAT : this.state.dataTableRevision
            listTableRevision[tableMeta.rowIndex][tableMeta.columnIndex] = value

            let detailRevisiCheck = this.state.detailRevisiCheck
            let indexId = detailRevisiCheck.findIndex((val) => val.report_id === tableMeta.rowData[0])
            if (indexId !== -1) {
                detailRevisiCheck[indexId].remarks = value
            }

            this.setState({ [master_report_type_id === 2 ? "dataTableRevisionCAT" : "dataTableRevision"]: listTableRevision, detailRevisiCheck })
        }

        const handleCheckRevision = (value, master_report_type_id) => {
            const listTableRevision = master_report_type_id === 2 ? this.state.dataTableRevisionCAT : this.state.dataTableRevision
            let detailRevisiCheck = this.state.detailRevisiCheck
            let payload = {
                report_id: value[0],
                remarks: value[2],
                number: value[3]
            }
            let indexDataRevisi = listTableRevision.findIndex((val) => val[3] == value[3])
            let indexId = detailRevisiCheck.sort((a, b) => a.number - b.number).findIndex((val) => val.number == value[3])
            // // console.log(indexId)
            if (indexId == -1) {
                listTableRevision.map((item, index) => {
                    if (index > indexDataRevisi) {
                        let indexIds = detailRevisiCheck.findIndex((val) => val.number == item[3])
                        if (indexIds == -1) {
                            let payload2 = {
                                report_id: item[0],
                                remarks: item[2],
                                number: item[3]
                            }
                            detailRevisiCheck.push(payload2)
                        }
                    }
                })
                detailRevisiCheck.push(payload)
            } else {

                let x = 0
                detailRevisiCheck.sort((a, b) => a.number - b.number).map((item, index) => {
                    if (item.number < value[3]) {
                        x += 1
                    }
                })
                if (x < 1) {
                    listTableRevision.map((item, index) => {
                        if (index > indexDataRevisi) {
                            let indexIdz = detailRevisiCheck.findIndex((val) => val.number == item[3])
                            if (indexIdz !== -1) {
                                detailRevisiCheck.splice(indexIdz, 1)
                            }
                        }
                    })
                    detailRevisiCheck.splice(indexId, 1)
                }
            }
            this.setState({ detailRevisiCheck: detailRevisiCheck.sort((a, b) => a.number - b.number) })
            // // console.log(detailRevisiCheck)
        }

        const columnRevisi = (master_report_type_id) => [
            {
                name: "#",
                options: {
                    customBodyRender: (val, tableMeta, updateValue) => {
                        var list = [];
                        for (var i = 0; i <= tableMeta.rowData[6]; i++) {
                            list.push(i);
                        }
                        return (
                            <div style={{ display: 'flex' }}>
                                <FormControlLabel
                                    style={{ margin: 0 }}
                                    value={val}
                                    control={
                                        <Checkbox
                                            checked={this.state.detailRevisiCheck.findIndex((val) => val.report_id == tableMeta.rowData[0]) == -1 ? false : true}
                                            onClick={() => handleCheckRevision(tableMeta.rowData, master_report_type_id)} />
                                    }
                                />
                            </div >
                        );
                    }
                }
            }, "Report Type",
            {
                name: 'Remarks',
                options: {
                    customBodyRender: (value, tableMeta, updateValue) => {
                        return (
                            <div style={{ textAlign: 'left' }}>
                                <FormControlLabel
                                    style={{ margin: 0 }}
                                    // value={value}
                                    control={
                                        <Input
                                            disableUnderline={true}
                                            style={{ fontSize: 12, textAlign: 'center', borderColor: 'transparent', margin: 0, width: 96, backgroundColor: 'transparent', marginTop: -10 }}
                                            type="text"
                                            placeholder=""
                                            defaultValue={value}
                                            color={"#5198ea"}
                                            onBlur={(event) => {
                                                // // // console.log(event.target.value)
                                                // updateValue(event.target.value)
                                                handleChangeText(event.target.value, tableMeta, master_report_type_id)
                                                // // // console.log(dataTable2)
                                            }}
                                        />}
                                />
                            </div>
                        )
                    }
                }
            }, {
                name: "",
                options: { display: false }
            }
        ]

        const loadingComponent = (
            <div style={{ position: 'fixed', 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>
        );

        const mstIdFinance = this.state?.rowDataFinance?.length > 0 && this.state.rowDataFinance[0]?.master_report_type_id
        const mstIdCAT = this.state?.rowDataCAT?.length > 0 && this.state.rowDataCAT[0]?.master_report_type_id
        return (
            <div style={{ flex: 1, backgroundColor: '#f8f8f8', overflow: 'scroll' }}>
                <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
                    <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
                        {this.state.messageAlert}
                    </Alert>
                </Snackbar>
                {this.state.loading && loadingComponent}
                {this.state.visibleMonthlyReport && (
                    <div>
                        <div className={"main-color"} style={{ height: 78, display: 'flex', alignItems: 'center', paddingLeft: 20 }}>
                            <Typography style={{ fontSize: '16px', color: 'white' }}>Monthly Report Submission</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 }}>Monthly Report</Typography>
                                </div>
                                <div style={{ padding: 20 }}>
                                    {this.renderFilter()}

                                    <div style={{ marginTop: 20 }}>
                                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                            <Typography style={{ fontSize: '16px', color: '#4b4b4b', fontWeight: 'bold' }}>Report Finance</Typography>
                                            <div style={{ display: 'flex', margin: '24px 5px' }}>
                                                <button
                                                    className="button"
                                                    type="button"
                                                    style={{
                                                        backgroundColor: 'transparent',
                                                        cursor: 'pointer',
                                                        borderColor: 'transparent',
                                                        outline: 'none',
                                                        marginRight: 20
                                                    }}
                                                    onClick={() => this.handleSelectAll(this.state.dataTable)}
                                                >
                                                    <div style={{ backgroundColor: '#fff', width: 100, height: 25, borderRadius: 3, justifyContent: 'center', display: 'flex', alignItems: 'center', border: 'solid 1px #354960' }}>
                                                        <Typography style={{ fontSize: '11px', color: '#354960', textAlign: 'center' }}>Check All</Typography>
                                                    </div>
                                                </button>
                                                <button
                                                    type="button"
                                                    disabled={this.state.buttonError}
                                                    onClick={() => this.state.selectReport.length > 0 ? this.handleDownloadReport(this.state.dataTable) : alert("Anda harus memilih report yang ingin di download terlebih dahulu!")}
                                                    style={{
                                                        backgroundColor: 'transparent',
                                                        borderColor: 'transparent',
                                                        outline: 'none',
                                                    }}
                                                >
                                                    <div style={{ backgroundColor: '#354960', width: 100, height: 25, borderRadius: 3, justifyContent: 'center', display: 'flex', alignItems: 'center' }}>
                                                        <Typography style={{ fontSize: '11px', color: '#fff', textAlign: 'center' }}>Download</Typography>
                                                    </div>
                                                </button>
                                            </div>
                                        </div>
                                        <MuiThemeProvider theme={getMuiTheme()}>
                                            <MUIDataTable
                                                data={this.state.dataTable}
                                                columns={columns('FINANCE')}
                                                options={options}
                                            />
                                        </MuiThemeProvider>
                                    </div>
                                    {this.renderAttachment(mstIdFinance)}
                                    {this.renderApproveMB(mstIdFinance)}
                                    {this.renderHistoryInfo(mstIdFinance)}
                                    {this.state.visibleTableHistory && (
                                        <div style={{ marginTop: 20 }}>
                                            <MuiThemeProvider theme={getMuiTheme()}>
                                                <MUIDataTable
                                                    data={this.state.dataTableHistory}
                                                    columns={columnsHistory}
                                                    options={optionsHistory}
                                                />
                                            </MuiThemeProvider>
                                        </div>
                                    )}
                                </div>
                                {((this.state.checkApprover && this.state.isApproverFinance) || this.state.submitter) && this.renderBtnSubmit(mstIdFinance)}
                                <div style={{ padding: '0 20px 20px' }}>
                                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                        <Typography style={{ fontSize: '16px', color: '#4b4b4b', fontWeight: 'bold' }}>Report CAT</Typography>
                                        <div style={{ display: 'flex', margin: '24px 5px' }}>
                                            <button
                                                type="button"
                                                disabled={this.state.buttonError}
                                                onClick={() => this.state.selectReport.length > 0 ? this.handleDownloadReport(this.state.dataTableCAT) : alert("Anda harus memilih report yang ingin di download terlebih dahulu!")}
                                                style={{
                                                    backgroundColor: 'transparent',
                                                    borderColor: 'transparent',
                                                    outline: 'none',
                                                }}
                                            >
                                                <div style={{ backgroundColor: '#354960', width: 100, height: 25, borderRadius: 3, justifyContent: 'center', display: 'flex', alignItems: 'center' }}>
                                                    <Typography style={{ fontSize: '11px', color: '#fff', textAlign: 'center' }}>Download</Typography>
                                                </div>
                                            </button>
                                        </div>
                                    </div>
                                    <MuiThemeProvider theme={getMuiTheme()}>
                                        <MUIDataTable
                                            data={this.state.dataTableCAT}
                                            columns={columns('CAT')}
                                            options={options}
                                        />
                                    </MuiThemeProvider>
                                    {this.renderAttachment(mstIdCAT)}
                                    {this.renderApproveMB(mstIdCAT)}
                                    {this.renderHistoryInfo(mstIdCAT)}
                                    {this.state.visibleTableHistoryCAT && (
                                        <div style={{ marginTop: 20 }}>
                                            <MuiThemeProvider theme={getMuiTheme()}>
                                                <MUIDataTable
                                                    data={this.state.dataTableHistoryCAT}
                                                    columns={columnsHistory}
                                                    options={optionsHistory}
                                                />
                                            </MuiThemeProvider>
                                        </div>
                                    )}
                                </div>
                                {((this.state.checkApprover && this.state.isApproverCAT) || this.state.submitterCAT) && this.renderBtnSubmit(mstIdCAT)}
                            </Paper>

                        </div>
                    </div>
                )}

                {this.state.visibleUpload && (
                    <div className="test app-popup-show">
                        <div className="popup-content background-white border-radius" style={{ borderRadius: 8 }}>
                            <div className="popup-panel grid grid-2x main-color" style={{ height: 64, borderTopRightRadius: 8, borderTopLeftRadius: 8 }}>
                                <div className="col-1" style={{ maxWidth: "inherit", display: 'flex', alignItems: 'center' }}>
                                    <div className="popup-title">
                                        <span style={{ color: '#fff', fontSize: 16, fontWeight: 'bold' }}>Upload File</span>
                                    </div>
                                </div>
                                <div className="col-2 content-right" style={{ maxWidth: "inherit", alignSelf: 'center' }}>
                                    <button
                                        type="button"
                                        className="btn btn-circle btn-white"
                                        onClick={() => this.setState({ visibleUpload: false, currentMasterReportTypeId: null })}
                                    >
                                        <img src={Images.close} />
                                    </button>
                                </div>
                            </div>
                            <UploadFile
                                type={this.state.uploadStatus}
                                percentage={this.state.percentage}
                                result={this.state.result}
                                acceptedFiles={["xlsx"]}
                                onHandle={(dt) => {
                                    this.fileHandler(dt)
                                    this.setState({ uploadStatus: 'idle', percentage: '0' })
                                }}
                                onUpload={() => this.uploadAttachment(this.state.formData)}
                            />
                        </div>
                    </div>
                )}

                {this.state.visibleBS && (
                    <BalanceSheetMR
                        open={this.props.open}
                        report_id={this.state.report_id}
                        height={this.props.height}
                        width={this.props.width}
                        company={this.state.company}
                        defaultCurrency={this.state.defaultCurrency}
                        currency={this.state.currency}
                        revision={this.state.revisionTable}
                        periode={this.state.periode.periode}
                        monthlyReportId={this.state.monthlyReportId}
                        month={this.state.month}
                        saveToMonthlyReport={this.saveToMonthlyReport.bind(this)}
                        onClickClose={() => this.setState({ visibleBS: false, visibleMonthlyReport: true })}
                        isApprover={this.state.isApprover}
                        status={this.state.status}
                        lastStatus={this.getLastStatus()}
                        master_report_type_id={this.getActiveMasterReportTypeId()}
                        prevRevision={this.state.isSubmit ? this.state.prevRevision : true}
                        createCF={this.createCashFlow.bind(this)}
                    // getReport={this.getCompanyActive.bind(this)}
                    />
                )}
                {this.state.visiblePL && (
                    <ProfitLossMR
                        open={this.props.open}
                        report_id={this.state.report_id}
                        height={this.props.height}
                        width={this.props.width}
                        company={this.state.company}
                        defaultCurrency={this.state.defaultCurrency}
                        currency={this.state.currency}
                        revision={this.state.revisionTable}
                        periode={this.state.periode.periode}
                        monthlyReportId={this.state.monthlyReportId}
                        month={this.state.month}
                        saveToMonthlyReport={this.saveToMonthlyReport.bind(this)}
                        onClickClose={() => this.setState({ visiblePL: false, visibleMonthlyReport: true })}
                        isApprover={this.state.isApprover}
                        status={this.state.status}
                        lastStatus={this.getLastStatus()}
                        master_report_type_id={this.getActiveMasterReportTypeId()}
                        prevRevision={this.state.isSubmit ? this.state.prevRevision : true}
                        createCF={this.createCashFlow.bind(this)}
                    // getReport={this.getCompanyActive.bind(this)}
                    />

                )}
                {this.state.visibleTP && (
                    <TaxPlanningMR
                        open={this.props.open}
                        report_id={this.state.report_id}
                        height={this.props.height}
                        width={this.props.width}
                        company={this.state.company}
                        defaultCurrency={this.state.defaultCurrency}
                        currency={this.state.currency}
                        revision={this.state.revisionTable}
                        periode={this.state.periode.periode}
                        monthlyReportId={this.state.monthlyReportId}
                        month={this.state.month}
                        saveToMonthlyReport={this.saveToMonthlyReport.bind(this)}
                        onClickClose={() => this.setState({ visibleTP: false, visibleMonthlyReport: true })}
                        btnCreate={this.state.btnCreate}
                        loadview={this.state.loadview}
                        isApprover={this.state.isApprover}
                        status={this.state.status}
                        lastStatus={this.getLastStatus()}
                        master_report_type_id={this.getActiveMasterReportTypeId()}
                        // getReport={this.getCompanyActive.bind(this)}
                        prevRevision={this.state.isSubmit ? this.state.prevRevision : true}
                    />
                )}
                {this.state.visibleFAM && (
                    <FixedAssetsMovementMR
                        open={this.props.open}
                        report_id={this.state.report_id}
                        height={this.props.height}
                        width={this.props.width}
                        company={this.state.company}
                        defaultCurrency={this.state.defaultCurrency}
                        currency={this.state.currency}
                        revision={this.state.revisionTable}
                        periode={this.state.periode.periode}
                        monthlyReportId={this.state.monthlyReportId}
                        month={this.state.month}
                        saveToMonthlyReport={this.saveToMonthlyReport.bind(this)}
                        onClickClose={() => this.setState({ visibleFAM: false, visibleMonthlyReport: true })}
                        isApprover={this.state.isApprover}
                        status={this.state.status}
                        lastStatus={this.getLastStatus()}
                        master_report_type_id={this.getActiveMasterReportTypeId()}
                        createCF={this.createCashFlow.bind(this)}
                        prevRevision={this.state.isSubmit ? this.state.prevRevision : true}
                    />
                )}
                {this.state.visibleCAT && (
                    <CorporateAnnualTargetMR
                        open={this.props.open}
                        report_id={this.state.report_id}
                        height={this.props.height}
                        width={this.props.width}
                        company={this.state.company}
                        defaultCurrency={this.state.defaultCurrency}
                        currency={this.state.currency}
                        revision={this.state.revisionTable}
                        periode={this.state.periode.periode}
                        monthlyReportId={this.state.monthlyReportId}
                        month={this.state.month}
                        saveToMonthlyReport={this.saveToMonthlyReport.bind(this)}
                        onClickClose={() => this.setState({ visibleCAT: false, visibleMonthlyReport: true })}
                        isApprover={this.state.isApprover}
                        status={this.state.status}
                        // status={'not-yet'}
                        // lastStatus={'SUBMIT'}
                        lastStatus={this.getLastStatus()}
                        master_report_type_id={this.getActiveMasterReportTypeId()}
                        prevRevision={this.state.isSubmit ? this.state.prevRevision : true}
                    />
                )}
                {this.state.visibleLOCF && (
                    <ListOfCreditFacilities
                        open={this.props.open}
                        report_id={this.state.report_id}
                        height={this.props.height}
                        width={this.props.width}
                        company={this.state.company}
                        defaultCurrency={this.state.defaultCurrency}
                        currency={this.state.currency}
                        revision={this.state.revisionTable}
                        periode={this.state.periode.periode}
                        monthlyReportId={this.state.monthlyReportId}
                        month={this.state.month}
                        saveToMonthlyReport={this.saveToMonthlyReport.bind(this)}
                        onClickClose={() => this.setState({ visibleLOCF: false, visibleMonthlyReport: true })}
                        isApprover={this.state.isApprover}
                        status={this.state.status}
                        lastStatus={this.getLastStatus()}
                        master_report_type_id={this.getActiveMasterReportTypeId()}
                        prevRevision={this.state.isSubmit ? this.state.prevRevision : true}
                    />
                )}

                {this.state.visibleOI && (
                    <OperatingIndicatorMR
                        open={this.props.open}
                        report_id={this.state.report_id}
                        height={this.props.height}
                        width={this.props.width}
                        company={this.state.company}
                        defaultCurrency={this.state.defaultCurrency}
                        currency={this.state.currency}
                        revision={this.state.revisionTable}
                        periode={this.state.periode.periode}
                        monthlyReportId={this.state.monthlyReportId}
                        month={this.state.month}
                        onClickClose={() => this.setState({ visibleOI: false, visibleMonthlyReport: true })}
                        status={this.state.status}
                        lastStatus={this.getLastStatus()}
                        prevRevision={this.state.isSubmit ? this.state.prevRevision : true}
                    />
                )}

                {this.state.visibleCF && (
                    <CashFlowMR
                        open={this.props.open}
                        report_id={this.state.report_id}
                        height={this.props.height}
                        width={this.props.width}
                        company={this.state.company}
                        defaultCurrency={this.state.defaultCurrency}
                        currency={this.state.currency}
                        revision={this.state.revisionTable}
                        periode={this.state.periode.periode}
                        monthlyReportId={this.state.monthlyReportId}
                        month={this.state.month}
                        onClickClose={() => this.setState({ visibleCF: false, visibleMonthlyReport: true })}
                        status={this.state.status}
                        // status={'not-yet'}
                        lastStatus={this.getLastStatus()}
                        isApprover={this.state.isApprover}
                        prevRevision={this.state.isSubmit ? this.state.prevRevision : true}
                        PLBSFAMSubmitted={this.getLastStatus() === 'APPROVED' ? true : false}
                        // PLBSFAMSubmitted={false}
                        createCashFlow={this.createCashFlow.bind(this)}
                    />
                )}

                {
                    this.state.visibleRevision && (
                        <div className="test app-popup-show">
                            <div className="popup-content background-white border-radius" style={{ borderRadius: 8 }}>
                                <div className="popup-panel grid grid-2x main-color" style={{ height: 64, borderTopRightRadius: 8, borderTopLeftRadius: 8 }}>
                                    <div className="col-1" style={{ maxWidth: "inherit", display: 'flex', alignItems: 'center' }}>
                                        <div className="popup-title">
                                            <span style={{ color: '#fff', fontSize: 16, fontWeight: 'bold' }}>Revision</span>
                                        </div>
                                    </div>
                                    <div className="col-2 content-right" style={{ maxWidth: "inherit", alignSelf: 'center' }}>
                                        <button
                                            type="button"
                                            className="btn btn-circle btn-white"
                                            onClick={() => this.setState({ visibleRevision: false, currentMasterReportTypeId: null })}
                                        >
                                            <img src={Images.close} />
                                        </button>
                                    </div>
                                </div>
                                <div className="border-bottom" style={{ padding: 20 }}>
                                    <span>You ask your subsidiary to make a revision</span>
                                    <div style={{ marginTop: 20 }}>
                                        <MuiThemeProvider theme={getMuiTheme()}>
                                            <MUIDataTable
                                                data={this.state.currentMasterReportTypeId === 2 ? this.state.dataTableRevisionCAT : this.state.dataTableRevision}
                                                columns={columnRevisi(this.state.currentMasterReportTypeId)}
                                                options={optionsRevision}
                                            />
                                        </MuiThemeProvider>
                                    </div>
                                    <div style={{ marginTop: 20 }}>
                                        <span>Timing duration you give for revision:</span>
                                        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 20 }}>
                                            <div>
                                                <DatePicker
                                                    margin="normal"
                                                    id="startDate"
                                                    label="Valid From"
                                                    format="dd-MM-yyyy"
                                                    onChange={(e) => this.setState({ minDateRevision: moment(e).format('YYYY/MM/DD') }, () => this.setState({ maxDateRevision: handleMaxDate() }))}
                                                    value={moment(this.state.minDateRevision).format('YYYY/MM/DD')}
                                                    KeyboardButtonProps={{
                                                        'aria-label': 'change date',
                                                    }}
                                                    inputProps={{
                                                        style: {
                                                            fontSize: 11
                                                        }
                                                    }}
                                                    InputLabelProps={{
                                                        style: {
                                                            fontSize: 11,
                                                            color: '#7e8085'
                                                        }
                                                    }}

                                                    style={{ padding: 0, margin: 0, width: '100%' }}
                                                />
                                            </div>
                                            <span style={{ alignSelf: 'center' }}>Until</span>
                                            <div>
                                                <DatePicker
                                                    margin="normal"
                                                    id="startDate"
                                                    label="Valid To"
                                                    format="dd-MM-yyyy"
                                                    onChange={(e) => this.setState({ maxDateRevision: moment(e).format('YYYY/MM/DD') })}
                                                    minDate={moment(this.state.minDateRevision).format('YYYY/MM/DD')}
                                                    value={moment(this.state.maxDateRevision).format('YYYY/MM/DD')}
                                                    KeyboardButtonProps={{
                                                        'aria-label': 'change date',
                                                    }}
                                                    inputProps={{
                                                        style: {
                                                            fontSize: 11
                                                        }
                                                    }}
                                                    InputLabelProps={{
                                                        style: {
                                                            fontSize: 11,
                                                            color: '#7e8085'
                                                        }
                                                    }}

                                                    style={{ padding: 0, margin: 0, width: '100%' }}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div className="border-top grid grid-2x" style={{ height: 56, backgroundColor: '#f5f5f5', paddingLeft: 20, paddingRight: 20 }}>
                                    <div className="column-1" style={{ alignSelf: 'center' }}>
                                        <button
                                            type="button"
                                            onClick={() => this.setState({ visibleRevision: false, currentMasterReportTypeId: null })}
                                        >
                                            <div style={{ width: 102, height: 30, border: 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                                <span style={{ color: '#354960', fontSize: 11 }}>Cancel</span>
                                            </div>
                                        </button>
                                    </div>
                                    <div className="column-2" style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
                                        <button
                                            type="button"
                                            onClick={() => this.validateRevision(this.state.currentMasterReportTypeId)}
                                        >
                                            <div style={{ width: 102, height: 30, backgroundColor: '#354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                                <span style={{ color: '#fff', fontSize: 11 }}>Revision</span>
                                            </div>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )
                }

                {this.state.visibleApproveSuperadmin && (
                    <div className="test app-popup-show">
                        <div className="popup-content background-white border-radius" style={{ borderRadius: 8 }}>
                            <div className="popup-panel grid grid-2x main-color" style={{ height: 64, borderTopRightRadius: 8, borderTopLeftRadius: 8 }}>
                                <div className="col-1" style={{ maxWidth: "inherit", display: 'flex', alignItems: 'center' }}>
                                    <div className="popup-title">
                                        <span style={{ color: '#fff', fontSize: 16, fontWeight: 'bold' }}>Superadmin Approve</span>
                                    </div>
                                </div>
                                <div className="col-2 content-right" style={{ maxWidth: "inherit", alignSelf: 'center' }}>
                                    <button
                                        type="button"
                                        className="btn btn-circle btn-white"
                                        onClick={() => this.setState({ visibleApproveSuperadmin: false, currentMasterReportTypeId: null })}
                                    >
                                        <img src={Images.close} />
                                    </button>
                                </div>
                            </div>
                            <div className="border-bottom" style={{ padding: 20 }}>
                                <span>Choose approver you want</span>
                                <div style={{ marginTop: 20 }}>
                                    <Autocomplete
                                        {...this.state.listApprover}
                                        id="periode"
                                        onChange={(event, newInputValue) => this.setState({ approver: newInputValue })}
                                        disabled={false}
                                        disableClearable
                                        style={{ width: 250 }}
                                        renderInput={(params) =>
                                            <TextField {...params} label="Approver" margin="normal" style={{ marginTop: 7 }}
                                            />}
                                        value={this.state.approver}
                                    />
                                </div>
                            </div>
                            <div className="border-top grid grid-2x" style={{ height: 56, backgroundColor: '#f5f5f5', paddingLeft: 20, paddingRight: 20 }}>
                                <div className="column-1" style={{ alignSelf: 'center' }}>
                                    <button
                                        type="button"
                                        onClick={() => this.setState({ visibleApproveSuperadmin: false, currentMasterReportTypeId: null })}
                                    >
                                        <div style={{ width: 102, height: 30, border: 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                            <span style={{ color: '#354960', fontSize: 11 }}>Cancel</span>
                                        </div>
                                    </button>
                                </div>
                                <div className="column-2" style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
                                    <button
                                        type="button"
                                        onClick={() => this.state.approver == null ? this.setState({ alert: true, messageAlert: 'Approver Cannot be Empty', tipeAlert: 'error' }) : this.setHeaderTokenSuperadmin('approve', this.state.currentMasterReportTypeId)}
                                    >
                                        <div style={{ width: 102, height: 30, backgroundColor: '#354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                            <span style={{ color: '#fff', fontSize: 11 }}>Confirm  Approve</span>
                                        </div>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {this.state.popupDownload && (
                    <div className="test app-popup-show">
                        <div className="popup-content border-radius" style={{ background: '#D9D9D9', borderRadius: 10, width: 609, height: 276 }}>
                            <div>
                                <div style={{ justifyContent: 'center', fontSize: 20, color: '#33508B', margin: '70px 20px' }}>Download Monthly Report {this.state.company.company_name} {this.state.month.month_value} {this.state.periode.periode} In Progress, silahkan cek status dan unduh report di menu <b>Download Report</b></div>
                                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                                    <button
                                        className="button"
                                        type="button"
                                        style={{
                                            background: '#F6F7F9',
                                            cursor: 'pointer',
                                            border: '1px solid #3549609e',
                                            outline: 'none',
                                            marginRight: 20,
                                            borderRadius: 3
                                        }}
                                        onClick={() => this.setState({ popupDownload: false })}
                                    >
                                        <div style={{ backgroundColor: '#fff', width: 105, height: 30, borderRadius: 3, justifyContent: 'center', display: 'flex', alignItems: 'center', border: 'solid 1px #3549609e' }}>
                                            <Typography style={{ fontSize: '15px', color: '#354960', textAlign: 'center' }}>Close</Typography>
                                        </div>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {this.state.visibleAlertSave && (
                    <div className="test app-popup-show">
                        <div className="popup-content border-radius" style={{ background: '#FFF27D', borderRadius: 10, width: 715, height: 238 }}>
                            <div style={{ margin: 30 }}>
                                <div style={{ display: 'flex', marginTop: 76, marginBottom: 43 }}>
                                    <div style={{ alignSelf: 'center', marginRight: 25 }}>
                                        <img src={Images.warning} />
                                    </div>
                                    <div style={{ justifyContent: 'center', fontSize: 20, color: '#1D2995', marginTop: 10 }}>
                                        <b>Rate Currency USD</b> pada periode yang dipilih <b>belum</b> diatur.<br /> Silahkan menghubungi Superadmin
                                    </div>
                                </div>
                                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                                    <button
                                        className="button"
                                        type="button"
                                        style={{
                                            background: '#F6F7F9',
                                            cursor: 'pointer',
                                            border: '1px solid #3549609e',
                                            outline: 'none',
                                            marginRight: 20,
                                            borderRadius: 9
                                        }}
                                        onClick={() => this.setState({ visibleAlertSave: false, loading: false })}
                                    >
                                        <div style={{ backgroundColor: '#fff', width: 105, height: 30, borderRadius: 9, justifyContent: 'center', display: 'flex', alignItems: 'center', border: 'solid 1px #3549609e' }}>
                                            <Typography style={{ fontSize: '15px', color: '#354960', textAlign: 'center' }}>Close</Typography>
                                        </div>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                )}
            </div >
        );
    }
}
