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 MuiAlert from '@material-ui/lab/Alert';
import { titleCase } from '../../library/Utils';
import ProfitLossOLPA from './ProfitLossOLPA';
import TaxPlanning from './TaxPlanningOLPA';
import CashFlow from './CashFlowOLPA';
import { ExcelRenderer } from 'react-excel-renderer';
import UploadFile from "../../library/Upload";
import Constant from '../../library/Constant';
import PropagateLoader from "react-spinners/PropagateLoader"
import { DatePicker } from '@material-ui/pickers';
import BalanceSheetOLPA from './BalanceSheetOLPA';
import moment from 'moment';
import CorporateAnnualTargetOLPA from './CorporateAnnualTargetOLPA';
import * as R from 'ramda'

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

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

export default class OutlookPA extends Component {
    constructor(props) {
        super(props)
        this.state = {
            perusahaan: 'TAP Group',
            listRevision: null,
            revision: null,
            visibleOutlookPA: true,
            listPeriode: null,
            periode: null,
            listCompany: null,
            company: null,
            report_id: null,
            visibleBS: false,
            visiblePL: false,
            visibleCF: false,
            visibleCAT: false,
            listAttachment: [],
            visibleUpload: false,
            revisionTable: null,
            alert: false,
            tipeAlert: '',
            messageAlert: '',
            outlook_pa_id: null,
            isSubmit: false,
            visibleTableHistory: false,
            isApprover: false,
            lastStatus: "",
            intent: "",
            approverID: null,
            pic: '',
            submitter: false,
            detailRevisiCheck: [],
            lastRevision: "",
            checkApprover: false,
            lastPeriod: '',
            latestPeriode: '',
            minDateRevision: new Date(),
            maxDateRevision: new Date(),
            btnApprove: false,
            listStatus: [],
            selectedStatus: [],
            prevRevision: false,
            dbPL: [],
            listApprover: null,
            approver: null,
            isAdmin: false
        }
        this.myRef = React.createRef()
        this.fileHandler = this.fileHandler.bind(this);
    }

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

    componentDidMount() {
        this.setState({ loading: true })
        this.props.selectIndex('Outlook Performance Appraisal')
        if (this.props.location.state !== undefined) {
            console.log(this.props);
            this.setState({ userType: this.props.location.state.userType, intent: 'Home', lastPeriodProps: this.props.location.state.rawData.periode, rawData: this.props.location.state.rawData }, () => {
                this.checkApprover()
            })
        } else {
            this.checkApprover()
        }
    }

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

