import React, { Component } from 'react'
import { Checkbox, FormControlLabel, Menu, Paper, Typography, Button } from '@material-ui/core'
import Images from '../../assets/Images'
import NumberFormat from 'react-number-format';
import ReactECharts from 'echarts-for-react';

export default class StrategiMap extends Component {
    constructor(props) {
        super(props)
        this.state = {
            openMenu: false,
            dataStrategy: this.props.data.kpi.category,
            checkAll: true,
            checkYTD: true,
            checkAB: true,
            checkYoy: true,
            loading: false,
            dataStrategyNew: []
        }
    }

    componentDidMount() {
        this.setState({ loading: true })
        this.olahDataKPI()
    }

    handleKPI(name) {
        let arrayCAT = this.props.tableCAT
        let indexID = this.props.tableCAT.findIndex((val) => String(val[5]).toLocaleLowerCase() == String(name).toLocaleLowerCase())
        return arrayCAT[indexID][8]
    }

    olahDataKPI() {
        console.log(this.state.dataStrategy)
        let arrayNew = this.state.dataStrategyNew
        this.state.dataStrategy.map((item, index) => {
            let arrayNodes = []
            item.nodes.map((itemz, indexz) => {
                let kpi = this.handleKPI(itemz.item_name)
                let act = []
                let mbv = []
                let yoy = []
                let minACT = 0
                let maxACT = 0
                let minMBV = 0
                let maxMBV = 0
                let minYOY = 0
                let maxYOY = 0
                itemz.trends.map((items, indexs) => {
                    act.push(items.nodes_actual_value)
                    mbv.push(items.nodes_mb_value)
                    yoy.push(items.nodes_yoy_value)

                    if (minACT > items.nodes_actual_value) {
                        minACT = items.nodes_actual_value
                    }
                    if (maxACT < items.nodes_actual_value) {
                        maxACT = items.nodes_actual_value
                    }
                    if (minMBV > items.nodes_mb_value) {
                        minMBV = items.nodes_mb_value
                    }
                    if (maxMBV < items.nodes_mb_value) {
                        maxMBV = items.nodes_mb_value
                    }
                    if (minYOY > items.nodes_yoy_value) {
                        minYOY = items.nodes_yoy_value
                    }
                    if (maxYOY < items.nodes_yoy_value) {
                        maxYOY = items.nodes_yoy_value
                    }
                })
                let sortMin = []
                let sortMax = []
                if (this.state.checkAll) {
                    sortMin = [minACT, minMBV, minYOY].sort((a, b) => a - b)
                    sortMax = [maxACT, maxMBV, maxYOY].sort((a, b) => b - a)
                } else if (this.state.checkAB && this.state.checkYTD && !this.state.checkYoy) {
                    sortMin = [minACT, minMBV].sort((a, b) => a - b)
                    sortMax = [maxACT, maxMBV].sort((a, b) => b - a)
                } else if (this.state.checkAB && !this.state.checkYTD && this.state.checkYoy) {
                    sortMin = [minACT, minYOY].sort((a, b) => a - b)
                    sortMax = [maxACT, maxYOY].sort((a, b) => b - a)
                } else if (this.state.checkAB && !this.state.checkYTD && !this.state.checkYoy) {
                    sortMin = [minMBV]
                    sortMax = [maxMBV]
                } else if (!this.state.checkAB && this.state.checkYTD && this.state.checkYoy) {
                    sortMin = [minMBV, minYOY].sort((a, b) => a - b)
                    sortMax = [maxMBV, maxYOY].sort((a, b) => b - a)
                } else if (!this.state.checkAB && this.state.checkYTD && !this.state.checkYoy) {
                    sortMin = [minMBV]
                    sortMax = [maxMBV]
                } else if (!this.state.checkAB && !this.state.checkYTD && this.state.checkYoy) {
                    sortMin = [minYOY]
                    sortMax = [maxYOY]
                }
                arrayNodes.push({ ...itemz, kpi, trends: { act, mbv, yoy, minACT, maxACT, minMBV, maxMBV, minYOY, maxYOY, sortMin, sortMax } })
            })
            arrayNew.push({ ...item, nodes: arrayNodes })
        })
        console.log(arrayNew)
        console.log(this.state.checkAll)
        this.setState({ dataStrategyNew: arrayNew }, () => {
            setTimeout(() => {
                this.setState({ loading: false })
            }, 500);
        })
    }

