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 './OutlookPA/ProfitLossOLPA';
import TaxPlanning from './OutlookPA/TaxPlanningOLPA';
import { ExcelRenderer } from 'react-excel-renderer';
import UploadFile from "../library/Upload";
import { format } from 'date-fns';
import Constant from '../library/Constant';
import PropagateLoader from "react-spinners/PropagateLoader"
import { DatePicker } from '@material-ui/pickers';
import BalanceSheetOLPA from './OutlookPA/BalanceSheetOLPA';
import moment from 'moment';

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,
            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
        }
        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', lastPeriod: this.props.location.state.rawData.periode, rawData: this.props.location.state.rawData }, () => {
                this.checkApprover()
            })
        } else {
            this.checkApprover()
        }
    }

    checkApprover() {
        api.create().checkApproverOLPA().then(response => {
            // console.log(response);
            if (response.data.data.is_approver === true) {
                this.setState({ isApprover: true, checkApprover: true }, () =>
                    this.getPeriode())
            } else {
                this.setState({ isApprover: false, checkApprover: false }, () =>
                    this.getDetailUser())
            }
        })
    }

    getCompanySubmitted() {
        let body = {
            "periode": this.state.periode.periode
        }
        api.create().getCompanySubmittedOLPA(body).then(response => {
            // console.log(response);
            if (response.data) {
                if (response.data.status === 'success') {
                    let data = response.data.data
                    let companyData = data.map((item) => {
                        return {
                            company_id: item.company_id,
                            company_name: item.company_name,
                        }
                    })

                    let defaultProps = {
                        options: companyData,
                        getOptionLabel: (option) => titleCase(option.company_name),
                    };
                    this.setState({ listCompany: defaultProps, company: companyData[0] }, () => {
                        // // 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({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        if (response.data.message.includes("Someone Logged In")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', listCompany: null, company: null })
            }
        })
    }

    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 })
                }
            }
            // // 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.revision
                        ]
                    })
                    let dataTableRevision = response.data.data.map((item, index) => {
                        return [
                            item.report_id,
                            item.report_name,
                            ""
                        ]
                    })
                    // // console.log(dataTable);
                    this.setState({ dataTable, loading: false, dataTableRevision, dataForRevision: response.data.data })
                }
            } 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) => {
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === 'success') {
                        this.setState({ userCompany: response.data.data.company }, () => {
                            this.getCompanyActive()
                        })
                    }
                }
            }
        })
    }

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

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

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

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

    getPeriode() {
        api.create().getPeriodeTransaction().then(response => {
            // let 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) + 1)) {
                                data.push(item)
                            }
                        } else {
                            if ((item >= 2000) && (item == this.state.lastPeriod || item < this.state.lastPeriod)) {
                                data.push(item)
                            }
                        }
                    })
                    let periodeData = data.map((item) => {
                        return {
                            periode: item,
                        }
                    })
                    let defaultProps = {
                        options: periodeData,
                        getOptionLabel: (option) => option.periode,
                    };
                    let periode = (this.state.lastPeriod == "" ? String(Number(currentYear) + 1) : this.state.lastPeriod)
                    let index = data.sort((a, b) => a - b).findIndex((val) => val === periode)
                    // // console.log(data)
                    // console.log(this.state.lastPeriod)
                    // // console.log(periodeData)
                    // // console.log(index)
                    this.setState({ listPeriode: defaultProps, periode: index === -1 ? periodeData[0] : periodeData[index] }, () => {
                        if (this.state.isApprover === true) {
                            this.getCompanySubmitted()
                        } else {
                            this.getRevision()
                        }
                    })
                }
            }
        })
    }

    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() {
        this.setState({ loading: true })
        let payload = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "is_approver": 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);
                        this.historyApproval()
                        this.getLatestPeriodSubmit()
                        api.create().checkApprover().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({ 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 })
            }
        })
    }

    approvalSubmission(type) {
        this.scrollToMyRef()
        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
        }
        let payload = {
            "company_id": this.state.company.company_id,
            "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().approvalSubmission(body).then((res) => {
            // console.log(res)
            this.setState({ loading: false }, () => {
                this.getSubmission()
            })
            if (type == 'revision') {
                api.create().createPeriodeRevision(payload).then((res) => console.log(res))
            }
        })
    }

    clickDetail(item, id, revision, status) {
        // console.log(this.state.dataForRevision);
        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,
                })
            } else
                if (item === 'Profit Loss') {
                    this.setState({
                        visibleOutlookPA: false,
                        visibleBS: false,
                        visiblePL: true,
                        visibleTP: false,
                    })
                }
                else if (item === 'Tax Planning') {
                    this.setState({
                        visibleOutlookPA: false,
                        visibleBS: false,
                        visiblePL: false,
                        visibleTP: 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()
                    })
                }
            }
        })
    }

    deleteAttachment(item) {
        api.create().deleteAttOLPA(item.attachment_id).then(response => {
            if (response.data) {
                if (response.data.status === "success") {
                    this.getOutlookPAID()
                }
            }
        })
    }

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

    saveToOLPA(data) {
        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()
                } 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 = `https://tia.eksad.com/tia-reporting-dev/public/transaction/outlook_pa/download_attachment?fileName=${fileurl}&&fileType=${fileType}`
        // // console.log(url);
        let res = await fetch(
            `https://tia.eksad.com/tia-reporting-dev/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[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');
        // }

    }

    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) => {
                        return (
                            <div style={{ display: 'flex' }}>
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: this.state.isSubmit === false ? 'default' : tableMeta.rowData[5] ? 'pointer' : 'default',
                                        // cursor: tableMeta.rowData[5] ? 'pointer' : 'default',
                                        borderColor: 'transparent'
                                    }}
                                    onClick={() =>
                                        tableMeta.rowData[5] == true ?
                                            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: 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>
                        )
                    }
                }
            }
        ]

        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 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 }, () => {
                                                if (this.state.isApprover === true) {
                                                    this.getCompanySubmitted()
                                                } else {
                                                    this.setState({ visibleTableHistory: false })
                                                    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
                                            {...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.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.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>
                )}
            </div >
        );
    }
}
