import React, { Component } from 'react';
import { Container, Row, Col } from "react-bootstrap";
import { makeStyles, createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles';
import { TextField } from '@material-ui/core';
import MenuItem from '@material-ui/core/MenuItem';
import ReactDragListView from 'react-drag-listview';
import Autocomplete from '@material-ui/lab/Autocomplete';
import api from "../../api";
import { none } from 'ramda';
import Constant from '../../library/Constant';


const type = [
  {
    value: 'KPI',
    label: 'KPI',
  },
  {
    value: 'Gatau',
    label: 'Gatau',
  },
];

export default class VisualisasiAM extends Component {
    constructor(props) {
        super(props)
        const data = [];
        for (let i = 1, len = 7; i < len; i++) {
            data.push({
                title: `rows${i}`
            });
        }
        this.state = {
            visibleAM: false,
            visibleVisual: true,
            data,
            listApproval: [],
            listEdit: [],
            listOriginal: []
        }
    }

    componentDidMount() {
        this.getTypeData()
    }

    getTypeData() {
        api.create().getTypeAM().then((response) => {
            if (response.data) {
                if (response.ok) {
                    if (response.data.status == 'success') {
                        let data = response.data.data
                        // console.log(data)
                        let typeData = data.map((item) => {
                            return {
                                approval_type_id: item.approval_type_id,
                                approval_type_name: item.approval_type_name
                            }
                        })
                        let typeProps = {
                            options: typeData,
                            getOptionLabel: (option) => option.approval_type_name,
                        };
                        this.setState({ types: typeProps, typeData: response.data.data })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            if (response.data.message.includes("Someone Logged In")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    handleInputChange(e) {
        this.setState({ search: e })
        let body = {
            "keyword": this.state.typeName
        }
        api.create().searchAM(body).then(response => {
            if (response.data) {
                if (response.ok) {
                    if (response.data.status == 'success') {
                        let data = response.data.data
                        // console.log(data)
                        let listVisual = []
                        data.map((item, index) => {
                            let indexId = listVisual.findIndex((val) => val.orderId == item.orders)
                            if(indexId == -1){
                                listVisual.push({
                                    orderId: item.orders,
                                    data: [item]
                                })
                                // console.log(listVisual);
                            } else {
                                listVisual[indexId].data.push(item)
                                // console.log('listVisual');
                                // console.log(listVisual);
                            }
                        })
                        this.setState({ listApproval: listVisual})
                        // console.log(listVisual);
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            if (response.data.message.includes("Someone Logged In")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    handleChangeOrder(fromIndex, toIndex, that) {
        let listApproval = that.state.listApproval
        let orderIdFrom = listApproval[fromIndex].orderId
        listApproval[fromIndex].orderId = listApproval[toIndex].orderId
        listApproval[toIndex].orderId = orderIdFrom
        that.setState({listEdit: listApproval}, () => console.log(this.state.listEdit))
    }

    handleSave() {
        let data = []
        if (this.state.listEdit.length == 0) {
            this.state.listApproval.map((item,index) => {
                item.data.map((items,index) => {
                    data.push({
                        approval_matrix_id: items.approval_matrix_id,
                        approval_type_id: items.approval_type_id,
                        operator_type_id: items.operator_type_id,
                        orders: item.orderId,
                        user_id: items.user_id
                    })
                })
            })
        } else {
            this.state.listEdit.map((item,index) => {
                item.data.map((items,index) => {
                    data.push({
                        approval_matrix_id: items.approval_matrix_id,
                        approval_type_id: items.approval_type_id,
                        operator_type_id: items.operator_type_id,
                        orders: item.orderId,
                        user_id: items.user_id
                    })
                })
            })
        }
        setTimeout(() => {
            let payload = {
                approval_type_id: data[0].approval_type_id,
                approval_matrix_detail : data
            }
            this.setState({listOriginal: payload})
            this.props.updateVAM(this.state.listOriginal)
        }, 500);
    }

    render() {
        const that = this;
        const dragProps = {
            onDragEnd(fromIndex, toIndex) {
                const data = [...that.state.listApproval];
                const item = data.splice(fromIndex, 1)[0];
                if (fromIndex !== -1 && toIndex !== -1) { 
                    that.handleChangeOrder(fromIndex, toIndex, that)
                    data.splice(toIndex, 0, item);
                    that.setState({ listApproval: data });
                }
            },
            nodeSelector: 'li',
            handleSelector: 'a'
        };
        return (
            <div>    
                <div style={{ height: this.props.height }}>
                    <div class="main-color" style={{ height: 199, width: '100%' }} />
                        <div>
                            <div style={{ display: 'flex', paddingRight: 25, paddingLeft: 25, marginTop: -150 }}>
                                <label style={{ color: 'white', width: '20%', fontSize: 16, paddingTop: 8 }}>Visualization</label>
                            </div>
                            <div style={{ display: 'flex', paddingRight: 25, paddingLeft: 25 }}>
                                <label style={{ color: '#51c6ea', width: '20%', fontSize: 11 }}>Master Data / Approval Matrix / 
                                    <span style={{ color: 'white', width: '20%', fontSize: 11 }}> Visualization</span> 
                                </label>
                            </div>
                            <div style={{ padding: 25, width: '100%' }}>
                                <div style={{ width: '100%', padding: 25, backgroundColor: 'white', borderRadius: 6, border: 'solid 1px #c4c4c4'}}>
                                    <label style={{ color: '#4b4b4b', fontSize: '16px', fontWeight: 'bold' }}>Approval Hierarchy</label>
                                    <div className="" style={{ width: 250, marginTop: 8, marginBottom: 28 }}>
                                        <Autocomplete
                                            {...this.state.types}
                                            id="tipe"
                                            onChange={(event, newInputValue) => this.setState({typeName:newInputValue.approval_type_name}, () => {
                                                this.handleInputChange()
                                            })}
                                            disableClearable
                                            renderInput={(params) => <TextField {...params} label="Approval Type" margin="normal" />}
                                        />
                                    </div>
                                    <ReactDragListView {...dragProps}>
                                        <ol style={{paddingLeft: 15}}>
                                        {this.state.listApproval.sort((a,b) => a.orderId - b.orderId).map((item, index) => (
                                            <li key={index} style={{color: 'white', fontSize: 14}}>
                                                <a href='#' style={{ color: '#4b4b4b', fontSize: '14px', cursor: 'auto', outline: 'none', justifyContent: 'flex-start', display: 'flex'}}>
                                                    <label style={{color: '#4b4b4b', marginRight: 15}}>{Number(index+1)}</label>
                                                    <div className="grid grid-4x grid-mobile-none gap-20px margin-bottom-20px" style={{width: '75%'}}>
                                                        {item.data.map((items, indexs) => {return(<label>{items.fullname}</label>)})}
                                                        <label>{item.data.length == 1? '' : item.data[0].operator_type_name}</label>
                                                    </div>
                                                </a>
                                            </li>
                                        ))}
                                        </ol>
                                    </ReactDragListView>
                                </div>
                            </div>
                            <div className="row" style={{ float: 'right', display: 'flex', flexDirection: 'row', justifyContent: 'space-between', paddingRight: 15, paddingLeft: 15, paddingBottom: 25 }}>
                                {/* <div onClick={() => this.props.onClickClose()} style={{ width: 102, height: 30, marginLeft: 25, backgroundColor: 'dodgerblue', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center', cursor:"pointer" }}>
                                    <span style={{ color: '#fff', fontSize: 11 }}>Back</span>
                                </div> */}
                                <div className="row" style={{ float: 'right', marginRight: 25 }}>
                                    <div onClick={() => this.props.onClickClose()} style={{ width: 102, height: 30, border: 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center', cursor:"pointer" }}>
                                        <span style={{ color: '#354960', fontSize: 11 }} >Cancel</span>
                                    </div>
                                    {this.props.btnedit && (
                                    <div onClick={() => this.handleSave()} style={{ width: 102, height: 30, marginLeft: 25, backgroundColor: '#354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center', cursor:"pointer" }}>
                                        <span style={{ color: '#fff', fontSize: 11 }}>Save</span>
                                    </div>
                                    )}
                                </div>
                            </div>
                        </div>
                </div>
            </div>
            
        );
    }
}
