import React, { Component } from 'react'
import { Tabs, Tab, Typography, Paper, withStyles, Snackbar } from '@material-ui/core'
import ReactTooltip from 'react-tooltip'
import Images from '../../assets/Images'
import ManualBookTia from './ManualBookTia'
import api from '../../api'
import AuditTahunan from './AuditTahunan'
import CreateManagementDoc from './CreateManagementDoc'
import AllDocument from './AllDocument'
import QReview from './QReview'
import BOD from './BOD'
import ManualBookETMS from './ManualBookETMS'
import PopUpKonfirmasi from "./PopUpKonfirmasi";
import Constant from '../../library/Constant'
import MuiAlert from '@material-ui/lab/Alert';
import PropagateLoader from "react-spinners/PropagateLoader"

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

export default class DocumentManagement extends Component {
    constructor(props) {
        super(props)
        this.state = {
            tab: 0,
            listData: [],
            id: 0,
            btncreate: false,
            btnedit: false,
            btndelete: false,
            load: false,
            name: '',
            userCompActive: []
        }
    }

    getPermission() {
        let payload = {
            menu: "document management"
        }
        api.create().getPermission(payload).then(response => {
            // console.log(response)
            if (response.data) {
                if (response.data.status === "success") {
                    this.setState({
                        btncreate: response.data.data.create,
                        btnedit: response.data.data.edit,
                        btndelete: response.data.data.delete,
                        load: true
                    })
                } else {
                    this.setState({
                        load: true
                    })
                }
            } else {
                this.setState({ load: true })
            }
        })
    }

    selectTab = (event, newEvent) => {
        this.setState({ tab: newEvent })
        // console.log(this.state.tab)
    }

    componentDidMount() {
        this.getDataDocument()
        this.getPermission()
        this.getDetailUser()
    }

    getDataDocument(id, name) {
        api.create().getDocumentCategory().then(response => {
            console.log(response);
            if (response) {
                if (response.data.status === "success") {
                    this.setState({
                        listData: response.data.data,
                        id: id === undefined ? response.data.data[0].setting_id : id,
                        name: name === undefined ? response.data.data[0].value : name,
                        loadTable: true,
                        refresh: id === undefined ? '' : 'create'
                    })
                    // console.log(this.state.listData)
                } else {

                }
            } else {

            }
        })
    }

    createDocument(payload, settingID, menuName) {
        this.setState({ loading: true })
        api.create().uploadDocument(payload).then(response => {
            console.log(response)
            if (response.data) {
                if (response.ok) {
                    if (response.data.message === "The Document Already Exists in The System, Do You Want to Overwrite It?") {
                        this.setState({ konfirmasi: true, formData: payload, docId: response.data.data.document_id, settingID, menuName, loading: false })
                    }
                    else if (response.data.message === "Data was Saved Successfully") {
                        this.getDataDocument(settingID, menuName)
                        this.setState({ visibleCreate: false,  loading: false, alert: true, messageAlert: response.data.message, tipeAlert: 'success', settingID, menuName})
                    }
                    else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                            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', loading: false })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
            }
        })
    }

    createUploadDocument() {
        this.setState({ visibleCreate: false, konfirmasi: false })
        const formData = this.state.formData
        formData.append("documentId", this.state.docId)
        formData.append("updated", 1)
        this.setState({ loading: true })
        api.create().updateDocument(formData).then(response => {
            console.log(response)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === "success") {
                        this.getDataDocument(this.state.settingID, this.state.menuName)
                        this.setState({ konfirmasi: false, alert: true, messageAlert: response.data.message, tipeAlert: 'success', visibleCreate: false, loading: false })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                            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', loading: false })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
            }
        })
    }

    getID(id) {
        console.log(id);
        this.setState({ id })
    }

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

