import React, { Component } from 'react';
import { Typography, Paper, TextField, Snackbar, withStyles} from '@material-ui/core';
import Images from '../../assets/Images';
import Constant from '../../library/Constant';
import api from '../../api';
import { PropagateLoader } from 'react-spinners';
import { format } from 'date-fns';
import Autocomplete from '@material-ui/lab/Autocomplete';
import TableProgressReport from './TableProgressReport'
import ReactTooltip from "react-tooltip";
import MuiAlert from '@material-ui/lab/Alert';

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

class ReportProgress extends Component {
    constructor(props) {
        super(props)
        this.state = {
            listApproval: null,
            listCategory: {
                options: [{ name: 'Report Status', value: 'report-status' }, { name: 'Approval Progress', value: 'approval-progress' }],
                getOptionLabel: (option) => option.name,
            },
            listReportType: null,
            listQuarter: {
                options: [{ name: 'Q1', value: 'q1' }, { name: 'Q2', value: 'q2' }, { name: 'Q3', value: 'q3' }],
                getOptionLabel: (option) => option.name,
            },
            listMonth: null,
            listPeriodeMB: null,
            quarter: {
                name: 'Q1', value: 'q1'
            },
            category: {
                name: 'Report Status', value: 'report-status'
            },
            month: null,
            periodeMB: null,
            reportType: null,
            dataTable: [],
            alert: false,
            tipeAlert: '',
            messageAlert: '',
            company: null
        }
    }

    componentDidMount() {
        this.getMonth()
        // console.log(this.state.listCategory);
        // console.log(this.state.category);
    }

