import React, { Component } from 'react'
import MUIDataTable from 'mui-datatables'
import {  withStyles } from '@material-ui/core/styles';
import { createMuiTheme, MuiThemeProvider, Snackbar } from '@material-ui/core';
import MuiAlert from '@material-ui/lab/Alert';
import Constant from '../../library/Constant';
import api from '../../api';
import Images from '../../assets/Images';
import ReactTooltip from 'react-tooltip';
import PopUpDelete from "./PopUpDelete";
import CreateManagementDoc from './CreateManagementDoc';
import EditManagementDoc from './EditManagementDoc';


var ct = require("../../library/CustomTable");
const getMuiTheme = () => createMuiTheme(ct.customTable());
const options = ct.customOptionsManagementDocument();

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

export default class BOD extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataTable: [],
            visibleCreate: false,
            visibleEdit: false,
            refresh: '',
            alert: false,
            popupDel: false,
        }
    }

    componentDidMount() {
        // console.log(this.props.data)
        this.getData()
    }

    componentWillReceiveProps(props) {
        // console.log(props);
        const { refresh, id } = this.props;
        if (props.refresh !== refresh) {
            this.getData()
        }
      }

    getData() {
        let payload = {
            "setting_id": this.props.data.setting_id
        }

        api.create().getAllDocument(payload).then((response) => {
            console.log(response)
            if (response.problem){
                alert(response.problem)
            } 
            if (response.data) {
                if (response.ok) {
                    if (response.data.status == 'success') {
                        let dataTable = response.data.data.map((item, index) => {
                            return [
                                index,
                                item.document_name,
                                item.description,
                                item.company_name,
                                item.document_periode,
                                item.document_type,
                                String(Number(item.document_size) / 1000 + ' KB'),
                                item.created_by,
                                item.created_at,
                            ]
                        })
                        this.setState({ dataTable })
                        let docPath = response.data.data.map((item) => {
                            return [
                                item.document_filepath
                            ]
                        })
                        this.setState({ docPath })
                        let docId = response.data.data.map((item) => {
                            return [
                                item.document_id
                            ]
                        })
                        this.setState({ docId })
                    } 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 })
            }
        })
    }

    openPopUp = async (index, val, type) =>{
        if (type === 'download') {
            console.log(this.state.docPath[val])
            let res = await fetch(
                "https://tia.eksad.com/tia-reporting-dev/public/document/download_document?documentName="+this.state.docPath[val]+"&&fileType="+index[5]
            )
            res = await res.blob()
            // console.log(res)
            if (res.size > 0) {
                let url = window.URL.createObjectURL(res);
                let a = document.createElement('a');
                a.href = url;
                a.download = index[1];
                a.click();
            }
        }
        if (type === 'delete') {
            this.setState({
                id: this.state.docId[val],
                rowData: index,
                popupDel: true
            })
        }
        if (type === 'edit') {
            this.setState({
                id: this.state.docId[val],
                rowData: index,
                visibleEdit: true
            })
        }
    }

    updateDocument(payload) {
        api.create().updateDocument(payload).then(response => {
            console.log(response)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === "success") {
                        this.getData()
                        this.setState({ konfirmasi: false, alert: true, messageAlert: response.data.message, tipeAlert: 'success', visibleEdit: false })
                    } 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' })
            }
        })
    }

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

    deleteDoc = (payload) => {
        this.setState({ popupDel: false })
        api.create().deleteDocument(payload).then(response => {
            console.log(response.data)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status == 'success') {
                        this.getData()
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'success' })
                    } 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' })
            }
        })
    }

    render() {
        let columns = [
            {
                name: "Action",
                options: {
                    filter: false,
                    sort: false,
                    customBodyRender: (val, tableMeta) => {
                        console.log(tableMeta)
                        return (
                            <div style={{ display: 'flex' }}>
                                {/* {this.state.btnedit && <span> */}
                                    <a data-tip={'Download'} data-for="download">
                                    <button
                                        style={{
                                            backgroundColor: 'transparent',
                                            cursor: 'pointer',
                                            borderColor: 'transparent',
                                            marginRight: 15
                                        }}
                                        // onClick={() => console.log(tableMeta)}
                                        onClick={() => this.openPopUp(tableMeta.rowData, val, 'download')}
                                        >
                                            <img src={Images.download} />
                                        </button>
                                    </a>
                                    <ReactTooltip border={true} id="download" place="bottom" type="light" effect="solid" />
                                {/* </span>} */}
                                {this.props.btnedit && <span>
                                    <a data-tip={'Edit'} data-for="edit">
                                    <button
                                        style={{
                                            backgroundColor: 'transparent',
                                            cursor: 'pointer',
                                            borderColor: 'transparent',
                                            marginRight: 15
                                        }}
                                        // onClick={() => console.log(tableMeta)}
                                        onClick={() => this.openPopUp(tableMeta.rowData, val, 'edit')}
                                        >
                                            <img src={Images.editCopy} />
                                        </button>
                                    </a>
                                    <ReactTooltip border={true} id="edit" place="bottom" type="light" effect="solid" />
                                </span>}
                                {this.props.btndelete && <span>
                                    <a data-tip={'Delete'} data-for="delete">
                                    <button
                                        style={{
                                            backgroundColor: 'transparent',
                                            cursor: 'pointer',
                                            borderColor: 'transparent',
                                        }}
                                        // onClick={() => console.log(tableMeta)}
                                        onClick={() => this.openPopUp(tableMeta.rowData, val, 'delete')}
                                        >
                                            <img src={Images.delete} />
                                        </button>
                                    </a>
                                    <ReactTooltip border={true} id="delete" place="bottom" type="light" effect="solid" />
                                </span>}
                            </div >
                        );
                    }
                }
            }, "File Name", "Description", "Company Name", "Period", "Type", "File Size", "Created By", "Created Date"
        ]
        return (
            <div style={{ width: '100%' }}>
                <div style={{ padding: 25 }}>
                    <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
                        <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
                            {this.state.messageAlert}
                        </Alert>
                    </Snackbar>
                    <MuiThemeProvider theme={getMuiTheme()}>
                        <MUIDataTable
                            theme={getMuiTheme()}
                            data={this.state.dataTable}
                            columns={columns}
                            options={options}
                        />
                    </MuiThemeProvider>
                </div>
                {this.state.popupDel && (
                    <PopUpDelete
                        type={"delete"}
                        onClickClose={() => this.setState({ popupDel: false })}
                        data={this.state.rowData}
                        idoc={this.state.id}
                        // getList={() => this.getData.bind(this)}
                        deleteDoc={this.deleteDoc.bind(this)}
                    />
                )}
                {this.state.visibleEdit && (
                    <EditManagementDoc
                        type={"edit"}
                        onClickClose={() => this.setState({ visibleEdit: false })}
                        data={this.state.rowData}
                        idoc={this.state.id}
                        updateDocument={this.updateDocument.bind(this)}
                    />
                )}
            </div>
        )
    }
}