    handleLoading(tipe) {
        this.setState({ loading: tipe == 0 ? false : 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()
                        })
                    }
                }
            }
        })
    }

    getCompanyActive() {
        api.create().getPerusahaanActive().then((response) => {
            if (response.data) {
                if (response.data.status === 'success') {
                    let data = response.data.data
                    let compActive = []
                    let userCompActive = []
                    this.state.userCompany.map((item, index) => {
                        let indeks = data.findIndex((val) => val.company_id == item)
                        if (indeks !== -1 && String(data[indeks].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)
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', visibleTrue: true }, () => {
                        if (response.data.message.includes("Someone Logged In")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', listCompany: null, company: null, visibleTrue: 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' }}>
                {/* {this.props.load && ()} */}
                <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' }}>Document Management</Typography>
                </div>
                <div style={{ padding: 20 }}>
                {this.state.loading && loadingComponent}
                    <Paper style={{ padding: 20 }}>
                        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                        {(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' }}>
                            <Tabs
                                orientation="vertical"
                                variant="scrollable"
                                value={this.state.tab}
                                onChange={this.selectTab}
                                aria-label="simple tabs example"
                                style={{ width: 350 }}
                            >
                                {this.state.listData.map((item, index) => {
                                    return (
                                        <Tab
                                            onClick={() => this.setState({ name: item.value, id: item.setting_id, refresh: '', loadTable : false }, () => this.setState({loadTable: true}))}
                                            label={item.value}
                                        />
                                    )
                                })}
                            </Tabs>
                            {this.state.loadTable && this.state.visibleTrue && (
                                <AllDocument
                                    data={this.state.listData[this.state.tab]}
                                    refresh={this.state.refresh}
                                    btnedit={this.state.btnedit}
                                    btndelete={this.state.btndelete}
                                    load={this.state.load}
                                    setId={this.state.id}
                                    userCompActive={this.state.userCompActive}
                                    allsubcoEdit={this.state.btnadd}
                                    handleLoading={this.handleLoading.bind(this)}
                                    name={this.state.name}
                                />
                                // this.state.id === 68542 ?
                                //     <AuditTahunan
                                //         data={this.state.listData[this.state.tab]}
                                //         refresh={this.state.refresh}
                                //         btnedit={this.state.btnedit}
                                //         btndelete={this.state.btndelete}
                                //         load={this.state.load}
                                //     />
                                //     :
                                //     this.state.id === 68541 ?
                                //         <ManualBookTia
                                //             data={this.state.listData[this.state.tab]}
                                //             refresh={this.state.refresh}
                                //             btnedit={this.state.btnedit}
                                //             btndelete={this.state.btndelete}
                                //             load={this.state.load}
                                //         />
                                //         :
                                //         this.state.id === 68544 ?
                                //             <QReview
                                //                 data={this.state.listData[this.state.tab]}
                                //                 refresh={this.state.refresh}
                                //                 btnedit={this.state.btnedit}
                                //                 btndelete={this.state.btndelete}
                                //                 load={this.state.load}
                                //             />
                                //             :
                                //             this.state.id === 68543 ?
                                //                 <BOD
                                //                     data={this.state.listData[this.state.tab]}
                                //                     refresh={this.state.refresh}
                                //                     btnedit={this.state.btnedit}
                                //                     btndelete={this.state.btndelete}
                                //                     load={this.state.load}
                                //                 />
                                //                 // :
                                //                 // this.state.id === 68545 ?
                                //                 //     <ManualBookETMS
                                //                 //         data={this.state.listData[this.state.tab]}
                                //                 //         refresh={this.state.refresh}
                                //                 //     />
                                //                     :
                                //                     <span>Coming Soon</span>

                            )}
                        </div>

                    </Paper>
                </div>
                {this.state.konfirmasi && (
                    <PopUpKonfirmasi
                        onClickClosePopUp={() => this.setState({ konfirmasi: false })}
                        uploadDocId={this.createUploadDocument.bind(this)}
                    />
                )}
                {this.state.visibleCreate && (
                    <CreateManagementDoc
                        onClickClose={() => this.setState({ visibleCreate: false })}
                        // getDataDocument={this.getDataDocument.bind(this)}
                        createDocument={this.createDocument.bind(this)}
                        setting_id={this.state.id}
                        name={this.state.name}
                        handleLoading={this.handleLoading.bind(this)}
                        allsubcoCreate={this.state.btnadd}
                    />
                )}
            </div>
        )
    }
}
