import React, { Component } from 'react'
import { withStyles } from '@material-ui/core/styles';
import { Paper, Snackbar, Typography } from '@material-ui/core';
import MuiAlert from '@material-ui/lab/Alert';
import Constant from '../../library/Constant';
import Images from '../../assets/Images';
import ReactTooltip from 'react-tooltip';
import api from '../../api';
import PropagateLoader from "react-spinners/PropagateLoader"
import TableDocument from "./TableCafrmDocument";
import CreateCafrmDoc from "./CreateCafrmDocument";

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

export default class CafrmDocument extends Component {

    constructor(props) {
        super(props);
        this.state = {
            alert: false,
            listData: [],
            id: 0,
            load: false,
            name: '',
            userCompActive: [],
            submenu_id : 0,
            submenu_name: "",
            menu_title: "",
            loading: false
        }
    }

    componentDidMount() {
        this.getMenuName();
    }

    getMenuName(){
        api.create().getMenuByUser().then(
            response => {
                if(response.data){
                    if(response.data.status === 'success'){
                        response.data.data.map(
                            (item) => {
                                let arr = window.location.href.split('/');
                                if (item.class_id == arr.slice(-1)[0]){
                                    this.setState({
                                        submenu_id : item.menu_id,
                                        submenu_name : item.menu_name.toLowerCase(),
                                        menu_title : item.menu_name.replace(/\b\w/g, c => c.toUpperCase())
                                    }, () => {
                                        this.getPermission(this.state.submenu_name)
                                        // this.getDataCarfm();
                                        this.getDetailUser();
                                    })
                                }
                            }
                        )
                    }
                }
            }
        )
    }

    // getDataCarfm(create){
    //     let payload = {
    //         submenu_id : this.state.submenu_id
    //     }
    //     api.create().getCarfmDocumentBySubmenu(payload).then(
    //         response => {
    //             if(response){
    //                 if(response.data.status === 'success'){
    //                     let dataList = []
    //                     response.data.data.map((item, index) => {
    //                         dataList.push(item)
    //                     })

    //                     this.setState({
    //                         listData: dataList,
    //                         refresh: create == undefined ? '' : create,
    //                         loading: false
    //                     })
    //                 } else {
    //                     this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
    //                         if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
    //                             setTimeout(() => {
    //                                 localStorage.removeItem(Constant.TOKEN)
    //                                 window.location.reload();
    //                             }, 1000);
    //                         }
    //                     })
    //                 }
    //             }else {
    //                 this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
    //             }
    //         }
    //     )
    // }

