import * as React from 'react';
import Paper from '@material-ui/core/Paper';
import { ResponsiveBar } from '@nivo/bar'
import { useTheme } from '@nivo/core'
import { Divider, Snackbar, TextField, Typography, withStyles } from '@material-ui/core';
import MuiAlert from '@material-ui/lab/Alert';
import { Autocomplete } from '@material-ui/lab';
import { titleCase } from '../../library/Utils';
import api from '../../api';
import Constant from '../../library/Constant';
import { format } from 'date-fns';
import { PropagateLoader } from 'react-spinners';
import ReactECharts from 'echarts-for-react';
import { FormatListNumberedRtlOutlined } from '@material-ui/icons';

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

// make sure parent container have a defined height when using
// responsive component, otherwise height will be 0 and
// no chart will be rendered.
// website examples showcase many properties,
// you'll often use just a few of them.
// const MyResponsiveBar = ({ data /* see data tab */ }) => (

// )

export default class DashboardFinancial extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            listReportType: [
                {
                    name: 'GRAPH - MONTHLY BY INDUSTRY',
                    value: 'mtd'
                }, {
                    name: 'GRAPH - YTD BY INDUSTRY',
                    value: 'ytd'
                }, {
                    name: 'GRAPH - MONTHLY HISTORICAL BY COMPANY',
                    value: 'summary'
                },
            ],
            report: {
                name: 'GRAPH - MONTHLY BY INDUSTRY',
                value: 'mtd'
            },
            listCompany: null,
            company: null,
            listPeriode: null,
            periode: null,
            listMonth: null,
            month: null,
            listBusiness: null,
            businessUnit: null,
            listPeriode2: null,
            periode2: null,
            listMonth2: null,
            month2: null,
            loading: false,
            tpat: null,
            companyRev: [],
            mbRev: [],
            mrRev: [],
            minRev: 0,
            maxRev: 0,
            intervalRev: 0,
            companyTPAT: [],
            mbTPAT: [],
            mrTPAT: [],
            minTPAT: 0,
            maxTPAT: 0,
            intervalTPAT: 0,
            companyEBITDA: [],
            mbEBITDA: [],
            mrEBITDA: [],
            minEBITDA: 0,
            maxEBITDA: 0,
            intervalEBITDA: 0,
            data: [],
            defaultMonth: [],
            defaultYear: [],
            revOptions: {},
            tpatOptions: {},
            ebitdaOptions: {},
            totalAssetsOptions: {}
        };
    }

    componentDidMount() {
        console.log(this.props.height)
        this.setState({ loading: true })
        this.getDetailUser()
    }

    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()
                        })
                    }
                    else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

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

                    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.sort((a, b) => a.company_name.localeCompare(b.company_name)),
                        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.getAllBusiness()
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', listCompany: null, company: null })
            }
        })
    }

    getAllBusiness() {
        api.create().getUnitBisnisActive().then((response) => {
            // console.log(response);
            if (response.data) {
                if (response.data.status === 'success') {
                    let data = response.data.data
                    console.log(data)
                    // let comID = this.state.rawData ? this.state.rawData.company_id : 0
                    let businessData = data.map((item) => {
                        return {
                            business_unit_id: item.business_unit_id,
                            business_unit_name: String(item.business_unit_name).toLocaleLowerCase(),
                        }
                    })
                    businessData.sort((a, b) => a.business_unit_name.localeCompare(b.business_unit_name))
                    let defaultProps = {
                        options: businessData,
                        getOptionLabel: (option) => titleCase(option.business_unit_name),
                    };
                    // let index = arrayBaru.findIndex((val) => val.company_id == comID)
                    this.setState({ listBusiness: defaultProps, businessUnit: businessData[0] }, () => {
                        this.getMonth()
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', listCompany: null, company: null })
            }
        })
    }

    getMonth() {
        api.create().getMonthTransaction().then(response => {
            let dateNow = new Date()
            dateNow.setMonth(dateNow.getMonth() - 1);
            let month = format(dateNow, 'MMMM')
            console.log(response);
            if (response.data) {
                if (response.data.status === "success") {
                    console.log(response);
                    let data = response.data.data
                    let index = data.findIndex((val) => val.month_name == month)
                    let monthData = []
                    let defaultMonth = []
                    data.map((item, indexs) => {
                        if (indexs <= index + 1) {
                            monthData.push({
                                month_id: item.id,
                                month_value: String(item.month_name).substr(0, 3)
                            })
                        }
                        defaultMonth.push({
                            month_id: item.id,
                            month_value: String(item.month_name).substr(0, 3)
                        })
                    })
                    let defaultProps = {
                        options: monthData,
                        getOptionLabel: (option) => option.month_value,
                    };

                    console.log(monthData);
                    this.setState({ defaultMonth, listMonth: defaultProps, listMonth2: defaultProps, month: index == -1 ? monthData[0] : monthData[index], month2: index == -1 ? monthData[1] : monthData[index + 1], }, () => {
                        console.log(this.state.month)
                        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() {
        api.create().getPeriodeTransaction().then(response => {
            let currentYear = new Date().getFullYear()
            // console.log(currentYear)
            if (response.data) {
                if (response.data.status === "success") {
                    let data = []
                    response.data.data.map((item) => {
                        // if (this.state.isApprover) {
                        if (item >= 2000 && item <= (Number(currentYear))) {
                            data.push(item)
                        }
                        // }
                    })
                    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 dateNow = new Date()
                    dateNow.setMonth(dateNow.getMonth() - 1);
                    let yearNow = dateNow.getFullYear()
                    let index = data.sort((a, b) => a - b).findIndex((val) => val == yearNow)
                    console.log(data)
                    // console.log(this.state.latestPeriode)
                    // console.log(periodeData)
                    // console.log(index)
                    this.setState({ listPeriode: defaultProps, listPeriode2: { ...defaultProps, options: [periodeData[index]] }, periode: index === -1 ? periodeData[0] : periodeData[index], periode2: periodeData[index] }, () => {
                        this.getDashboardFinancial()
                    })
                }
            }
        })
    }

    getOption() {
        let option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: '#999'
                    }
                }
            },
            toolbox: {
                feature: {
                    dataView: { show: true, readOnly: false },
                    magicType: { show: true, type: ['line', 'bar'] },
                    restore: { show: true },
                    saveAsImage: { show: true }
                }
            },
            legend: {
                data: ['蒸发量', '降水量', '平均温度']
            },
            xAxis: [
                {
                    type: 'category',
                    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                    axisPointer: {
                        type: 'shadow'
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '水量',
                    min: 0,
                    max: 250,
                    interval: 50,
                    axisLabel: {
                        formatter: '{value} ml'
                    }
                },
                {
                    type: 'value',
                    name: '温度',
                    min: 0,
                    max: 25,
                    interval: 5,
                    axisLabel: {
                        formatter: '{value} °C'
                    }
                }
            ],
            series: [
                {
                    name: '蒸发量',
                    type: 'bar',
                    data: [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
                },
                {
                    name: '降水量',
                    type: 'bar',
                    data: [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
                },
                {
                    name: '平均温度',
                    type: 'line',
                    yAxisIndex: 1,
                    data: [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]
                }
            ]
        };

        return option
    }

    getDashboardFinancial() {
        let payload = {
            "report_type": this.state.report.value,
            "business_unit_id": this.state.businessUnit.business_unit_id,
            "periode": this.state.periode.periode,
            "months": this.state.month.month_id
        }
        if (this.state.report.value == 'summary') {
            payload = {
                ...payload,
                "company_id": this.state.company.company_id,
                "periode_from": this.state.periode.periode,
                "periode_to": this.state.periode2.periode,
                "month_from": this.state.month.month_id,
                "month_to": this.state.month2.month_id
            }
        }

        const handleName = (name) => {
            let newName = ''
            if (String(name).includes(':')) {
                let indexTidu = String(name).indexOf(':')
                let indexSpace = String(name).indexOf(' ')
                if (indexTidu > indexSpace) {
                    newName = String(name).substr(0, indexSpace)
                } else {
                    newName = String(name).substr(0, indexTidu)
                }
            } else {
                // if (String(name).includes('Consolidated')) {
                //     newName = `asd \n baba`
                // } else {
                let splitName = String(name).split(' ')
                // console.log(splitName)
                newName = name
                // }
            }
            return newName
        }
        api.create().getDashboardFinancial(payload).then((res) => {
            console.log(res)
            if (res.data) {
                let response = res.data.data.ytd != null ? res.data.data.ytd : (res.data.data.mtd != null ? res.data.data.mtd : res.data.data.summary)
                let revenue = []
                let totalAssets = []

                let companyRev = []
                let mbRev = []
                let mrRev = []
                let maxRev = response.revenue.vertical_pointing[0]
                let minRev = response.revenue.vertical_pointing[1]
                let intervalRev = Number(response.revenue.interval)

                let companyTPAT = []
                let mbTPAT = []
                let mrTPAT = []
                let maxTPAT = response.tpat.vertical_pointing[0]
                let minTPAT = response.tpat.vertical_pointing[1]
                let intervalTPAT = Number(response.tpat.interval)

                let companyEBITDA = []
                let mbEBITDA = []
                let mrEBITDA = []
                let maxEBITDA = response.ebitda.vertical_pointing[0]
                let minEBITDA = response.ebitda.vertical_pointing[1]
                let intervalEBITDA = Number(response.ebitda.interval)

                let companyTA = []
                let mbTA = []
                let maxTA = 0
                let minTA = 0
                let intervalTA = 0
                if (response.total_asset != undefined) {
                    intervalTA = Number(response.total_asset.interval)
                    maxTA = response.total_asset.vertical_pointing[0]
                    minTA = response.total_asset.vertical_pointing[1]
                }

                let respRev = this.state.report.value == 'summary' ? response.revenue.nodes.sort((a, b) => a.index - b.index) : response.revenue.nodes.sort((a, b) => a.company.localeCompare(b.company))
                respRev.map((item, index) => {
                    if (this.state.report.value == 'summary') {
                        companyRev.push(item.periode)
                        mbRev.push(Number(item.value))
                        mrRev.push(Number(item.gp_margin).toFixed(1))
                    } else {
                        companyRev.push(handleName(item.company))
                        mbRev.push(Number(item.value_mb))
                        mrRev.push(Number(item.value_mr))
                    }

                })

                let revOptions = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            crossStyle: {
                                color: '#999'
                            }
                        }
                    },
                    toolbox: {
                        feature: {
                            // restore: { show: true },
                            // saveAsImage: { show: true }
                        }
                    },
                    legend: {
                        data: ['MB', 'MR', 'Revenue', 'GP Margin']
                    },
                    grid: {
                        bottom: 125,
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: companyRev,
                            axisPointer: {
                                type: 'shadow'
                            },
                            axisLabel: {
                                interval: 0,
                                rotate: 30,
                                textStyle: {
                                    baseline: "top",
                                    color: "#333",
                                    fontSize: 13,
                                }
                            }
                        }
                    ],
                    yAxis: this.state.report.value != 'summary' ?
                        [
                            {
                                type: 'value',
                                name: '(Rp bn)',
                                min: minRev,
                                max: maxRev,
                                interval: intervalRev,
                                axisLabel: {
                                    interval: 0,
                                    // rotate: 10,
                                    textStyle: {
                                        baseline: "top",
                                        color: "#333",
                                        fontSize: 12,
                                        // fontWeight: "bold"
                                    }
                                }
                            }
                        ] :
                        [
                            {
                                type: 'value',
                                name: '(Rp bn)',
                                min: minRev,
                                max: maxRev,
                                interval: intervalRev,
                                axisLabel: {
                                    interval: 0,
                                    textStyle: {
                                        baseline: "top",
                                        color: "#333",
                                        fontSize: 12,
                                    }
                                }
                            },
                            {
                                type: 'value',
                                name: '(%)',
                                min: 0,
                                max: 100,
                                interval: 20,
                                axisLabel: {
                                    formatter: '{value}%',
                                    interval: 0,
                                    textStyle: {
                                        baseline: "top",
                                        color: "#333",
                                        fontSize: 12,
                                    }
                                }
                            }
                        ]
                    ,
                    series: this.state.report.value != 'summary' ?
                        [
                            {
                                name: 'MB',
                                type: 'bar',
                                data: mbRev
                            },
                            {
                                name: 'MR',
                                type: 'bar',
                                data: mrRev
                            }
                        ] :
                        [
                            {
                                name: 'Revenue',
                                type: 'bar',
                                data: mbRev
                            },
                            {
                                name: 'GP Margin',
                                type: 'line',
                                yAxisIndex: 1,
                                data: mrRev
                            }
                        ]
                }

                let respTpat = this.state.report.value == 'summary' ? response.tpat.nodes.sort((a, b) => a.index - b.index) : response.tpat.nodes.sort((a, b) => a.company.localeCompare(b.company))
                respTpat.map((item, index) => {
                    if (this.state.report.value == 'summary') {
                        companyTPAT.push(item.periode)
                        mbTPAT.push(Number(item.value))
                        mrTPAT.push(Number(item.gp_margin).toFixed(1))
                    } else {
                        companyTPAT.push(handleName(item.company))
                        mbTPAT.push(Number(item.value_mb))
                        mrTPAT.push(Number(item.value_mr))
                    }
                })

                let tpatOptions = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            crossStyle: {
                                color: '#999'
                            }
                        }
                    },
                    toolbox: {
                        feature: {
                            // restore: { show: true },
                            // saveAsImage: { show: true }
                        }
                    },
                    legend: {
                        data: ['MB', 'MR', 'TPAT', 'TPAT Margin']
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: companyTPAT,
                            axisPointer: {
                                type: 'shadow'
                            },
                            axisLabel: {
                                interval: 0,
                                rotate: 30,
                                textStyle: {
                                    baseline: "top",
                                    color: "#333",
                                    fontSize: 13,
                                }
                            }
                        }
                    ],
                    yAxis: this.state.report.value != 'summary' ?
                        [
                            {
                                type: 'value',
                                name: '(Rp bn)',
                                min: minTPAT,
                                max: maxTPAT,
                                interval: intervalTPAT
                            }
                        ] :
                        [
                            {
                                type: 'value',
                                name: '(Rp bn)',
                                min: minTPAT,
                                max: maxTPAT,
                                interval: intervalTPAT,
                                axisLabel: {
                                    interval: 0,
                                    textStyle: {
                                        baseline: "top",
                                        color: "#333",
                                        fontSize: 12,
                                    }
                                }
                            },
                            {
                                type: 'value',
                                name: '(%)',
                                min: 0,
                                max: 100,
                                interval: 20,
                                axisLabel: {
                                    formatter: '{value}%',
                                    interval: 0,
                                    textStyle: {
                                        baseline: "top",
                                        color: "#333",
                                        fontSize: 12,
                                    }
                                }
                            }
                        ]
                    ,
                    grid: {
                        bottom: 125,
                    },
                    series: this.state.report.value != 'summary' ?
                        [
                            {
                                name: 'MB',
                                type: 'bar',
                                data: mbTPAT
                            },
                            {
                                name: 'MR',
                                type: 'bar',
                                data: mrTPAT
                            }
                        ] :
                        [
                            {
                                name: 'TPAT',
                                type: 'bar',
                                data: mbTPAT
                            },
                            {
                                name: 'TPAT Margin',
                                type: 'line',
                                yAxisIndex: 1,
                                data: mrTPAT
                            }
                        ]
                }

                let respEbit = this.state.report.value == 'summary' ? response.ebitda.nodes.sort((a, b) => a.index - b.index) : response.ebitda.nodes.sort((a, b) => a.company.localeCompare(b.company))
                respEbit.map((item, index) => {
                    if (this.state.report.value == 'summary') {
                        companyEBITDA.push(item.periode)
                        mbEBITDA.push(Number(item.value))
                        mrEBITDA.push(Number(item.gp_margin).toFixed(1))
                    } else {
                        companyEBITDA.push(handleName(item.company))
                        mbEBITDA.push(Number(item.value_mb))
                        mrEBITDA.push(Number(item.value_mr))
                    }
                })

                let ebitdaOptions = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            crossStyle: {
                                color: '#999'
                            }
                        }
                    },
                    toolbox: {
                        feature: {
                            // restore: { show: true },
                            // saveAsImage: { show: true }
                        }
                    },
                    legend: {
                        data: ['MB', 'MR', 'EBITDA', 'EBITDA Margin']
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: companyEBITDA,
                            axisPointer: {
                                type: 'shadow'
                            },
                            axisLabel: {
                                interval: 0,
                                rotate: 30,
                                textStyle: {
                                    baseline: "top",
                                    color: "#333",
                                    fontSize: 13,
                                }
                            }
                        }
                    ],
                    yAxis: this.state.report.value != 'summary' ?
                        [
                            {
                                type: 'value',
                                name: '(Rp bn)',
                                min: minEBITDA,
                                max: maxEBITDA,
                                interval: intervalEBITDA,
                                axisLabel: {
                                    interval: 0,
                                    textStyle: {
                                        baseline: "top",
                                        color: "#333",
                                        fontSize: 12,
                                    }
                                }
                            }
                        ] :
                        [
                            {
                                type: 'value',
                                name: '(Rp bn)',
                                min: minEBITDA,
                                max: maxEBITDA,
                                interval: intervalEBITDA,
                                axisLabel: {
                                    interval: 0,
                                    textStyle: {
                                        baseline: "top",
                                        color: "#333",
                                        fontSize: 12,
                                    }
                                }
                            },
                            {
                                type: 'value',
                                name: '(%)',
                                min: 0,
                                max: 100,
                                interval: 20,
                                axisLabel: {
                                    formatter: '{value}%',
                                    interval: 0,
                                    textStyle: {
                                        baseline: "top",
                                        color: "#333",
                                        fontSize: 12,
                                    }
                                }
                            }
                        ]
                    ,
                    grid: {
                        bottom: 125,
                    },
                    series: this.state.report.value != 'summary' ?
                        [
                            {
                                name: 'MB',
                                type: 'bar',
                                data: mbEBITDA
                            },
                            {
                                name: 'MR',
                                type: 'bar',
                                data: mrEBITDA
                            }
                        ] :
                        [
                            {
                                name: 'EBITDA',
                                type: 'bar',
                                data: mbEBITDA
                            },
                            {
                                name: 'EBITDA Margin',
                                type: 'line',
                                yAxisIndex: 1,
                                data: mrEBITDA
                            }
                        ]
                }

                if (this.state.report.value == 'summary') {
                    response.total_asset.nodes.sort((a, b) => a.index - b.index).map((item, index) => {
                        companyTA.push(item.periode)
                        mbTA.push(item.value)
                    })

                    let totalAssetsOptions = {
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'cross',
                                crossStyle: {
                                    color: '#999'
                                }
                            }
                        },
                        toolbox: {
                            feature: {
                                // restore: { show: true },
                                // saveAsImage: { show: true }
                            }
                        },
                        legend: {
                            data: ['MB']
                        },
                        grid: {
                            bottom: 125,
                        },
                        xAxis: [
                            {
                                type: 'category',
                                data: companyTA,
                                axisPointer: {
                                    type: 'shadow'
                                },
                                axisLabel: {
                                    interval: 0,
                                    rotate: 30,
                                    textStyle: {
                                        baseline: "top",
                                        color: "#333",
                                        fontSize: 13,
                                    }
                                }
                            }
                        ],
                        yAxis:
                            [
                                {
                                    type: 'value',
                                    name: '(Rp bn)',
                                    min: minTA,
                                    max: maxTA,
                                    interval: intervalTA
                                }
                            ]
                        ,
                        series:
                            [
                                {
                                    name: 'MB',
                                    type: 'bar',
                                    data: mbTA
                                }
                            ]
                    }

                    this.setState({ totalAssetsOptions })
                }


                this.setState({ revOptions, tpatOptions, ebitdaOptions }, () => {
                    setTimeout(() => {
                        this.setState({ loading: false })
                    }, 300);
                })
            }
        })
    }

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

            return (
                <g transform={`translate(${tick.x},${tick.y + 22})`}>
                    {/* <rect x={-14} y={-6} rx={3} ry={3} width={28} height={24} fill="rgba(0, 0, 0, .05)" />
                    <rect x={-12} y={-12} rx={2} ry={2} width={24} height={24} fill="rgb(232, 193, 160)" />
                    <line stroke="rgb(232, 193, 160)" strokeWidth={1.5} y1={-22} y2={-12} /> */}
                    <text
                        lengthAdjust
                        fontSizeAdjust
                        textAnchor="middle"
                        dominantBaseline="middle"
                        style={{
                            ...theme.axis.ticks.text,
                            fill: '#333',
                            fontSize: 11,
                            // textAlign: 'justify',
                        }}
                    >
                        {tick.value}
                    </text>
                </g>
            )
        }
        return (
            <div style={{ flex: 1, backgroundColor: '#f8f8f8' }} ref={this.myRef}>
                {/* {this.state.loading && loadingComponent} */}
                <div>
                    <div className={"main-color"} style={{ height: 78, display: 'flex', alignItems: 'center', paddingLeft: 20 }}>
                        <Typography style={{ fontSize: '16px', color: 'white' }}>Dashboard Financial</Typography>
                    </div>
                    <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
                        <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
                            {this.state.messageAlert}
                        </Alert>
                    </Snackbar>
                    <div style={{ padding: 20, width: '100%' }}>
                        <Paper style={{ paddingTop: 10, minHeight: this.props.height, paddingBottom: 20 }}>
                            <div style={{ borderBottom: 'solid 1px #c4c4c4' }} >
                                <Typography style={{ fontSize: '12px', color: '#4b4b4b', margin: 10 }}>FINANCIAL SUMMARY OF TRIPUTRA GROUP</Typography>
                            </div>
                            <div style={{ minWidth: 'max-content', padding: '20px 20px 0px 20px' }}>
                                <div style={{ marginTop: 15 }}>
                                    <Autocomplete
                                        options={this.state.listReportType}
                                        getOptionLabel={(option) => titleCase(option.name)}
                                        id="typereport"
                                        onChange={(event, newInputValue) => this.setState({ report: newInputValue, loading: true, previewTable: false }, () => {
                                            this.getDashboardFinancial()
                                        })}
                                        disableClearable
                                        style={{ width: 250 }}
                                        renderInput={(params) => <TextField {...params} label="Report Type" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.report}
                                    />
                                </div>
                                <div style={{ display: 'flex', marginTop: 10 }}>
                                    <Autocomplete
                                        {...this.state.listMonth}
                                        id="month"
                                        onChange={(event, newInputValue) => this.setState({ month: newInputValue, loading: true }, () => {
                                            let indexMonth1 = this.state.listMonth.options.findIndex((val) => val.month_value == newInputValue.month_value)
                                            let listMonth2 = []
                                            this.state.listMonth.options.map((item, index) => {
                                                if (index >= indexMonth1) {
                                                    listMonth2.push(item)
                                                }
                                            })
                                            this.setState({ listMonth2: Number(this.state.periode.periode) < Number(this.state.periode2.periode) ? this.state.listMonth2 : { ...this.state.listMonth2, options: listMonth2, month2: listMonth2[0] } }, () => {
                                                this.setState({ month2: Number(this.state.periode.periode) < Number(this.state.periode2.periode) ? this.state.month2 : this.state.listMonth2.options[0] })
                                            })
                                            this.getDashboardFinancial()
                                        })}
                                        disableClearable
                                        style={{ minWidth: 250, marginRight: 20 }}
                                        renderInput={(params) => <TextField {...params} label="Month" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.month}
                                    />
                                    <Autocomplete
                                        {...this.state.listPeriode}
                                        id="periode"
                                        onChange={(event, newInputValue) => this.setState({ periode: newInputValue, loading: true }, () => {
                                            let indexPeriode1 = this.state.listPeriode.options.findIndex((val) => val.periode == newInputValue.periode)
                                            let listPeriode2 = []
                                            let listMonth = []
                                            let listMonth2 = this.state.listMonth2.options
                                            let dateNow = new Date()
                                            let dateNow2 = new Date()
                                            let yearNow = dateNow.getFullYear()
                                            dateNow2.setMonth(dateNow2.getMonth() - 1);
                                            let month = format(dateNow2, 'MMMM')
                                            this.state.listPeriode.options.map((item, index) => {
                                                if (index >= indexPeriode1) {
                                                    listPeriode2.push(item)
                                                }
                                            })

                                            let data = this.state.defaultMonth
                                            let index = data.findIndex((val) => val.month_value == String(month).substr(0, 3))
                                            let monthData = []
                                            let monthData2 = []

                                            if (Number(newInputValue.periode) < Number(yearNow)) {
                                                listMonth = this.state.defaultMonth
                                                data.map((item, indexs) => {
                                                    if (indexs <= index + 1) {
                                                        monthData2.push({
                                                            month_id: item.month_id,
                                                            month_value: String(item.month_value).substr(0, 3)
                                                        })
                                                    }
                                                })
                                                listMonth2 = monthData2
                                            } else {
                                                data.map((item, indexs) => {
                                                    if (indexs <= index + 1) {
                                                        monthData.push({
                                                            month_id: item.month_id,
                                                            month_value: String(item.month_value).substr(0, 3)
                                                        })
                                                    }
                                                })
                                                listMonth = monthData
                                            }
                                            this.setState({ listPeriode2: { ...this.state.listPeriode2, options: listPeriode2, periode2: listPeriode2[0], } }, () => {
                                                this.setState({
                                                    periode2: Number(this.state.periode.periode) < Number(this.state.periode2.periode) ? this.state.periode2 : this.state.listPeriode2.options[0],
                                                    listMonth: { ...this.state.listMonth, options: listMonth },
                                                    listMonth2: { ...this.state.listMonth2, options: listMonth2 },
                                                    month: Number(newInputValue.periode) < Number(this.state.periode.periode) ? this.state.month : listMonth[0]
                                                }, () => {
                                                    this.getDashboardFinancial()
                                                })
                                            })
                                        })}
                                        disableClearable
                                        style={{ width: 250 }}
                                        renderInput={(params) => <TextField {...params} label="Period" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.periode}
                                    />
                                    {this.state.report.value == 'summary' && <Typography style={{ fontSize: '16px', color: 'black', alignSelf: 'center', marginLeft: 25, marginRight: 25, paddingTop: 25 }}>To</Typography>}
                                    {this.state.report.value == 'summary' && <Autocomplete
                                        {...this.state.listMonth2}
                                        id="month"
                                        onChange={(event, newInputValue) => this.setState({ month2: newInputValue, loading: true }, () => {
                                            this.getDashboardFinancial()
                                        })}
                                        disableClearable
                                        style={{ minWidth: 250, marginRight: 20 }}
                                        renderInput={(params) => <TextField {...params} label="Month" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.month2}
                                    />}
                                    {this.state.report.value == 'summary' && <Autocomplete
                                        {...this.state.listPeriode2}
                                        id="periode"
                                        onChange={(event, newInputValue) => this.setState({ periode2: newInputValue, loading: true }, () => {
                                            let dateNow = new Date()
                                            let yearNow = dateNow.getFullYear()
                                            let data = this.state.defaultMonth
                                            let monthData2 = []
                                            let dateNow2 = new Date()
                                            dateNow2.setMonth(dateNow2.getMonth() - 1);
                                            let month = format(dateNow2, 'MMMM')
                                            if (Number(this.state.periode2.periode) < Number(yearNow)) {
                                                if (Number(this.state.periode2.periode) == Number(this.state.periode.periode)) {
                                                    let index = data.findIndex((val) => val.month_value == this.state.month.month_value)
                                                    data.map((item, indexs) => {
                                                        if (indexs >= index) {
                                                            monthData2.push({
                                                                month_id: item.month_id,
                                                                month_value: String(item.month_value).substr(0, 3)
                                                            })
                                                        }
                                                    })
                                                    let listMonth2 = monthData2
                                                    this.setState({ month2: listMonth2[0], listMonth2: { ...this.state.listMonth2, options: listMonth2 } }, () => {
                                                        this.getDashboardFinancial()
                                                    })
                                                } else {
                                                    this.setState({ listMonth2: { ...this.state.listMonth2, options: this.state.defaultMonth } }, () => {
                                                        this.getDashboardFinancial()
                                                    })
                                                }
                                            } else {
                                                let index = data.findIndex((val) => val.month_value == String(month).substr(0, 3))
                                                data.map((item, indexs) => {
                                                    if (indexs <= index + 1) {
                                                        monthData2.push({
                                                            month_id: item.month_id,
                                                            month_value: String(item.month_value).substr(0, 3)
                                                        })
                                                    }
                                                })
                                                let listMonth2 = monthData2
                                                this.setState({ listMonth2: { ...this.state.listMonth2, options: listMonth2 } }, () => {
                                                    this.setState({ month2: this.state.listMonth2.options[0] }, () => {
                                                        this.getDashboardFinancial()
                                                    })
                                                })
                                            }
                                        })}
                                        disableClearable
                                        style={{ width: 250 }}
                                        renderInput={(params) => <TextField {...params} label="Period" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.periode2}
                                    />}
                                </div>
                                {/* {this.state.report.value == 'summary' && <div style={{ display: 'flex', marginTop: 10}}>
                                    
                                </div>} */}
                                {this.state.report.value != 'summary' && <div style={{ marginTop: 10 }}>
                                    <Autocomplete
                                        {...this.state.listBusiness}
                                        id="company"
                                        disabled={this.state.intent === 'Home' ? true : false}
                                        onChange={(event, newInputValue) => this.setState({ businessUnit: newInputValue, loading: true, previewTable: false }, () => {
                                            this.getDashboardFinancial()
                                        })}
                                        disableClearable
                                        style={{ width: 250 }}
                                        renderInput={(params) => <TextField {...params} label="Business Unit" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.businessUnit}
                                    />
                                </div>}
                                {this.state.report.value == 'summary' && <div style={{ marginTop: 10 }}>
                                    <Autocomplete
                                        {...this.state.listCompany}
                                        id="company"
                                        disabled={this.state.intent === 'Home' ? true : false}
                                        onChange={(event, newInputValue) => this.setState({ company: newInputValue, loading: true, previewTable: false }, () => {
                                            this.getDashboardFinancial()
                                        })}
                                        disableClearable
                                        style={{ width: 250 }}
                                        renderInput={(params) => <TextField {...params} label="Company" margin="normal" style={{ marginTop: 7 }} />}
                                        value={this.state.company}
                                    />
                                </div>}
                                {/* <div style={{ marginTop: 15 }}>
                                    <Autocomplete
                                        {...this.state.listPeriode}
                                        id="periode"
                                        onChange={(event, newInputValue) => this.setState({ periode: newInputValue, loading: true, previewTable: false }, () => {
                                            this.getReportType()
                                        })}
                                        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>
                            <Divider style={{ marginTop: 15 }} />
                            <div style={{ minWidth: 'max-content', padding: '20px 20px 0px 20px' }}>
                                <div>
                                    <Typography style={{ fontSize: '16px', color: 'black' }}>{this.state.report.value == 'mtd' ? 'Graph MTD by Industry' : this.state.report.value == 'ytd' ? 'Graph YTD by Industry' : 'Graph Monthly Historical by Company'}</Typography>
                                    {this.state.month != null && this.state.periode != null && <Typography style={{ fontSize: '16px', color: 'black' }}>Period : {String(this.state.month.month_value).toLocaleUpperCase()} {this.state.periode.periode}</Typography>}
                                    <Typography style={{ fontSize: '16px', color: 'black' }}>in IDR mn</Typography>
                                </div>

                                <div style={{ height: Number(0.6 * this.props.height), border: '1px solid black', marginTop: 25, paddingBottom: 50 }}>
                                    {this.state.businessUnit != null && <Typography style={{ fontSize: '16px', color: 'black', textAlign: 'center', marginTop: 10, marginBottom: 10 }}>{`Revenue ${this.state.report.value == 'mtd' || this.state.report.value == 'ytd' ? String(this.state.report.value).toLocaleUpperCase() : ''} - ${this.state.report.value == 'mtd' || this.state.report.value == 'ytd' ? titleCase(this.state.businessUnit.business_unit_name) : this.state.company.company_name}`}</Typography>}
                                    {<ReactECharts
                                        showLoading={this.state.loading}
                                        style={{ height: 500, width: '100%', marginTop: 20 }}
                                        option={this.state.revOptions}
                                    />}
                                </div>

                                <div style={{ height: Number(0.6 * this.props.height), border: '1px solid black', marginTop: 50, paddingBottom: 50 }}>
                                    {this.state.businessUnit != null && <Typography style={{ fontSize: '16px', color: 'black', textAlign: 'center', marginTop: 10, marginBottom: 10 }}>{`TPAT ${this.state.report.value == 'mtd' || this.state.report.value == 'ytd' ? String(this.state.report.value).toLocaleUpperCase() : ''} - ${this.state.report.value == 'mtd' || this.state.report.value == 'ytd' ? titleCase(this.state.businessUnit.business_unit_name) : this.state.company.company_name}`}</Typography>}
                                    {<ReactECharts
                                        showLoading={this.state.loading}
                                        style={{ height: 500, width: '100%', marginTop: 20 }}
                                        option={this.state.tpatOptions}
                                    />}
                                </div>

                                <div style={{ height: Number(0.6 * this.props.height), border: '1px solid black', marginTop: 50, paddingBottom: 50 }}>
                                    {this.state.businessUnit != null && <Typography style={{ fontSize: '16px', color: 'black', textAlign: 'center', marginTop: 10, marginBottom: 10 }}>{`EBITDA ${this.state.report.value == 'mtd' || this.state.report.value == 'ytd' ? String(this.state.report.value).toLocaleUpperCase() : ''} - ${this.state.report.value == 'mtd' || this.state.report.value == 'ytd' ? titleCase(this.state.businessUnit.business_unit_name) : this.state.company.company_name}`}</Typography>}
                                    {<ReactECharts
                                        lazyUpdate={true}
                                        showLoading={this.state.loading}
                                        style={{ height: 500, width: '100%', marginTop: 20 }}
                                        option={this.state.ebitdaOptions}
                                    />}
                                </div>

                                {this.state.report.value == 'summary' && <div style={{ height: Number(0.6 * this.props.height), border: '1px solid black', marginTop: 50, paddingBottom: 50 }}>
                                    <Typography style={{ fontSize: '16px', color: 'black', textAlign: 'center', marginTop: 10, marginBottom: 10 }}>{`Total Assets - ${this.state.company.company_name}`}</Typography>
                                    {<ReactECharts
                                        style={{ height: 500, width: '100%', marginTop: 20 }}
                                        showLoading={this.state.loading}
                                        option={this.state.totalAssetsOptions}
                                    />}
                                </div>}
                            </div>
                        </Paper>
                    </div>
                </div>
            </div>
        );
    }
}
