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';


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.status == 'success') {
                let data = response.data.data
                let typeData = data.map((item) => {
                    return {
                        approval_type_id: item.approval_type_id,
                        approval_type_name: item.approval_type_name
                    }
                })
                // console.log(userData)
                let typeProps = {
                    options: typeData,
                    getOptionLabel: (option) => option.approval_type_name,
                  };
                this.setState({ types: typeProps, typeData: response.data.data })
            } else {
                alert(response.data.message)
            }
        })
    }

    handleInputChange(e) {
        this.setState({ search: e })
        let body = {
            "keyword": this.state.typeName
        }
        api.create().searchAM(body).then(response => {
            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)
                    }
                })
                this.setState({ listApproval: listVisual})
                console.log(listVisual);
            } else {
                alert(response.data.message)
            }
        })
    }

    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})
    }

    handleSave() {
        let data = []
        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,
                    approval_type_name: items.approval_type_name,
                    created: items.created,
                    end_date: items.end_date,
                    fullname: items.fullname,
                    operator_type_id: items.operator_type_id,
                    operator_type_name: items.operator_type_name,
                    orders: item.orderId,
                    start_date: items.start_date,
                    status: items.status,
                    updated: items.updated,
                    user_id: items.user_id
                })
            })
        })

        setTimeout(() => {
            this.setState({listOriginal: data})
        }, 500);
    }

    render() {
        const that = this;
        const dragProps = {
            onDragEnd(fromIndex, toIndex) {
                const data = [...that.state.listApproval];
                const item = data.splice(fromIndex, 1)[0];
                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 }}>Visualisasi</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 }}> Visualisasi</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' }}>Hirarki Persetujuan</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="Tipe Persetujuan" margin="normal" />}
                                        />
                                    </div>
                                    <ReactDragListView {...dragProps}>
                                        <ol style={{paddingLeft: 15}}>
                                        {this.state.listApproval.map((item, index) => (
                                            <li key={index} style={{color: '#4b4b4b', fontSize: 14}}>
                                                <a href='#' style={{ color: '#4b4b4b', fontSize: '14px', cursor: 'auto', outline: 'none' }}>
                                                    <div className="grid grid-3x 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={{ 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 }}>Kembali</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 }} >Batal</span>
                                    </div>
                                    <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 }}>Simpan</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                </div>
            </div>
            
        );
    }
}