    getPermission(subMenu) {
        let payload = {
            menu: subMenu
        }
        api.create().getPermission(payload).then(response => {
            if (response.data) {
                console.log(`status get permission ${response.data.status}`);
                if (response.data.status === "success") {
                    this.setState({
                        btncreate: response.data.data.create,
                        btnview: response.data.data.view,
                        btndownload: response.data.data.download,
                        load: true,
                    })
                    console.log("btn create " + this.state.btncreate);
                } else {
                    this.setState({
                        load: true
                    })
                }
            } else {
                this.setState({ load: true })
            }
        })
    }

    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, visibleTrue: false }, () => {
                            this.getCompanyActive()
                            console.log(this.state.userCompany);
                        })
                    }
                }
            }
        })
    }

    getCompanyActive() {
        api.create().getPerusahaanActive().then((response) => {
            console.log("getcompanyactive start");
            console.log(response.data.data);
            console.log("getcompanyactive stop");
            if (response.data) {
                if (response.data.status === 'success') {
                    let data = response.data.data
                    let compActive = []
                    let userCompActive = []
                    this.state.userCompany.map((item, index) => {
                        if (index !== -1 && String(data[index].status).toLocaleLowerCase() == 'active'){
                            userCompActive.push(item)
                        }
                    })
                    data.map(( item, index ) => {
                        if (String(item.status).toLocaleLowerCase() == 'active') {
                            compActive.push(item)
                        }
                    })
                    if (compActive.length == userCompActive.length){
                        this.setState({ btnadd: true})
                    } else {
                        this.setState({ btnadd: false})
                    }
                    this.setState({ userCompActive, visibleTrue: true })
                    console.log("usercompactive")
                     console.log(userCompActive)
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', visibleTrue: true }, () => {
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                console.log("error di getcompany active")
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', listCompany: null, company: null, visibleTrue: true })
            }
        })
    }

    createDocument(payload) { //upload apinya disini
        this.setState({ loading: true, visibleTrue: false })
        api.create().uploadCarfmDocument(payload).then(response => {
            // console.log(response)
            if (response.data) {
                if (response.ok) {
                    if (response.data.message === "Data was Saved Successfully") {
                        this.setState({ visibleCreate: false, visibleTrue: true, loading: false, alert: true, messageAlert: response.data.message, tipeAlert: 'success'}, () => {
                            // window.location.reload();
                        })
                        // this.getDataCarfm('create')
                    }
                    else {
                        this.setState({ visibleCreate: false, visibleTrue: true, alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                            if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    this.setState({ visibleCreate: false, visibleTrue: true, alert: true, messageAlert: response.data.message, tipeAlert: 'error', loading: false })
                }
            } else {
                this.setState({ visibleCreate: false, visibleTrue: true, alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
            }
        })
    }


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

    handleLoading(tipe) {
        this.setState({loading: tipe == 0 ? false : true})
    }

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

        return (
            <div style={{height: this.props.height, backgroundColor: '#f8f8f8'}}>
                <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
                    <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
                        {this.state.messageAlert}
                    </Alert>
                </Snackbar>

                <div className={"main-color"} style={{ height: 78, display: 'flex', alignItems: 'center', paddingLeft: 20 }}>
                    <Typography style={{ fontSize: '16px', color: 'white' }}>{this.state.menu_title}</Typography>
                </div>

                <div style={{padding: 20}}>
                    {this.state.loading && loadingComponent}
                    {this.state.btnview && (
                        <Paper style={{padding: 20}}>
                            <div style={{display: 'flex', justifyContent: 'flex-end'}}>
                                {/* {console.log("renderbtn" +  this.state.btncreate)} */}
                                {(this.state.btncreate) && (
                                    <span>
                                        <a data-tip={'Add'} data-for="add">
                                            <div style={{display: 'grid', justifyContent: 'flex-end'}}>
                                                <button
                                                    type="button"
                                                    onClick={() => this.setState({visibleCreate: true, refresh: ''})}
                                                    style={{marginRight: 25, background: 'transparent'}}
                                                >
                                                    <img src={Images.add}/>
                                                </button>
                                            </div>
                                        </a>
                                        <ReactTooltip border={true} id="add" place="bottom" type="light" effect="solid"/>
                                    </span>
                                )}
                            </div>

                            <div style={{display: 'flex'}}>
                                {this.state.visibleTrue && (
                                <TableDocument
                                    data={this.state.listData}
                                    refresh={this.state.refresh}
                                    load={this.state.load}
                                    userCompActive={this.state.userCompActive}
                                    handleLoading={this.handleLoading.bind(this)}
                                    name={this.state.name}
                                    submenu_id={this.state.submenu_id}
                                    btndownload = {this.state.btndownload}
                                />)}

                            </div>
                        </Paper>
                    )}
                </div>

                {this.state.visibleCreate && (
                    <CreateCafrmDoc
                        onClickClose={() => this.setState({ visibleCreate: false })}
                        // getDataDocument={this.getDataDocument.bind(this)}
                        createDocument={this.createDocument.bind(this)}
                        handleLoading={this.handleLoading.bind(this)}
                        submenu_id={this.state.submenu_id}
                        menuName={this.state.menu_title}
                    />
                )}

            </div>
        );
    }
}