    getMonth() {
        this.setState({ loading: true })
        api.create().getMonthTransaction().then(response => {
            let dateNow = new Date()
            dateNow.setMonth(dateNow.getMonth() - 1);
            let month = format(dateNow, 'MMMM')
            if (response.data) {
                if (response.data.status === "success") {
                    let data = response.data.data
                    let monthData = data.map((item) => {
                        return {
                            month_id: item.id,
                            month_value: String(item.month_name).substr(0, 3)
                        }
                    })
                    let defaultProps = {
                        options: monthData,
                        getOptionLabel: (option) => option.month_value,
                    };
                    let index = data.findIndex((val) => val.month_name == month)
                    this.setState({ listMonth: defaultProps, month: index == -1 ? monthData[0] : monthData[index] }, () => {
                        this.getPeriode()
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
            }
        })
    }

    getPeriode() {
        let currentYear = new Date().getFullYear()
        let MB = []
        for (var i = 2000; i <= currentYear; i++) {
            MB.push({ name: String(i), value: i })
            if (i == currentYear) {
                MB.push({ name: String(i + 1), value: i + 1})
            }
        }
        console.log(MB);

        let defaultPropsMB = {
            options: MB,
            getOptionLabel: (option) => option.name,
        };

        this.setState({
            listPeriodeMB: defaultPropsMB,
            // periodeMB: MB[MB.length - 1],
            periodeMB: MB[MB.length - 2],
        }, () => {
            this.getReportType()
            // console.log(this.state.listMonth)
            // console.log(this.state.listPeriodeMB)
        })
    }

    getReportType() {
        let arrayReportType = [
            {
                name: 'Master Budget',
                value: 0
            }, {
                name: 'Monthly Report',
                value: 1
            }, {
                name: 'Rolling Outlook',
                value: 2
            }, {
                name: 'Outlook PA',
                value: 3
            },
        ]

        let defaultProps = {
            options: arrayReportType,
            getOptionLabel: (option) => option.name,
        };
        this.setState({ listReportType: defaultProps, reportType: arrayReportType[0] }, () => {
            // console.log(this.state.periodeMB)
            this.getDataMonitoring()
            // console.log(this.state.listReportType)
            // console.log(this.state.reportType)
        })
    }

    getDataMonitoring() {
        let payload = {
            "year": this.state.periodeMB.name,
            "month": this.state.month.month_id,
            "quarter": this.state.quarter.value

        }
        console.log(payload)
        if (String(this.state.reportType.name).toLocaleUpperCase().includes('MASTER')) {
            this.getMonitoringMB(payload)
        } else if (String(this.state.reportType.name).toLocaleUpperCase().includes('MONTHLY')) {
            this.getMonitoringMR(payload)
        } else if (String(this.state.reportType.name).toLocaleUpperCase().includes('ROLLING')) {
            this.getMonitoringRO(payload)
        } else {
            this.getMonitoringOLPA(payload)
        }
    }

    getMonitoringMB(payload) {
        let dataTable = []
        api.create().getMonitoringMB(payload).then((response) => {
            console.log(response)
            if (response.data) {
                if (response.data.status === "success") {
                    let data = response.data.data
                    data.map((item,index) => {
                        let report = []
                        let statusSubmission = String(item.submission_status).toLocaleUpperCase()
                        let statusOI = String(item.operating_indicator).toLocaleUpperCase()
                        item.report.map((items,index) => {
                            let statusReport = String(items.status_report).toLocaleUpperCase()
                            report.push({report_name: items.report_name, status_report: (statusReport == 'APPROVED' || statusReport == 'REVISION' || statusReport == 'COMPLETED') ? (statusReport + ' - ' + items.report_date) : statusReport })
                        })
                        report.push(
                            {report_name: 'Operating Indicator', status_report: statusOI}, 
                            {report_name: 'Submission Status', status_report: (statusSubmission == 'APPROVED' || statusSubmission == 'REVISION' || statusSubmission == 'COMPLETED') ? (statusSubmission + ' - ' + item.submissionStatusDate) : statusSubmission})
                        dataTable.push([
                            item.company_name,
                            report,
                            item.automatic_reminder_report_date,
                            item.manual_reminder_report_status,
                            item.manual_reminder_report_date,
                            item.submission_status,
                            item.manual_reminder_report_button,
                            item.company_id,
                        ])
                    })
                    // data.map((item,index) => {
                    //     let report = []
                    //     item.report.map((items,indexs) => {
                    //         if (!String(items.report_name).includes('Indicator') && !String(items.report_name).includes('OLPA')) {
                    //             if (String(items.report_name).includes('Fixed')) {
                    //                 report.push({...items, status_report: (items.report_date == null? items.status_report : items.status_report + ' - ' + items.report_date), report_name: 'Fixed Assets Movement'})
                    //             } else {
                    //                 report.push({...items, status_report: (items.report_date == null? items.status_report : items.status_report + ' - ' + items.report_date)})
                    //             }
                    //         }
                    //     })
                    //     report.push({report_name: 'Operating Indicator', status_report: item.operatingIndicator}, {report_name: 'Submission Status', status_report: (item.submissionStatusDate == null? item.submissionStatus : item.submissionStatus + ' - ' + item.submissionStatusDate)})
                    //     dataTable.push([
                    //         item.companyName,
                    //         report
                    //     ])
                    // })
                    // console.log(dataTable)
                    this.setState({dataTable, loading: 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({ alert: true, messageAlert: response.data.message, tipeAlert: 'error', loading: false })
            }
        })    
    }

    getMonitoringMR(payload) {
        let dataTable = []
        api.create().getMonitoringMR(payload).then((response) => {
            console.log(response)
            if (response.data) {
                if (response.data.status === "success") {
                    let data = response.data.data
                    data.map((item,index) => {
                        let report = item.report
                        report.push({report_name: 'Operating Indicator', status_report: item.operating_indicator}, {report_name: 'Monthly Status', status_report: item.monthly_status})
                        dataTable.push([
                            item.company_name,
                            report,
                            item.automatic_reminder_report_date,
                            item.manual_reminder_report_status,
                            item.manual_reminder_report_date,
                            item.monthly_status,
                            item.manual_reminder_report_button,
                            item.company_id,
                        ])
                    })
                    this.setState({dataTable, loading: 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({ alert: true, messageAlert: response.data.message, tipeAlert: 'error', loading: false })
            }
        })    
    }

    getMonitoringRO(payload) {
        let dataTable = []
        api.create().getMonitoringRO(payload).then((response) => {
            console.log(response)
            if (response.data) {
                if (response.data.status === "success") {
                    let data = response.data.data
                    data.map((item,index) => {
                        let report = item.report
                        report.push({report_name: 'Operating Indicator', status_report: item.operating_indicator}, {report_name: 'Rolling Status', status_report: item.rolling_status})
                        dataTable.push([
                            item.company_name,
                            report,
                            item.automatic_reminder_report_date,
                            item.manual_reminder_report_status,
                            item.manual_reminder_report_date,
                            item.rolling_status,
                            item.manual_reminder_report_button,
                            item.company_id,
                        ])
                    })
                    this.setState({dataTable, loading: 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({ alert: true, messageAlert: response.data.message, tipeAlert: 'error', loading: false })
            }
        })    
    }

    getMonitoringOLPA(payload) {
        let dataTable = []
        api.create().getMonitoringOLPA(payload).then((response) => {
            console.log(response)
            if (response.data) {
                if (response.data.status === "success") {
                    let data = response.data.data
                    data.map((item,index) => {
                        let report = []
                        let statusSubmission = String(item.outlook_status).toLocaleUpperCase()
                        let statusOI = String(item.operating_indicator).toLocaleUpperCase()
                        item.report.map((items,index) => {
                            let statusReport = String(items.status_report).toLocaleUpperCase()
                            report.push({report_name: items.report_name, status_report: (statusReport == 'APPROVED' || statusReport == 'REVISION' || statusReport == 'COMPLETED') ? (statusReport + ' - ' + items.report_date) : statusReport })
                        })
                        report.push(
                            {report_name: 'Operating Indicator', status_report: statusOI}, 
                            {report_name: 'OLPA Status', status_report: (statusSubmission == 'APPROVED' || statusSubmission == 'REVISION' || statusSubmission == 'COMPLETED') ? (statusSubmission + ' - ' + item.submissionStatusDate) : statusSubmission})
                        dataTable.push([
                            item.company_name,
                            report,
                            item.automatic_reminder_report_date,
                            item.manual_reminder_report_status,
                            item.manual_reminder_report_date,
                            item.outlook_status,
                            item.manual_reminder_report_button,
                            item.company_id,
                        ])
                    })
                    // data.map((item,index) => {
                        // let report = []
                        // item.report.map((items,indexs) => {
                        //     if (!String(items.report_name).includes('Indicator') && !String(items.report_name).includes('OLPA')) {
                        //         if (String(items.report_name).includes('Fixed')) {
                        //             report.push({...items, status_report: (items.report_date == null? items.status_report : items.status_report + ' - ' + items.report_date), report_name: 'Fixed Assets Movement'})
                        //         } else {
                        //             report.push({...items, status_report: (items.report_date == null? items.status_report : items.status_report + ' - ' + items.report_date)})
                        //         }
                        //     }
                        // })
                        // report.push({report_name: 'Operating Indicator', status_report: item.operatingIndicator}, {report_name: 'OLPA Status', status_report: (item.submissionStatusDate == null? item.submissionStatus : item.submissionStatus + ' - ' + item.submissionStatusDate)})
                        // dataTable.push([
                        //     item.companyName,
                        //     report
                        // ])
                        // let report = item.report
                        // report.push({report_name: 'Operating Indicator', status_report: item.operating_indicator}, {report_name: 'OLPA Status', status_report: item.olpa_status})
                        // dataTable.push([
                        //     item.company_name,
                        //     report
                        // ])
                    // })
                    this.setState({dataTable, loading: 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({ alert: true, messageAlert: response.data.message, tipeAlert: 'error', loading: false })
            }
        })    
    }

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

    downloadData() {
        let path = ''
        let type = ''
        if (String(this.state.reportType.name).toLocaleUpperCase().includes('MASTER')) {
            path = `public/transaction/monitoring/master_budget?periode=${this.state.periodeMB.name}`
            type = 'Master Budget'
        } else if (String(this.state.reportType.name).toLocaleUpperCase().includes('MONTHLY')) {
            path = `public/transaction/monitoring/monthly_report?months=${this.state.month.month_id}&&periode=${this.state.periodeMB.name}`
            type = `Monthly Report (${this.state.month.month_value})`
        } else if (String(this.state.reportType.name).toLocaleUpperCase().includes('ROLLING')) {
            path = `public/transaction/monitoring/rolling_outlook?quartals=${this.state.quarter.value}&&periode=${this.state.periodeMB.name}`
            type = `Rolling Outlook ${this.state.quarter.name}`
        } else {
            path = `public/transaction/monitoring/outlook_pa?periode=${this.state.periodeMB.name}`
            type = 'Outlook PA'
        }
        this.downloadAllData(path, type)
    }

    async downloadAllData(path, type) {
        let url = `${process.env.REACT_APP_URL_MAIN_BE}/${path}`
        console.log(url);
        let res = await fetch(
            `${process.env.REACT_APP_URL_MAIN_BE}/${path}`
        )
        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 = `Progress Report - ${type}.xlsx`;
            a.click();
        }
    }

    render() {

        const dataTableMB = [
            ['Tax Planning', '2', 'ABA: Anugerah Buminusantara Abadi', '2021-05-03'],
            ['CAT', '1', 'ABA: Anugerah Buminusantara Abadi', '2021-05-03'],
            ['Profit Loss', '0', 'ABA: Anugerah Buminusantara Abadi', '2021-05-03']
        ]

        const dataTableMBStatus = [
            ['ABA: Anugerah Buminusantara Abadi', '2021', 'approved', '2', 'Sudah Approved', 'Sudah Approved', 'Sudah Approved', 'Sudah Approved', 'Sudah Approved', 'Sudah Approved'],
            ['ABA: Anugerah Buminusantara Abadi', '2021', 'approved', '1', 'Sudah Approved', 'Sudah Approved', 'Sudah Approved', 'Sudah Approved', 'Sudah Approved', 'Sudah Approved'],
            ['ABA: Anugerah Buminusantara Abadi', '2021', 'approved', '0', 'Sudah Approved', 'Sudah Approved', 'Sudah Approved', 'Sudah Approved', 'Sudah Approved', 'Sudah Approved']
        ]

        const loadingComponent = (
            <div style={{ position: 'fixed', zIndex: 110, top: 0, left: 0, width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', background: 'rgba(255,255,255,0.8)' }}>
                <PropagateLoader
                    // css={override}
                    size={20}
                    color={"#274B80"}
                    loading={this.state.loading}
                />
            </div>
        );

        return (
            <div style={{ flex: 1, backgroundColor: '#f8f8f8', minHeight: this.props.height }}>
                <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
                    <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
                        {this.state.messageAlert}
                    </Alert>
                </Snackbar>
                <div>
                    <div className={"main-color"} style={{ height: 78, display: 'flex', alignItems: 'center', paddingLeft: 20 }}>
                        <Typography style={{ fontSize: '16px', color: 'white' }}>Report Status & Approval Progress Monitoring</Typography>
                    </div>
                    <div style={{ padding: 20, width: '100%' }}>
                        <Paper style={{ paddingTop: 10, paddingBottom: 50 }}>
                            <div style={{ borderBottom: 'solid 1px #c4c4c4' }} >
                                <Typography style={{ fontSize: '12px', color: '#4b4b4b', margin: 10 }}>Report Status & Approval Progress</Typography>
                            </div>
                            {/* <div style={{ minWidth: 'max-content', padding: '20px 20px 0px 20px' }}>
                                <div style={{ marginTop: 15, display: 'flex' }}>
                                    <Autocomplete
                                        {...this.state.listCategory}
                                        id="category"
                                        onChange={(event, newInputValue) => this.setState({ category: newInputValue, loading: true }, () => {
                                            // this.getListUserSubcoRO()
                                            this.getReportType()
                                            this.setState({ loading: false })
                                        })}
                                        disableClearable
                                        style={{ minWidth: 210, marginRight: 20 }}
                                        renderInput={(params) => <TextField {...params} label="Category" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.category}
                                    />
                                    <Autocomplete
                                        {...this.state.listReportType}
                                        id="report-type"
                                        onChange={(event, newInputValue) => this.setState({ reportType: newInputValue, loading: true }, () => {
                                            // this.getListUserSubcoRO()
                                            this.setState({ loading: false })
                                        })}
                                        disableClearable
                                        style={{ minWidth: 210, marginRight: 20 }}
                                        renderInput={(params) => <TextField {...params} label="Report Type" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.reportType}
                                    />
                                </div>
                            </div> */}
                            <div style={{ minWidth: 'max-content', padding: '20px 20px 0px 20px' }}>
                                <div style={{ marginTop: 15, display: 'flex' }}>
                                    <Autocomplete
                                        {...this.state.listReportType}
                                        id="menu"
                                        onChange={(event, newInputValue) => this.setState({ reportType: newInputValue, loading: true, dataTable: [] }, () => {
                                            // this.getListUserSubcoRO()
                                            this.getDataMonitoring()
                                        })}
                                        disableClearable
                                        style={{ minWidth: 210, marginRight: 20 }}
                                        renderInput={(params) => <TextField {...params} label="Menu" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.reportType}
                                    />
                                    <Autocomplete
                                        {...this.state.listPeriodeMB}
                                        id="periode"
                                        onChange={(event, newInputValue) => this.setState({ periodeMB: newInputValue, loading: true }, () => {
                                            // this.getListUserSubcoRO()
                                            this.getDataMonitoring()
                                        })}
                                        disableClearable
                                        style={{ minWidth: 210, marginRight: 20 }}
                                        renderInput={(params) => <TextField {...params} label="Periode" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.periodeMB}
                                    />
                                    {this.state.reportType != null && this.state.reportType.value == 1 && <Autocomplete
                                        {...this.state.listMonth}
                                        id="month"
                                        onChange={(event, newInputValue) => this.setState({ month: newInputValue, loading: true }, () => {
                                            // this.getListUserSubcoRO()
                                            this.getDataMonitoring()
                                        })}
                                        disableClearable
                                        style={{ minWidth: 210, marginRight: 20 }}
                                        renderInput={(params) => <TextField {...params} label="Month" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.month}
                                    />}
                                    {this.state.reportType != null && this.state.reportType.value == 2 && <Autocomplete
                                        {...this.state.listQuarter}
                                        id="quarter"
                                        onChange={(event, newInputValue) => this.setState({ quarter: newInputValue, loading: true }, () => {
                                            // this.getListUserSubcoRO()
                                            this.getDataMonitoring()
                                        })}
                                        disableClearable
                                        style={{ minWidth: 210, marginRight: 20 }}
                                        renderInput={(params) => <TextField {...params} label="Quarter" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.quarter}
                                    />}
                                </div>
                            </div>
                            <div style={{ marginTop: 20, marginBottom: 20 }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', padding: '0px 20px 10px 20px' }}>
                                    <div></div>
                                    {/* {this.state.previewDownload && ( */}
                                        <div style={{ width: '50%', justifyContent: 'flex-end', display: 'flex', flexFlow: 'wrap' }}>
                                            <a data-tip={'Download'} data-for="download">
                                                <button
                                                    style={{
                                                        backgroundColor: 'transparent',
                                                        cursor: 'pointer',
                                                        borderColor: 'transparent',
                                                        margin: 5,
                                                        outline: 'none'
                                                    }}
                                                    onClick={() => this.setState({ loading: true }, () => {
                                                        setTimeout(() => {
                                                            this.downloadData()
                                                        }, 100);
                                                    })}
                                                >
                                                    <img src={Images.download} />
                                                </button>
                                            </a>
                                            <ReactTooltip border={true} id="download" place="bottom" type="light" effect="solid" />
                                        </div>
                                    {/* )} */}
                                </div>
                                {this.state.loading && loadingComponent}
                                {this.state.reportType != null && !this.state.loading && (
                                <TableProgressReport
                                    width={this.props.width}
                                    // height={this.props.height}
                                    open={this.props.open}
                                    // month={this.state.month.month_value}
                                    category={this.state.category ? this.state.category.value : 1}
                                    reportType={this.state.reportType ? this.state.reportType.value : 0}
                                    dataTable={this.state.dataTable}
                                    // dataTable={this.state.dataTable}
                                    periode={this.state.periode ? this.state.periode.periode : null}
                                    quarter={this.state.quarter.name}
                                    month={this.state.month.month_id}
                                    company={this.state.company_id}
                                    typeReport={String(this.state.reportType.name).toLocaleUpperCase()}
                                    year={this.state.periodeMB.value}
                                    getMonitoringMB={this.getMonitoringMB.bind(this)}
                                    getMonitoringMR={this.getMonitoringMR.bind(this)}
                                    getMonitoringRO={this.getMonitoringRO.bind(this)}
                                    getMonitoringOLPA={this.getMonitoringOLPA.bind(this)}
                                />
                                )}
                            </div>
                        </Paper>
                    </div>
                </div>
            </div>
        );

    }
}

export default ReportProgress;