        let listStatus2 = [
            { name: 'Open', value: 'not-yet' },
            { name: 'Submitted', value: 'approval_review' },
            { name: 'Approved', value: 'approved' },
        ]
        api.create().checkApproverOLPA().then(response => {
            // console.log(response);
            if (response.data.data.is_approver === true) {
                this.setState({ isApprover: true, checkApprover: true, listStatus: listStatus1, selectedStatus: listStatus1 }, () =>
                    this.getPeriode())
            } else {
                this.setState({ isApprover: false, checkApprover: false, listStatus: listStatus2, selectedStatus: listStatus2 }, () =>
                    this.getPeriode())
            }
        })
    }

    getCompanySubmitted() {
        let selectedStatus = this.state.selectedStatus.map((item) => {
            return item.value
        })
        let body = {
            "periode": this.state.periode.periode,
            "status": selectedStatus
        }
        api.create().getCompanySubmittedOLPA(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)
                        }

                        // if (companyData.length > 0) {
                        //     companyData = companyData.sort((a, b) => a.company_name.localeCompare(b.company_name))
                        // }

                        // let defaultProps = {
                        //     options: companyData,
                        //     getOptionLabel: (option) => titleCase(option.company_name),
                        // };
                        // let indexID = null
                        // if (this.state.rawData !== undefined) {
                        //     indexID = companyData.findIndex((val) => val.company_id == this.state.rawData.company_id)
                        // }
                        this.setState({ listCompany: defaultProps, company: indexID == null ? arrayBaru[0] : arrayBaru[indexID] }, () => {
                            console.log(response.data.data);
                            if (response.data.data.length > 0) {
                                this.getRevision()
                            } else {
                                this.setState({ listRevision: null, revision: null, dataTable: [], checkApprover: false, lastRevision: "", visibleTableHistory: false, loading: false })
                            }
                            // 
                        })
                    } else {
                        this.setState({ listRevision: null, revision: null, listCompany: null, company: null, dataTable: [], lastRevision: "", visibleTableHistory: 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 })
            }
        })
    }

    getReportAttachment() {
        let payload = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "revision": this.state.revision.revision,
        }
        api.create().getOLPAAtt(payload).then(response => {
            // console.log(response)
            if (response.data) {
                if (response.data.status === "success") {
                    this.setState({ listAttachment: response.data.data })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                    if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                        setTimeout(() => {
                            localStorage.removeItem(Constant.TOKEN)
                            window.location.reload();
                        }, 1000);
                    }
                })
            }
            // console.log(response);
        })
    }

    getReport() {
        let payload = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "report_type": "Outlook PA",
        }
        api.create().getReportOLPA(payload).then(response => {
            console.log(response);
            if (response.data) {
                if (response.data.status === "success") {
                    let dataTable = response.data.data.map((item, index) => {
                        return [
                            item.number,
                            item.report_name,
                            item.revision,
                            this.state.isSubmit === false ? "CLOSED" : item.current_status,
                            item.report_id,
                            // Number(item.revision) > 0 ? (item.current_status == "not-yet" ? false : item.is_can_upload) : 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
                        ]
                    })
                    // dataTable.push([
                    //     5, "Corporate Annual Target", 0, "not-yet", 39, false, 0
                    // ])
                    let dataTableRevision = []
                    response.data.data.map((item, index) => {
                        if (item.report_name !== 'Cash Flow') {
                            dataTableRevision.push([
                                item.report_id,
                                item.report_name === 'CAT' ? 'Corporate Annual Target' : item.report_name,
                                "",
                                item.number
                            ])
                        }
                    })
                    // console.log(dataTable);
                    this.setState({ dataTable, loading: false, dataTableRevision: dataTableRevision.sort((a, b) => a.number - b.number), dataForRevision: response.data.data })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ loading: false })
            }
        })
    }

    getLatestPeriodSubmit() {
        let body = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode
        }
        api.create().getSubmitOLPA(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()
                    })
                }
            }
        })
    }

    getDetailUser() {
        let userId = localStorage.getItem(Constant.USER)
        api.create().getDetailUser(userId).then((response) => {
            // console.log(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' })
            }
        })
    }

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

                    if (companyData.length > 0) {
                        companyData = companyData.sort((a, b) => a.company_name.localeCompare(b.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))
                    }

                    console.log(companyData)
                    console.log(arrayBaru)

                    let defaultProps = {
                        options: arrayBaru,
                        getOptionLabel: (option) => titleCase(option.company_name),
                    };
                    let index = arrayBaru.findIndex((val) => val.company_id == comID)
                    this.setState({ listCompany: defaultProps, company: arrayBaru.length < 1 ? companyData[0] : (index == -1 ? arrayBaru[0] : arrayBaru[index]) }, () => {
                        this.getLastPeriod()
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        if (response.data.message.includes("Someone Logged In") || 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 })
            }
        })
    }

    getLastPeriod() {
        api.create().getLastPeriodOLPA(this.state.company.company_id).then(response => {
            // console.log(response);
            let currentYear = new Date().getFullYear()
            if (response.data.status === "success") {
                this.setState({ lastPeriod: Number(response.data.data.last_periode) < Number(currentYear) ? String(currentYear) : response.data.data.last_periode, latestPeriode: response.data.data.latest_periode }, () => {
                    this.getPeriode()
                })
            }
        })
    }

    getPeriode() {
        api.create().getPeriodeTransaction().then(response => {
            // let dateNow = new Date
            // let year = this.state.rawData ? this.state.rawData.periode : format(dateNow, 'yyyy')
            let currentYear = new Date().getFullYear()
            // console.log(currentYear)
            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 == 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.lastPeriodProps == undefined ? (this.state.lastPeriod == "" ? String(Number(currentYear)) : Number(this.state.lastPeriod)) : this.state.lastPeriodProps)
                    let index = data.sort((a, b) => a - b).findIndex((val) => val == periode)
                    // console.log(data)
                    // console.log(this.state.lastPeriod)
                    // console.log(periode)
                    // console.log(index)
                    this.setState({ listPeriode: defaultProps, periode: index === -1 ? periodeData[0] : periodeData[index] }, () => {
                        // if (this.state.isApprover === true) {
                        //     this.getCompanySubmitted()
                        // } else {
                        //     this.getRevision()
                        // }
                        this.getDetailUser()
                    })
                }
            }
        })
    }

    getRevision() {
        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.getOutlookPAID()
                    })
                }
            }
        })
    }

    getOutlookPAID(type) {
        this.setState({ loading: true })
        let payload = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "is_approver": this.state.isAdmin && this.state.lastStatus == 'WAITING FOR APPROVAL' ? false : this.state.isApprover
        }
        api.create().getOutlookPAID(payload).then(response => {
            console.log(response)
            if (response) {
                if (response.data.status === "success") {
                    this.setState({
                        outlook_pa_id: response.data.data.outlook_pa_id,
                        submitter: response.data.data.submitter,
                        approverID: response.data.data.approve_id, pic: response.data.data.approver == null ? '' : response.data.data.approver,
                        lastStatus: response.data.data.last_status === null ? 'SUBMIT' : response.data.data.last_status,
                        lastRevision: response.data.data.last_revision,
                        btnApprove: response.data.data.is_submit
                    }, () => {
                        // console.log(this.state.lastStatus);
                        if (this.state.isAdmin) {
                            console.log('masuk')
                            api.create().getListApprover('outlook_pa', this.state.outlook_pa_id).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.historyApproval()
                        this.getLatestPeriodSubmit()
                        if (type != undefined && type == 'PL') {
                            // this.getCashFlow(type)
                            this.getPL(type)
                        } else if (type != undefined && type == 'BS') {
                            let bodyRatioOLPA = {
                                "report": 'ratio',
                                "outlookPaId": this.state.outlook_pa_id,
                                "companyId": this.state.company.company_id,
                                "periode": this.state.periode.periode
                            }
                            api.create().triggerRatioOLPA(bodyRatioOLPA).then((res) => {
                                console.log(res)
                                this.setState({ loading: false })
                            })
                        } else {
                            this.setState({ loading: false })
                        }
                        api.create().checkApproverOLPA().then(response => {
                            // console.log(response);
                            if (response.data.data.is_approver === true) {
                                this.setState({ isApprover: true, checkApprover: true })
                            } else {
                                this.setState({ isApprover: false, checkApprover: false })
                            }

                        })
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ outlook_pa_id: null, loading: false })
            }
        })
    }

    historyApproval() {
        let body = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode
        }
        api.create().historyApprovalOLPA(body).then(response => {
            // console.log(response);
            if (response.data.data.length > 0) {
                let dataTableHistory = response.data.data.map(item => {
                    return [
                        item.pic,
                        item.status_approval,
                        // String(item.status_approval).replace('APPROVAL_PROCCESS', 'WAITING FOR APPROVAL').replace('- -', ''),
                        item.remarks,
                        item.item_revision,
                        item.history_approval_date
                    ]
                })
                this.setState({ dataTableHistory, visibleTableHistory: true })
            }
        })
    }

    async setHeaderTokenSuperadmin(type) {
        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, realToken)
        })
    }

    approvalSubmission(type, realToken) {
        this.scrollToMyRef()
        // if (this.state.isAdmin && type == 'approve') {
        //     api.create().getIdToken(this.state.approver.userId).then((response) => {
        //         // console.log(realToken)
        //         // console.log(response.data.data.token)
        //         localStorage.setItem(Constant.TOKEN, response.data.data.token)
        //     })
        // }
        this.setState({ loading: true })
        let body = {
            "approval_id": this.props.location.state == undefined ? this.state.approverID : this.state.rawData.approval_id,
            "status": type,
            "detail": this.state.detailRevisiCheck,
            "is_superadmin": this.state.isAdmin
        }
        let payload = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "min_periode": moment(this.state.minDateRevision).format('YYYY-MM-DD'),
            "max_periode": moment(this.state.maxDateRevision).format('YYYY-MM-DD')
        }
        // console.log(payload)
        // api.create().approvalSubmissionOLPA(body).then((res) => {
        //     console.log(res)
        //     // this.setState({ loading: false }, () => {
        //         this.getOutlookPAID()
        //     // })
        //     if (type == 'revision') {
        //         api.create().createPeriodeRevisionOLPA(payload).then((res) => console.log(res))
        //     }
        // })
        setTimeout(() => {
            api.create().approvalSubmissionOLPA(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 })
                }
                setTimeout(() => {
                    if (type == 'revision') {
                        api.create().createPeriodeRevisionOLPA(payload).then((res))
                    }
                    this.getOutlookPAID()
                }, 300);
            })
        }, 100);
    }

    clickDetail(item, id, revision, status) {
        this.state.dataForRevision.map(i => {
            if (i.report_name === item) {
                if (i.revision == revision) {
                    this.setState({ prevRevision: true })
                } else {
                    this.setState({ prevRevision: false })
                }
            }
        })
        this.setState({
            report_id: id,
            revisionTable: revision,
            status: status
        }, () => {
            if (item === 'Balance Sheet') {
                this.setState({
                    visibleOutlookPA: false,
                    visibleBS: true,
                    visiblePL: false,
                    visibleTP: false,
                    visibleCF: false,
                    visibleCAT: false
                })
            } else if (item === 'Profit Loss') {
                this.setState({
                    visibleOutlookPA: false,
                    visibleBS: false,
                    visiblePL: true,
                    visibleTP: false,
                    visibleCF: false,
                    visibleCAT: false
                })
            } else if (item === 'Tax Planning') {
                this.setState({
                    visibleOutlookPA: false,
                    visibleBS: false,
                    visiblePL: false,
                    visibleTP: true,
                    visibleCF: false,
                    visibleCAT: false
                })
            } else if (item === 'Cash Flow') {
                this.setState({
                    visibleOutlookPA: false,
                    visibleBS: false,
                    visiblePL: false,
                    visibleTP: false,
                    visibleCF: true,
                    visibleCAT: false
                })
                // } else if (item === 'Corporate Annual Target') {
            } else if (item === 'CAT') {
                this.setState({
                    visibleOutlookPA: false,
                    visibleBS: false,
                    visiblePL: false,
                    visibleTP: false,
                    visibleCF: false,
                    visibleCAT: true
                })
            }
        })
    }

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

    handleChange(value, tableMeta) {
        let data = 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.revision.revision));
                formData.append("companyId", this.state.company.company_id);
                formData.append("periode", Number(this.state.periode.periode));
                formData.append("file", event);
                this.setState({ formData })
            }
        })
    }

    uploadAttachment(formData) {
        api.create().uploadAttOLPA(formData).then(response => {
            if (response.data) {
                if (response.data.status === "success") {
                    this.setState({ visibleUpload: false }, () => {
                        this.getOutlookPAID()
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            }
        })
    }

    deleteAttachment(item) {
        api.create().deleteAttOLPA(item.attachment_id).then(response => {
            if (response.data) {
                if (response.data.status === "success") {
                    this.getOutlookPAID()
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            }
        })
    }

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

    saveToOLPA(data, type) {
        this.setState({ loading: true })
        // console.log(JSON.stringify(data));
        api.create('UPLOAD').createReportOLPA(data).then(response => {
            console.log(response);
            if (response.data) {
                if (response.data.status === "success") {
                    this.getOutlookPAID(type)
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false, handleDoubleClick: 0 }, () => {
                        document.body.style.overflow = 'unset';
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                        this.getOutlookPAID()
                    })
                }
                // else {
                //     this.setState({ loading: false }, () => {
                //         // alert(response.data.message)
                //         this.getOutlookPAID()
                //     })
                // }
            } else {
                this.setState({ loading: false }, () => {
                    // alert(response.problem)
                    this.getOutlookPAID()
                })
            }
        })
    }

    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/outlook_pa/download_attachment?fileName=${fileurl}&&fileType=${fileType}`
        // console.log(url);
        let res = await fetch(
            `${process.env.REACT_APP_URL_MAIN_BE}/public/transaction/outlook_pa/download_attachment?fileName=${fileurl}&&fileType=${fileType}`
        )
        res = await res.blob()
        this.setState({ loading: false })
        if (res.size > 0) {
            let url = window.URL.createObjectURL(res);
            let a = document.createElement('a');
            a.href = url;
            a.download = 'Outlook Perfromance Appraisal.xlsx';
            a.click();
        }
    }

    validate() {
        this.setState({ loading: true })
        let array = []
        let canSubmit = true
        this.state.dataTable.map(item => {
            if (item[3] !== "submitted" && item[3] !== 'approved') {
                canSubmit = false
                array.push(item[3])
            }
            // 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 = {
                outlook_pa_id: this.state.outlook_pa_id
            }
            api.create().submitOLPA(body).then(response => {
                // console.log(response);
                if (response.data) {
                    if (response.data.status === "success") {
                        this.getOutlookPAID()
                    }
                }
            })
        } else {
            this.setState({ alert: true, messageAlert: 'Data Is Not Complete', tipeAlert: 'warning', loading: false })
        }
        // if (array.includes("not-yet" || "draft")) {
        //     // console.log('gagal');
        // } else {
        //     // console.log('masuk');
        // }

    }

    getPL(type) {
        let PLID = null
        let payloadID = {
            "periode": this.state.periode.periode,
            "company_id": this.state.company.company_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 = {
                    "report_id": 28,
                    "revision": Number(this.state.lastRevision),
                    "periode": this.state.periode.periode,
                    "company_id": this.state.company.company_id,
                    "outlook_pa_id": this.state.PLID,
                }
                api.create().getHierarkiDBPLOLPA(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.profit_detail_outlook.total_actual_before === null ? "0" : item.profit_detail_outlook.total_actual_before === "" ? "0" : item.profit_detail_outlook.total_actual_before,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.january, formula: item.profit_detail_outlook.january_formula } : item.profit_detail_outlook.january,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.february, formula: item.profit_detail_outlook.february_formula } : item.profit_detail_outlook.february,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.march, formula: item.profit_detail_outlook.march_formula } : item.profit_detail_outlook.march,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.april, formula: item.profit_detail_outlook.april_formula } : item.profit_detail_outlook.april,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.may, formula: item.profit_detail_outlook.may_formula } : item.profit_detail_outlook.may,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.june, formula: item.profit_detail_outlook.june_formula } : item.profit_detail_outlook.june,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.july, formula: item.profit_detail_outlook.july_formula } : item.profit_detail_outlook.july,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.august, formula: item.profit_detail_outlook.august_formula } : item.profit_detail_outlook.august,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.september, formula: item.profit_detail_outlook.september_formula } : item.profit_detail_outlook.september,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.october, formula: item.profit_detail_outlook.october_formula } : item.profit_detail_outlook.october,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.november, formula: item.profit_detail_outlook.november_formula } : item.profit_detail_outlook.november,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.december, formula: item.profit_detail_outlook.december_formula } : item.profit_detail_outlook.december,
                                item.profit_detail_outlook.total_current_year,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? 0 : item.profit_detail_outlook.total_next_year,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? 0 : item.profit_detail_outlook.total_more_year,
                                item.order,
                                item.condition_it_should_be,
                                item.condition_if_wrong,
                                item.profit_detail_outlook.forecast_formula == null ? [] : item.profit_detail_outlook.forecast_formula,
                                item.profit_detail_outlook.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,
                                item.profit_detail_outlook.total_actual_before === null ? "0" : item.profit_detail_outlook.total_actual_before === "" ? "0" : item.profit_detail_outlook.total_actual_before,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.january, formula: item.profit_detail_outlook.january_formula } : item.profit_detail_outlook.january,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.february, formula: item.profit_detail_outlook.february_formula } : item.profit_detail_outlook.february,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.march, formula: item.profit_detail_outlook.march_formula } : item.profit_detail_outlook.march,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.april, formula: item.profit_detail_outlook.april_formula } : item.profit_detail_outlook.april,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.may, formula: item.profit_detail_outlook.may_formula } : item.profit_detail_outlook.may,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.june, formula: item.profit_detail_outlook.june_formula } : item.profit_detail_outlook.june,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.july, formula: item.profit_detail_outlook.july_formula } : item.profit_detail_outlook.july,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.august, formula: item.profit_detail_outlook.august_formula } : item.profit_detail_outlook.august,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.september, formula: item.profit_detail_outlook.september_formula } : item.profit_detail_outlook.september,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.october, formula: item.profit_detail_outlook.october_formula } : item.profit_detail_outlook.october,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.november, formula: item.profit_detail_outlook.november_formula } : item.profit_detail_outlook.november,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? { value: item.profit_detail_outlook.december, formula: item.profit_detail_outlook.december_formula } : item.profit_detail_outlook.december,
                                item.profit_detail_outlook.total_current_year,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? 0 : item.profit_detail_outlook.total_next_year,
                                item.type_report_id == 5 || item.type_report_id == 6 || item.type_report_id == 7 ? 0 : item.profit_detail_outlook.total_more_year,
                                item.order,
                                item.condition_it_should_be,
                                item.condition_if_wrong,
                                item.profit_detail_outlook.forecast_formula == null ? [] : item.profit_detail_outlook.forecast_formula,
                                item.profit_detail_outlook.notes
                            ])
                            if (item.children !== null) {
                                if (item.children.length > 0) {
                                    item.children.map((items, indexs) => {
                                        handlePushChild(items)
                                    })
                                }
                            }
                        })
                        // console.log(dataTable)
                        this.setState({ dbPL: dataTable }, () => {
                            this.olahDataPL(this.state.dbPL, type)
                        })
                    } else {
                        this.setState({ dbPL: [], previewTable: false, previewDownload: false })
                    }


                })
            })
        })


    }

    handleValueFormulaDBPL = (indexDBCF, value, tableMeta, column, periode, forecast) => {
        let splitFormula = String(tableMeta[3]).split(/([()@])/)
        // let splitFormula = String(tableMeta.rowData[3]).split('@')
        let baru = []
        let anjay = []
        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 (forecast !== undefined) {
                        let forecastt = 0
                        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.state.periode.periode) - 1 : this.state.periode.periode
                            let indexID = tableMeta[data].formula.findIndex((val) => val.item_formula == String(`@${tst}`) && val.periode == period)

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

                } else {
                    let indexID = dataTable2.findIndex((val) => val[22] == item)
                    if (indexID !== -1) {
                        // if (forecast !== undefined) {
                        //     console.log(dataTable2[indexID])
                        //     console.log(column)
                        //     console.log(dataTable2[indexID][column])

                        // }
                        if (forecast != undefined) {
                            // console.log(dataTable2[indexID][column])
                        }
                        let 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)
                }
            }
        })

        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 (String(tableMeta[5]) == "Cost of Goods Sold (COGS)" && column == 20) {
            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
    }

    handleForecastDBPL = (index, tableMeta, periode, column) => {
        let total = 0
        let dataTable2 = this.state.dbPL

        if (tableMeta[3].includes('#PL')) {
            dataTable2[index][25].map((item, index) => {
                if (item.periode == periode) {
                    total += Number(item.value)
                }
            })
        } else {
            total = this.handleValueFormulaDBPL(dataTable2[index][column], tableMeta[column], tableMeta, column, periode, dataTable2[index][25])
        }

        return total
    }

    olahDataPL(dbPL, type) {
        dbPL.map((item, index) => {
            if (item[0] == 5 || item[0] == 6 || item[0] == 7) {
                item[7].value = this.handleValueFormulaDBPL(index, item[7], item, 7)
                item[8].value = this.handleValueFormulaDBPL(index, item[8], item, 8)
                item[9].value = this.handleValueFormulaDBPL(index, item[9], item, 9)
                item[10].value = this.handleValueFormulaDBPL(index, item[10], item, 10)
                item[11].value = this.handleValueFormulaDBPL(index, item[11], item, 11)
                item[12].value = this.handleValueFormulaDBPL(index, item[12], item, 12)
                item[13].value = this.handleValueFormulaDBPL(index, item[13], item, 13)
                item[14].value = this.handleValueFormulaDBPL(index, item[14], item, 14)
                item[15].value = this.handleValueFormulaDBPL(index, item[15], item, 15)
                item[16].value = this.handleValueFormulaDBPL(index, item[16], item, 16)
                item[17].value = this.handleValueFormulaDBPL(index, item[17], item, 17)
                item[18].value = this.handleValueFormulaDBPL(index, item[18], item, 18)
                item[20] = this.handleForecastDBPL(index, item, `${Number(this.state.periode.periode) + 1}`, 20)
                item[21] = this.handleForecastDBPL(index, item, `${Number(this.state.periode.periode) + 2}`, 21)
            }
        })
        this.setState({ dbPL }, () => {
            this.payloadPL(type)
        })
    }

    payloadPL(type) {
        let listPL = []
        // console.log(this.state.dbPL)
        this.state.dbPL.map((item, index) => {
            if (item[0] == 5 || item[0] == 6 || item[0] == 7) {
                // if (item[7].value == "" || item[7].value == 0 || item[7].value == "0.0") {
                item[7].value = this.handleValueFormulaDBPL(index, item[7], item, 7)
                // }  

                // if (item[8].value == "" || item[8].value == 0 || item[8].value == "0.0") {
                item[8].value = this.handleValueFormulaDBPL(index, item[8], item, 8)
                // } 

                // if (item[9].value == "" || item[9].value == 0 || item[9].value == "0.0") {
                item[9].value = this.handleValueFormulaDBPL(index, item[9], item, 9)
                // } 

                // if (item[10].value == "" || item[10].value == 0 || item[10].value == "0.0") {
                item[10].value = this.handleValueFormulaDBPL(index, item[10], item, 10)
                // } 

                // if (item[11].value == "" || item[11].value == 0 || item[11].value == "0.0") {
                item[11].value = this.handleValueFormulaDBPL(index, item[11], item, 11)
                // } 

                // if (item[12].value == "" || item[12].value == 0 || item[12].value == "0.0") {
                item[12].value = this.handleValueFormulaDBPL(index, item[12], item, 12)
                // } 

                // if (item[13].value == "" || item[13].value == 0 || item[13].value == "0.0") {
                item[13].value = this.handleValueFormulaDBPL(index, item[13], item, 13)
                // }

                // if (item[14].value == "" || item[14].value == 0 || item[14].value == "0.0") {
                item[14].value = this.handleValueFormulaDBPL(index, item[14], item, 14)
                // } 

                // if (item[15].value == "" || item[15].value == 0 || item[15].value == "0.0") {
                item[15].value = this.handleValueFormulaDBPL(index, item[15], item, 15)
                // } 

                // if (item[16].value == "" || item[16].value == 0 || item[16].value == "0.0") {
                item[16].value = this.handleValueFormulaDBPL(index, item[16], item, 16)
                // } 

                // if (item[17].value == "" || item[17].value == 0 || item[17].value == "0.0") {
                item[17].value = this.handleValueFormulaDBPL(index, item[17], item, 17)
                // } 

                // if (item[18].value == "" || item[18].value == 0 || item[18].value == "0.0") {
                item[18].value = this.handleValueFormulaDBPL(index, item[18], item, 18)
                // } 

                // if (item[20] == "" || item[20] == 0 || item[20] == "0.0") {
                item[20] = this.handleForecastDBPL(index, item, `${Number(this.state.periode.periode) + 1}`, 20)
                // } 

                // if (item[21] == "" || item[21] == 0 || item[21] == "0.0") {
                item[21] = this.handleForecastDBPL(index, item, `${Number(this.state.periode.periode) + 2}`, 21)
                // } 
            }


            listPL.push(
                {
                    "item_report_id": item[1],
                    "january": String(item[7].value == undefined ? item[7] : Number(item[7].value).toFixed(1)),
                    "february": String(item[8].value == undefined ? item[8] : Number(item[8].value).toFixed(1)),
                    "march": String(item[9].value == undefined ? item[9] : Number(item[9].value).toFixed(1)),
                    "april": String(item[10].value == undefined ? item[10] : Number(item[10].value).toFixed(1)),
                    "may": String(item[11].value == undefined ? item[11] : Number(item[11].value).toFixed(1)),
                    "june": String(item[12].value == undefined ? item[12] : Number(item[12].value).toFixed(1)),
                    "july": String(item[13].value == undefined ? item[13] : Number(item[13].value).toFixed(1)),
                    "august": String(item[14].value == undefined ? item[14] : Number(item[14].value).toFixed(1)),
                    "september": String(item[15].value == undefined ? item[15] : Number(item[15].value).toFixed(1)),
                    "october": String(item[16].value == undefined ? item[16] : Number(item[16].value).toFixed(1)),
                    "november": String(item[17].value == undefined ? item[17] : Number(item[17].value).toFixed(1)),
                    "december": String(item[18].value == undefined ? item[18] : Number(item[18].value).toFixed(1)),
                    "total_current_year": String(item[19]),
                    "total_next_year": String(item[20] != '' ? Number(item[20]).toFixed(1) : item[20]),
                    "total_more_year": String(item[21] != '' ? Number(item[21]).toFixed(1) : item[21]),
                    "notes": String(item[26]),
                }
            )

        })

        // console.log(listPL)
        this.setState({ dbPL: listPL }, () => {
            // if (this.state.submissionID != null) {
            //     this.createDBPL()
            // }
            if (type != undefined) {
                if (type == 'PL') {
                    console.log('tarik sis')
                    this.createDBPL()
                }
            }
        })
    }

    createDBPL() {
        let payload = {
            // "submission_id": this.state.submissionID,
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "report_id": 28,
            "status": "submitted",
            "profit_loss_id": this.state.PLID,
            "profit_loss_olpa": this.state.dbPL,
        }
        console.log(this.state.dbPL)
        // console.log(JSON.stringify(payload))
        api.create().createDBPLOLPA(payload).then((res) => {
            console.log(res)
            this.setState({ loading: false })
        })
    }

    handleApproveAdmin() {
        this.setState({ visibleApproveSuperadmin: true })
    }

    render() {
        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 columns = ["#", "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)
                                            }}
                                            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 === "revision" ?
                                            <span>REVISION</span> :
                                            val === "approval_proccess" ?
                                                <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) => {
                        // console.log(tableMeta)
                        return (
                            <div style={{ display: 'flex' }}>
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: (this.state.periode.periode == '2020' && tableMeta.rowData[1] == 'Balance Sheet' && tableMeta.rowData[3] == 'CLOSED') ? 'pointer' : (this.state.isSubmit === false ? 'default' : tableMeta.rowData[5] ? 'pointer' : 'default'),
                                        // cursor: tableMeta.rowData[5] ? 'pointer' : 'default',
                                        borderColor: 'transparent'
                                    }}
                                    onClick={() =>
                                        tableMeta.rowData[5] == true || (this.state.periode.periode == '2020' && tableMeta.rowData[1] == 'Balance Sheet' && tableMeta.rowData[3] == 'CLOSED') ?
                                            this.clickDetail(tableMeta.rowData[1], tableMeta.rowData[4], tableMeta.rowData[2], tableMeta.rowData[3])
                                            : null
                                    }
                                >
                                    {/* {this.state.isApprover == true ? 
                                        (tableMeta.rowData[5] ? '#5198ea' : 'GrayText') :
                                        (this.state.lastRevision == 0 ? (tableMeta.rowData[5] ? '#5198ea' : 'GrayText') :
                                        (tableMeta.rowData[3] !== 'submitted' ? '#5198ea' : 'GrayText'))} */}
                                    <Typography style={{ color: (this.state.periode.periode == '2020' && tableMeta.rowData[1] == 'Balance Sheet' && tableMeta.rowData[3] == 'CLOSED') ? '#5198ea' : tableMeta.rowData[5] ? '#5198ea' : 'GrayText', fontSize: 12, }}>Detail</Typography>
                                </button>
                            </div >
                        );
                    }
                }
            }, {
                name: "",
                options: { display: false }
            }, {
                name: "",
                options: { display: false }
            }]

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

        const columnRevisi = [
            {
                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)} />
                                    }
                                />
                            </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)
                                                // console.log(dataTable2)
                                            }}
                                        />}
                                />
                            </div>
                        )
                    }
                }
            }, {
                name: "",
                options: { display: false }
            }
        ]

        const handleChangeText = (value, tableMeta) => {
            let dataTableRevision = this.state.dataTableRevision
            dataTableRevision[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({ dataTableRevision, detailRevisiCheck })
        }

        // const handleCheckRevision = (value) => {
        //     let detailRevisiCheck = this.state.detailRevisiCheck
        //     let payload = {
        //         report_id: value[0],
        //         remarks: value[2]
        //     }

        //     let indexId = detailRevisiCheck.findIndex((val) => val.report_id == value[0])
        //     if (indexId == -1) {
        //         detailRevisiCheck.push(payload)
        //     } else {
        //         detailRevisiCheck.splice(indexId, 1)
        //     }
        //     this.setState({ detailRevisiCheck })
        //     // console.log(detailRevisiCheck)
        // }

        const handleCheckRevision = (value) => {
            let detailRevisiCheck = this.state.detailRevisiCheck
            let payload = {
                report_id: value[0],
                remarks: value[2],
                number: value[3]
            }
            let indexDataRevisi = this.state.dataTableRevision.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) {
                this.state.dataTableRevision.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) {
                    this.state.dataTableRevision.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 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 loadingComponent = (
            <div style={{ position: 'absolute', zIndex: 110, top: 0, left: 0, width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', background: 'rgba(255,255,255,0.8)' }}>
                <PropagateLoader
                    // css={override}
                    size={20}
                    color={"#274B80"}
                    loading={this.state.loading}
                />
            </div>
        );
        return (
            <div style={{ flex: 1, backgroundColor: '#f8f8f8' }} ref={this.myRef}>
                <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.visibleOutlookPA && (
                    <div>
                        <div className={"main-color"} style={{ height: 78, display: 'flex', alignItems: 'center', paddingLeft: 20 }}>
                            <Typography style={{ fontSize: '16px', color: 'white' }}>Outlook Performance Appraisal 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 }}>Outlook Performance Appraisal</Typography>
                                </div>
                                <div style={{ padding: 20 }}>
                                    <div>
                                        <Autocomplete
                                            {...this.state.listPeriode}
                                            id="periode"
                                            onChange={(event, newInputValue) => this.setState({ periode: newInputValue }, () => {
                                                this.setState({ visibleTableHistory: false })
                                                if (this.state.listCompany == null) {
                                                    console.log('yak')
                                                    this.getCompanySubmitted()
                                                } else {
                                                    console.log('zz')
                                                    this.getRevision()
                                                }
                                            })}
                                            disabled={this.state.intent === 'Home' ? true : false}
                                            disableClearable
                                            style={{ width: 250 }}
                                            renderInput={(params) =>
                                                <TextField {...params} label="Period" margin="normal" style={{ marginTop: 7 }}
                                                />}
                                            value={this.state.periode}
                                        />
                                    </div>
                                    <div style={{ marginTop: 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 }} />}
                                        />
                                    </div>
                                    <div style={{ marginTop: 20 }}>
                                        <Autocomplete
                                            {...this.state.listCompany}
                                            id="company"
                                            disabled={this.state.intent === 'Home' ? true : false}
                                            onChange={(event, newInputValue) => this.setState({ company: newInputValue }, () => {
                                                this.setState({ visibleTableHistory: false })
                                                this.getRevision()
                                            })}
                                            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()
                                            })}
                                            disabled={true}
                                            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 style={{ marginTop: 20 }}>
                                        <MuiThemeProvider theme={getMuiTheme()}>
                                            <MUIDataTable
                                                data={this.state.dataTable}
                                                columns={columns}
                                                options={options}
                                            />
                                        </MuiThemeProvider>
                                    </div>
                                    <div style={{ display: 'flex', marginTop: 20 }}>
                                        <div style={{ width: '50%' }}>
                                            <Typography style={{ fontSize: '16px', color: '#4b4b4b', fontWeight: 'bold' }}>Attachment: </Typography>
                                        </div>
                                        {!this.state.isApprover && (this.state.lastStatus === 'SUBMIT' || this.state.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 })}
                                                >
                                                    <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 }}>
                                            {this.state.listAttachment.length > 0 ?
                                                this.state.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.isApprover && (this.state.lastStatus === 'SUBMIT' || this.state.lastStatus === 'REVISION') && (
                                            <div style={{ width: '50%' }}>
                                                {
                                                    this.state.listAttachment.length > 0 ?
                                                        this.state.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>
                                    {this.state.checkApprover === true ?
                                        this.state.lastStatus === 'WAITING FOR REVIEW' ?
                                            <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                                                <span>{this.state.lastStatus}</span>
                                            </div> : this.state.lastStatus === 'WAITING FOR YOUR APPROVAL' ?
                                                <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                                                    <span>{this.state.lastStatus}</span>
                                                </div> : this.state.lastStatus === 'WAITING FOR APPROVAL' ?
                                                    <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                                                        <span>{`${this.state.lastStatus} - ${this.state.pic}`}</span>
                                                    </div> : this.state.lastStatus === 'APPROVED' ?
                                                        <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                                                            <span>{`${this.state.lastStatus}`}</span>
                                                        </div> : null
                                        :
                                        this.state.lastStatus === 'SUBMITTED' ?
                                            <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                                                <span>{this.state.lastStatus}</span>
                                            </div> :
                                            this.state.lastStatus === 'WAITING FOR APPROVAL' ?
                                                <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                                                    <span>{`${this.state.lastStatus} - ${this.state.pic}`}</span>
                                                </div> :
                                                this.state.lastStatus === 'REVISION' ?
                                                    <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                                                        <span>NEED REVISION</span>
                                                    </div> :
                                                    this.state.lastStatus === 'APPROVED' ?
                                                        <div style={{ width: '100%', padding: '10px 20px', backgroundColor: 'yellow', textAlign: 'center', marginTop: 20 }}>
                                                            <span>APPROVED</span>
                                                        </div> : null
                                    }
                                    {this.state.visibleTableHistory && (
                                        <div style={{ marginTop: 20 }}>
                                            <MuiThemeProvider theme={getMuiTheme()}>
                                                <MUIDataTable
                                                    data={this.state.dataTableHistory}
                                                    columns={columnsHistory}
                                                    options={options}
                                                />
                                            </MuiThemeProvider>
                                        </div>
                                    )}
                                </div>
                                {this.state.isAdmin && this.state.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 })}
                                            >
                                                <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 && (this.state.lastStatus == 'WAITING FOR YOUR APPROVAL' || this.state.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()}
                                                >
                                                    <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 === true ?
                                            this.state.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')
                                                        }
                                                    >
                                                        <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> : (this.state.lastStatus === 'WAITING FOR YOUR APPROVAL' && this.state.btnApprove) ?
                                                    <div className="grid grid-2x" style={{ borderTop: 'solid 1px #c4c4c4', padding: 10, backgroundColor: '#f5f5f5', width: '100%', }}>
                                                        <div className="col-1">
                                                            <button
                                                                style={{
                                                                    backgroundColor: 'transparent',
                                                                    cursor: 'pointer',
                                                                    borderColor: 'transparent',
                                                                    outline: 'none',
                                                                }}
                                                                onClick={() => this.setState({ visibleRevision: true })}
                                                            >
                                                                <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>
                                                        </div>
                                                        <div className="col-2" style={{ display: 'flex', justifyContent: 'flex-end', maxWidth: '100%' }}>
                                                            <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> : null
                                            :
                                            (this.state.lastStatus === 'SUBMIT' || this.state.lastStatus === 'REVISION') && this.state.isSubmit === true ?
                                                <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()}
                                                    >
                                                        <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> :
                                                this.state.lastStatus === 'SUBMITTED' && this.state.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')}
                                                        >
                                                            <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
                                }
                            </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 })}
                                    >
                                        <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 && (
                    <BalanceSheetOLPA
                        open={this.props.open}
                        report_id={this.state.report_id}
                        height={this.props.height}
                        width={this.props.width}
                        company={this.state.company}
                        revision={this.state.revisionTable}
                        periode={this.state.periode.periode}
                        outlook_pa_id={this.state.outlook_pa_id}
                        saveToOLPA={this.saveToOLPA.bind(this)}
                        onClickClose={() => this.setState({ visibleBS: false, visibleOutlookPA: true })}
                        getReport={this.getOutlookPAID.bind(this)}
                        isApprover={this.state.isApprover}
                        lastStatus={this.state.lastStatus}
                        prevRevision={this.state.isSubmit ? this.state.prevRevision : true}
                        status={this.state.status}
                    />
                )}
                {this.state.visiblePL && (
                    <ProfitLossOLPA
                        open={this.props.open}
                        report_id={this.state.report_id}
                        height={this.props.height}
                        width={this.props.width}
                        company={this.state.company}
                        revision={this.state.revisionTable}
                        periode={this.state.periode.periode}
                        outlook_pa_id={this.state.outlook_pa_id}
                        saveToOLPA={this.saveToOLPA.bind(this)}
                        onClickClose={() => this.setState({ visiblePL: false, visibleOutlookPA: true })}
                        getReport={this.getOutlookPAID.bind(this)}
                        status={this.state.status}
                        isApprover={this.state.isApprover}
                        lastStatus={this.state.lastStatus}
                        prevRevision={this.state.isSubmit ? this.state.prevRevision : true}
                    />

                )}
                {this.state.visibleTP && (
                    <TaxPlanning
                        open={this.props.open}
                        report_id={this.state.report_id}
                        height={this.props.height}
                        width={this.props.width}
                        company={this.state.company}
                        revision={this.state.revisionTable}
                        periode={this.state.periode.periode}
                        outlook_pa_id={this.state.outlook_pa_id}
                        saveToOLPA={this.saveToOLPA.bind(this)}
                        onClickClose={() => this.setState({ visibleTP: false, visibleOutlookPA: true })}
                        getReport={this.getOutlookPAID.bind(this)}
                        status={this.state.status}
                        isApprover={this.state.isApprover}
                        lastStatus={this.state.lastStatus}
                        prevRevision={this.state.isSubmit ? this.state.prevRevision : true}
                    />
                )}
                {this.state.visibleCF && (
                    <CashFlow
                        open={this.props.open}
                        report_id={this.state.report_id}
                        height={this.props.height}
                        width={this.props.width}
                        company={this.state.company}
                        revision={this.state.revisionTable}
                        periode={this.state.periode.periode}
                        outlook_pa_id={this.state.outlook_pa_id}
                        saveToOLPA={this.saveToOLPA.bind(this)}
                        onClickClose={() => this.setState({ visibleCF: false, visibleOutlookPA: true })}
                        getReport={this.getOutlookPAID.bind(this)}
                        status={this.state.status}
                        isApprover={this.state.isApprover}
                        lastStatus={this.state.lastStatus}
                        prevRevision={this.state.isSubmit ? this.state.prevRevision : true}
                        PLBSFAMSubmitted={this.state.lastStatus == 'APPROVED' ? true : false}
                    />
                )}
                {this.state.visibleCAT && (
                    <CorporateAnnualTargetOLPA
                        open={this.props.open}
                        report_id={this.state.report_id}
                        height={this.props.height}
                        width={this.props.width}
                        company={this.state.company}
                        revision={this.state.revisionTable}
                        periode={this.state.periode.periode}
                        outlook_pa_id={this.state.outlook_pa_id}
                        saveToOLPA={this.saveToOLPA.bind(this)}
                        onClickClose={() => this.setState({ visibleCAT: false, visibleOutlookPA: true })}
                        getReport={this.getOutlookPAID.bind(this)}
                        isApprover={this.state.isApprover}
                        lastStatus={this.state.lastStatus}
                        prevRevision={this.state.isSubmit ? this.state.prevRevision : true}
                        status={this.state.status}
                    />
                )}

                {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 })}
                                    >
                                        <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.dataTableRevision}
                                            columns={columnRevisi}
                                            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) => null}
                                                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) => null}
                                                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 })}
                                    >
                                        <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()}
                                    >
                                        <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 })}
                                    >
                                        <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 })}
                                    >
                                        <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')}
                                    >
                                        <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>
                )}
            </div >
        );
    }
}