    handleAch(item) {
        let value = String(item)
        value = String(value).substr(0, String(value).length - 1)
        return Number(value)
    }

    render() {
        const data = [
            {
                color: "steelblue",
                points: [{ x: 1, y: 1 }, { x: 2, y: 2 }, { x: 3, y: -2 }]
            },
            {
                color: "green",
                points: [{ x: 1, y: 2 }, { x: 2, y: 3 }, { x: 3, y: 5 }]
            }
        ];

        const optionvv = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: '#999'
                    }
                }
            },
            grid: {
                left: 0,
                bottom: 0
            },
            xAxis: {
                type: 'category',
                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                data: [150, 230, 224, 218, 135, 147, 260],
                type: 'line'
            }]
        };
        const newTitleCase = (val) => {
            let value = val
            return value.split(' ')
                .map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
                .join(' ')
        }
        const handleIsHigher = (item) => {
            let actMo = 0
            let prevMo = 0
            let isHigh = 'false'
            let trends = [...item.trends.act]
            let trendsLength = trends.length

            if (trendsLength < 2) {
                actMo = trends[0]
            } else {
                actMo = trends[trendsLength-1]
                prevMo = trends[trendsLength-2]
            }

            if (actMo > prevMo) {
                isHigh = item.kpi == 'HIG' ? 'true' : 'false'
            } else if (actMo == prevMo) {
                isHigh = 'same'
            } else {
                isHigh = item.kpi == 'HIB' ? 'true' : 'false'
            }

            return isHigh
        }
        const handleColorAch = (item) => {
            let actMR = 0
            let actMB = 0
            let isHigh = false
            let trendsAct = [...item.trends.act]
            let trendsMB = [...item.trends.mbv]
            let trendsActLength = trendsAct.length
            let trendsMBLength = trendsMB.length
            actMR = trendsAct[trendsActLength-1]
            actMB = trendsMB[trendsMBLength-1]
            let percentage = String(item.achievement).includes('%')? Number(String(item.achievement).substr(0,String(item.achievement).length -1)) : Number(item.achievement)

            if (percentage < 100) {
                isHigh = false
            }  else {
                isHigh = true
            }
            
            return isHigh
        }
        return (
            <div style={{ padding: 20, width: this.props.width }}>
                <Paper style={{ borderRadius: 10, boxShadow: '0 0 4px 0 rgba(0, 0, 0, 0.5)', padding: 20 }}>
                    <div>
                        <Button aria-controls="simple-menu" aria-haspopup="true" onClick={(e) => this.setState({ openMenu: e.currentTarget })}>
                            Filter
                        </Button>
                        <Menu
                            id="simple-menu"
                            anchorEl={this.state.openMenu}
                            keepMounted
                            open={Boolean(this.state.openMenu)}
                            onClose={() => this.setState({ openMenu: false })}
                        >
                            <div style={{ padding: 20 }}>
                                <div style={{ display: 'flex', borderBottom: 'solid 3px #979696' }}>
                                    <FormControlLabel
                                        control={
                                            <Checkbox
                                                checked={this.state.checkAll}
                                                onChange={() => {
                                                    this.setState({
                                                        checkAll: true,
                                                        checkYTD: true,
                                                        checkAB: true,
                                                        checkYoy: true,
                                                        loading: true,
                                                    }, () => {
                                                        setTimeout(() => {
                                                            this.setState({ loading: false })
                                                        }, 500);
                                                    })
                                                }}
                                                name="checkedB"
                                                color="primary"
                                            />
                                        }
                                        style={{ marginRight: 20 }}
                                        label={"Pilih Semua"}
                                    />
                                    <FormControlLabel
                                        control={
                                            <Checkbox
                                                checked={!this.state.checkAll && !this.state.checkYoy && !this.state.checkAB && !this.state.checkYTD}
                                                onChange={() => {
                                                    this.setState({
                                                        checkAll: false,
                                                        checkYTD: false,
                                                        checkAB: false,
                                                        checkYoy: false
                                                    })
                                                }}
                                                name="checkedB"
                                                color="primary"
                                            />
                                        }
                                        label={"Hapus Semua"}
                                    />
                                </div>
                                <div style={{ display: 'grid' }}>
                                    <FormControlLabel
                                        control={
                                            <Checkbox
                                                checked={this.state.checkYTD}
                                                onChange={() => {
                                                    this.setState({
                                                        checkYTD: !this.state.checkYTD,
                                                        loading: true
                                                    }, () => {
                                                        this.setState({ checkAll: this.state.checkYoy && this.state.checkAB && this.state.checkYTD }, () => {
                                                            setTimeout(() => {
                                                                this.setState({ loading: false })
                                                            }, 500);
                                                        })
                                                    })
                                                }}
                                                name="checkedB"
                                                color="primary"
                                            />
                                        }
                                        label={"Tren YTD"}
                                    />
                                    <FormControlLabel
                                        control={
                                            <Checkbox
                                                checked={this.state.checkAB}
                                                onChange={() => {
                                                    this.setState({ checkAB: !this.state.checkAB, loading: true }, () => {
                                                        this.setState({ checkAll: this.state.checkYoy && this.state.checkAB && this.state.checkYTD }, () => {
                                                            setTimeout(() => {
                                                                this.setState({ loading: false })
                                                            }, 500);
                                                        })
                                                    })
                                                }}
                                                name="checkedB"
                                                color="primary"
                                            />
                                        }
                                        label={"Actual vs Budget"}
                                    />
                                    <FormControlLabel
                                        control={
                                            <Checkbox
                                                checked={this.state.checkYoy}
                                                onChange={() => {
                                                    this.setState({ checkYoy: !this.state.checkYoy, loading: true }, () => {
                                                        this.setState({ checkAll: this.state.checkYoy && this.state.checkAB && this.state.checkYTD }, () => {
                                                            setTimeout(() => {
                                                                this.setState({ loading: false })
                                                            }, 500);
                                                        })
                                                    })
                                                }}
                                                name="checkedB"
                                                color="primary"
                                            />
                                        }
                                        label={"Yoy"}
                                    />
                                </div>
                            </div>
                        </Menu>
                    </div>
                    <div style={{ height: 56, backgroundColor: '#ffffff', display: 'flex', justifyContent: 'space-between', borderBottom: 'solid 3px #979696 ' }}>
                        <div style={{ display: 'grid', alignContent: 'center', width: '20%' }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>Category</Typography>
                        </div>
                        <div style={{ display: 'grid', alignContent: 'center', width: '20%' }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>KPI</Typography>
                        </div>
                        <div style={{ display: 'grid', alignContent: 'center', width: '25%' }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>Trends</Typography>
                        </div>
                        <div style={{ display: 'grid', alignContent: 'center', width: '10%' }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>Current ({this.props.dataPayload.month.month_value})</Typography>
                        </div>
                        <div style={{ display: 'grid', alignContent: 'center', width: '10%' }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>Achievement</Typography>
                        </div>
                        <div style={{ display: 'grid', alignContent: 'center', width: '5%' }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>vs Prev. Month</Typography>
                        </div>
                    </div>
                    {this.state.dataStrategyNew.map((i) => (
                        i.nodes.map((item, index) => {
                            // let dataYTD = []
                            // let dataAB = []
                            // let dataYoy = []
                            // let option = []
                            // if (this.state.checkYTD === true) {
                            //     option.push({
                            //         color: "steelblue",
                            //         points: dataYTD
                            //     })
                            // }
                            // if (this.state.checkAB === true) {
                            //     option.push({
                            //         color: "#e3e16d",
                            //         points: dataAB
                            //     })
                            // }
                            // if (this.state.checkYoy === true) {
                            //     option.push({
                            //         color: "#f27f77",
                            //         points: dataYoy
                            //     })
                            // }
                            // item.trends.map((val, idx) => {
                            //     dataYTD.push({
                            //         x: idx + 1,
                            //         y: val.nodes_actual_value
                            //     })
                            //     dataAB.push({
                            //         x: idx + 1,
                            //         y: val.nodes_mb_value
                            //     })
                            //     dataYoy.push({
                            //         x: idx + 1,
                            //         y: val.nodes_yoy_value
                            //     })
                            // })
                            return (
                                <div style={{ backgroundColor: '#ffffff', display: 'flex', justifyContent: 'space-between', borderBottom: 'solid 3px #979696', padding: '10px 0px' }}>
                                    <div style={{ width: '20%', display: 'grid', alignContent: 'center' }}>
                                        <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>{index > 0 ? '' : newTitleCase(String(i.category_name).toLocaleLowerCase())}</Typography>
                                    </div>
                                    <div style={{ width: '20%', display: 'grid', alignContent: 'center' }}>
                                        <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>{item.item_name}</Typography>
                                        <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>{item.unit}</Typography>
                                    </div>
                                    <div style={{ width: '25%', display: 'grid', alignContent: 'center' }}>
                                        <div style={{ marginLeft: -50 }}>
                                            {!this.state.loading && (this.state.checkAB || this.state.checkYTD || this.state.checkYoy) && <ReactECharts
                                                // showLoading={this.state.loading2}
                                                // lazyUpdate
                                                style={{ height: 350, width: '100%', marginTop: 20 }}
                                                option={{
                                                    tooltip: {
                                                        trigger: 'axis',
                                                        axisPointer: {
                                                            type: 'cross',
                                                            crossStyle: {
                                                                color: '#999'
                                                            }
                                                        }
                                                    },
                                                    legend: {
                                                        data:
                                                            this.state.checkAll ?
                                                                ['Actual', 'MB', 'Yoy']
                                                                :
                                                                (this.state.checkAB && this.state.checkYTD && !this.state.checkYoy ?
                                                                    ['Actual', 'MB']
                                                                    :
                                                                    (this.state.checkAB && !this.state.checkYTD && this.state.checkYoy ?
                                                                        ['Actual', 'Yoy']
                                                                        :
                                                                        (this.state.checkAB && !this.state.checkYTD && !this.state.checkYoy ?
                                                                            ['Actual']
                                                                            :
                                                                            (!this.state.checkAB && this.state.checkYTD && this.state.checkYoy ?
                                                                                ['MB', 'Yoy']
                                                                                :
                                                                                (!this.state.checkAB && this.state.checkYTD && !this.state.checkYoy ?
                                                                                    ['MB']
                                                                                    :
                                                                                    ['Yoy'])))))
                                                    },
                                                    grid: {
                                                        left: 50,
                                                        bottom: 50
                                                    },
                                                    xAxis: {
                                                        type: 'category',
                                                        data: this.props.selectedMonth
                                                    },
                                                    yAxis: {
                                                        type: 'value',
                                                        min: item.trends.sortMin[0] - 0.5,
                                                        max: item.trends.sortMax[0] + 0.5,
                                                    },
                                                    series:
                                                        this.state.checkAll ?
                                                            [
                                                                {
                                                                    name: 'Actual',
                                                                    data: item.trends.act,
                                                                    type: 'line'
                                                                },
                                                                {
                                                                    name: 'MB',
                                                                    data: item.trends.mbv,
                                                                    type: 'line'
                                                                },
                                                                {
                                                                    name: 'Yoy',
                                                                    data: item.trends.yoy,
                                                                    type: 'line'
                                                                }
                                                            ]
                                                            :
                                                            this.state.checkAB && this.state.checkYTD && !this.state.checkYoy ?
                                                                [
                                                                    {
                                                                        name: 'Actual',
                                                                        data: item.trends.act,
                                                                        type: 'line'
                                                                    },
                                                                    {
                                                                        name: 'MB',
                                                                        data: item.trends.mbv,
                                                                        type: 'line'
                                                                    },
                                                                ]
                                                                :
                                                                this.state.checkAB && !this.state.checkYTD && this.state.checkYoy ?
                                                                    [
                                                                        {
                                                                            name: 'Actual',
                                                                            data: item.trends.act,
                                                                            type: 'line'
                                                                        },
                                                                        {
                                                                            name: 'Yoy',
                                                                            data: item.trends.yoy,
                                                                            type: 'line'
                                                                        }
                                                                    ]
                                                                    :
                                                                    this.state.checkAB && !this.state.checkYTD && !this.state.checkYoy ?
                                                                        [
                                                                            {
                                                                                name: 'Actual',
                                                                                data: item.trends.act,
                                                                                type: 'line'
                                                                            },
                                                                        ]
                                                                        :
                                                                        !this.state.checkAB && this.state.checkYTD && this.state.checkYoy ?
                                                                            [
                                                                                {
                                                                                    name: 'MB',
                                                                                    data: item.trends.mbv,
                                                                                    type: 'line'
                                                                                },
                                                                                {
                                                                                    name: 'Yoy',
                                                                                    data: item.trends.yoy,
                                                                                    type: 'line'
                                                                                }
                                                                            ]
                                                                            :
                                                                            !this.state.checkAB && this.state.checkYTD && !this.state.checkYoy ?
                                                                                [
                                                                                    {
                                                                                        name: 'MB',
                                                                                        data: item.trends.mbv,
                                                                                        type: 'line'
                                                                                    },
                                                                                ]
                                                                                :
                                                                                [
                                                                                    {
                                                                                        name: 'Yoy',
                                                                                        data: item.trends.yoy,
                                                                                        type: 'line'
                                                                                    }
                                                                                ]

                                                }}
                                            />}
                                        </div>

                                    </div>
                                    <div style={{ width: '10%', display: 'grid', alignContent: 'center' }}>
                                        <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}><NumberFormat value={item.current_value} displayType={'text'} thousandSeparator={true} /></Typography>
                                        {/* <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>{item.current_value}</Typography> */}
                                    </div>
                                    <div style={{ width: '10%', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                                        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', backgroundColor: item.achievement == '-' || item.achievement == "" ? 'transparent' : handleColorAch(item) ? 'green' : '#ff0000', height: 70, width: 105, marginRight: 20 }}>
                                            {item.achievement == '-' || item.achievement == "" ?
                                                <Typography style={{ color: '#fff', fontWeight: 'bold', fontSize: 12 }}>-</Typography>
                                                :
                                                <Typography style={{ color: '#fff', fontWeight: 'bold', fontSize: 12 }}><NumberFormat value={this.handleAch(item.achievement)} displayType={'text'} thousandSeparator={true} suffix={'%'} /></Typography>}
                                        </div>
                                    </div>
                                    <div style={{ width: '5%', display: 'grid', alignContent: 'center' }}>
                                        {item.trends.act.length == 0 ?
                                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>-</Typography>
                                            :
                                            (handleIsHigher(item) == 'same' ?
                                                <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>-</Typography>
                                                :
                                                <img src={handleIsHigher(item) == 'true' ? Images.up : Images.down} />
                                            )
                                        }
                                    </div>
                                </div>
                            )
                        })
                    ))}
                    {/* <div style={{ height: 56, backgroundColor: '#ffffff', display: 'flex' }}>
                        <div style={{ width: '100%', borderBottom: 'solid 1px #979696 ', display: 'grid', alignContent: 'center', marginLeft: 20 }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>Category</Typography>
                        </div>
                        <div style={{ width: '75%', borderBottom: 'solid 1px #979696 ', display: 'grid', alignContent: 'center', paddingLeft: 20 }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>KPI</Typography>
                        </div>
                        <div style={{ width: '100%', borderBottom: 'solid 1px #979696 ', display: 'grid', alignContent: 'center', paddingLeft: 20 }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>Trends</Typography>
                        </div>
                        <div style={{ width: '75%', borderBottom: 'solid 1px #979696 ', display: 'grid', alignContent: 'center', paddingLeft: 20 }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>Current</Typography>
                        </div>
                        <div style={{ width: '75%', borderBottom: 'solid 1px #979696 ', marginRight: 20, display: 'grid', alignContent: 'center', paddingLeft: 20 }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>Achievement</Typography>
                        </div>
                    </div>
                    <div style={{ height: 56, backgroundColor: '#ffffff', display: 'flex' }}>
                        <div style={{ width: '100%', borderBottom: 'solid 1px #979696 ', display: 'grid', alignContent: 'center', marginLeft: 20 }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}></Typography>
                        </div>
                        <div style={{ width: '75%', borderBottom: 'solid 1px #979696 ', display: 'grid', alignContent: 'center', paddingLeft: 20 }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>KPI</Typography>
                        </div>
                        <div style={{ width: '100%', borderBottom: 'solid 1px #979696 ', display: 'grid', alignContent: 'center', paddingLeft: 20 }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>Trends</Typography>
                        </div>
                        <div style={{ width: '75%', borderBottom: 'solid 1px #979696 ', display: 'grid', alignContent: 'center', paddingLeft: 20 }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>Current</Typography>
                        </div>
                        <div style={{ width: '75%', borderBottom: 'solid 1px #979696 ', marginRight: 20, display: 'grid', alignContent: 'center', paddingLeft: 20 }}>
                            <Typography style={{ color: '#656565', fontWeight: 'bold', fontSize: 12 }}>Achievement</Typography>
                        </div>
                    </div> */}
                </Paper>
            </div>
        )
    }
}
