import React, { Component } from 'react';
import { Container, Row, Col } from "react-bootstrap";
import { makeStyles, createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles';
import { Typography } from '@material-ui/core';
import Images from '../../../assets/Images';
import UploadFile from "../../../library/Upload";
import MUIDataTable from "mui-datatables";
import { render } from '@testing-library/react';
import { TextField, InputBase } from "@material-ui/core";
import { ExcelRenderer } from 'react-excel-renderer';
import CreatePerusahaan from "./CreatePerusahaan";
import EditPerusahaan from "./EditPerusahaan"
import VisualPerusahaan from "./VisualPerusahaan";
import api from "../../../api";
import ReactTooltip from 'react-tooltip';
import PopUpFailedSave from '../../../library/PopUpFailedSave';

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

export default class Perusahaan extends Component {
    constructor(props) {
        super(props)
        this.state = {
            visibleCreate: false,
            visibleEdit: false,
            visibleVisual: false,
            dataTable: [],
            listData: [],
            data: [],
            search: "",
            visiblePerusahaan: true,
            cols: null,
            rows: null,
            dataLoaded: false,
            popupError: false
        }
        this.fileHandler = this.fileHandler.bind(this);
    }

    fileHandler = (event) => {
        let fileObj = event
        ExcelRenderer(fileObj, (err, resp) => {
            if (err) {
                console.log(err);
            }
            else {
                let judul = resp.rows[2]
                let isi = resp.rows.slice(3)
                let payload = []
                isi.map((item, index) => {
                    if (item.length > 0) {
                        payload.push({
                            "id": index + 1,
                            "company_name": item[0],
                            "company_parent": item[1],
                            "unit_bisnis": item[2],
                            "startDate": item[3],
                            "endDate": item[4],
                        })
                    }
                })
                let body = {
                    company: payload
                }
                this.setState({ payload: body, buttonError: false })
                api.create().checkUploadPerusahaan(body).then(response => {
                    console.log(response);
                    if (response.data.status === "success") {
                        let dataRow = response.data.data.map((item, index) => {
                            return [
                                index + 1,
                                item.company_name,
                                item.company_parent,
                                item.unit_bisnis,
                                item.start_date,
                                item.end_date,
                                item.error
                            ]
                        })
                        let columns = [
                            "Data Ke-",
                            {
                                name: "Nama Perusahaan",
                                options: {
                                    customBodyRender: (val, tableMeta) => {
                                        let check = null
                                        if (tableMeta.rowData[6] != null) {
                                            check = tableMeta.rowData[6].findIndex((val) => val.field.includes('company_name'))
                                            if (check > -1) {
                                                this.setState({ buttonError: true })
                                            }
                                        }
                                        return (
                                            <div style={{ display: 'flex' }}>
                                                {tableMeta.rowData[6] != null && check > -1 ?
                                                    <a data-tip={tableMeta.rowData[6][check].message} data-for="company_name">
                                                        <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                                                    </a> :
                                                    <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                                                }
                                                <ReactTooltip border={true} id="company_name" place="bottom" type="light" effect="solid" />
                                            </div >
                                        );
                                    }
                                }
                            },
                            {
                                name: "Parent Company",
                                options: {
                                    customBodyRender: (val, tableMeta) => {
                                        let check = null
                                        if (tableMeta.rowData[6] != null) {
                                            check = tableMeta.rowData[6].findIndex((val) => val.field.includes('company_parent'))
                                            if (check > -1) {
                                                this.setState({ buttonError: true })
                                            }
                                        }
                                        return (
                                            <div style={{ display: 'flex' }}>
                                                {tableMeta.rowData[6] != null && check > -1 ?
                                                    <a data-tip={tableMeta.rowData[6][check].message} data-for="company_parent">
                                                        <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                                                    </a> :
                                                    <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                                                }
                                                <ReactTooltip border={true} id="company_parent" place="bottom" type="light" effect="solid" />
                                            </div >
                                        );
                                    }
                                }
                            },
                            {
                                name: "Unit Bisnis",
                                options: {
                                    customBodyRender: (val, tableMeta) => {
                                        let check = null
                                        if (tableMeta.rowData[6] != null) {
                                            check = tableMeta.rowData[6].findIndex((val) => val.field.includes('unit_bisnis'))
                                            if (check > -1) {
                                                this.setState({ buttonError: true })
                                            }
                                        }
                                        return (
                                            <div style={{ display: 'flex' }}>
                                                {tableMeta.rowData[6] != null && check > -1 ?
                                                    <a data-tip={tableMeta.rowData[6][check].message} data-for="unit_bisnis">
                                                        <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                                                    </a> :
                                                    <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                                                }
                                                <ReactTooltip border={true} id="unit_bisnis" place="bottom" type="light" effect="solid" />
                                            </div >
                                        );
                                    }
                                }
                            },
                            {
                                name: "Start Date",
                                options: {
                                    customBodyRender: (val, tableMeta) => {
                                        let check = null
                                        if (tableMeta.rowData[6] != null) {
                                            check = tableMeta.rowData[6].findIndex((val) => val.field.includes('start_date'))
                                            if (check > -1) {
                                                this.setState({ buttonError: true })
                                            }
                                        }
                                        return (
                                            <div style={{ display: 'flex' }}>
                                                {tableMeta.rowData[6] != null && check > -1 ?
                                                    <a data-tip={tableMeta.rowData[6][check].message} data-for="startdate">
                                                        <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                                                    </a> :
                                                    <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                                                }
                                                <ReactTooltip border={true} id="startdate" place="bottom" type="light" effect="solid" />
                                            </div >
                                        );
                                    }
                                }
                            },
                            {
                                name: "End Date",
                                options: {
                                    customBodyRender: (val, tableMeta) => {
                                        let check = null
                                        if (tableMeta.rowData[6] != null) {
                                            check = tableMeta.rowData[6].findIndex((val) => val.field.includes('end_date'))
                                            if (check > -1) {
                                                this.setState({ buttonError: true })
                                            }
                                        }
                                        return (
                                            <div style={{ display: 'flex' }}>
                                                {tableMeta.rowData[6] != null && check > -1 ?
                                                    <a data-tip={tableMeta.rowData[6][check].message} data-for="enddate">
                                                        <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                                                    </a> :
                                                    <span style={{ color: check != null && check > -1 ? "red" : 'black' }}>{val}</span>
                                                }
                                                <ReactTooltip border={true} id="enddate" place="bottom" type="light" effect="solid" />
                                            </div >
                                        );
                                    }
                                }
                            },
                            {
                                name: "",
                                options: {
                                    display: false
                                }
                            }
                        ]

                        console.log(dataRow);
                        this.setState({
                            dataLoaded: true,
                            cols: columns,
                            rows: dataRow
                        });
                    }
                    console.log(response);
                })

            }
        });
    }

    componentDidMount() {
        this.getData()
    }

    getData() {
        api.create().getPerusahaan().then((response) => {
            console.log(response)
            if (response.data.status == 'success') {
                let data = response.data.data
                let listData = data.map((item, index) => {
                    return [index, item.company_id, item.company_name, item.parent_name, item.business_unit_name, item.total_report, item.status]
                })
                this.setState({ dataTable: listData, listData: response.data.data })
            } else {
                alert(response.data.message)
            }
        })
    }

    openPopUp(index, type) {
        if (type === 'edit') {
            this.setState({
                selectIndex: index,
                visibleEdit: true
            })
        } else {
            this.setState({
                data: this.state.listData[index],
                visibleCreate: true
            })
        }
    }

    handleInputChange(e) {
        this.setState({ search: e })
        let body = {
            "keyword": e
        }
        api.create().searchPerusahaan(body).then(response => {
            console.log(response.data);
            if (response.data.status == 'success') {
                let data = response.data.data
                let listData = data.map((item, index) => {
                    return [index, item.company_id, item.company_name, item.parent_name, item.business_unit_name, item.total_report, item.status]
                })
                this.setState({ dataTable: listData, listData: response.data.data })
            } else {
                alert(response.data.message)
            }
        })
    }

    updatePerusahaan = (payload) => {
        this.setState({ visibleEdit: false })
        api.create().updatePerusahaan(payload).then(response => {
            if (response.data.status == 'success') {
                this.getData()
            } else {
                alert(response.data.message)
            }
        })
    }

    createPerusahaan = (payload) => {
        this.setState({ visibleCreate: false })
        api.create().createPerusahaan(payload).then(response => {
            if (response.data.status == 'success') {
                this.getData()
            } else {
                alert(response.data.message)
            }
        })
    }

    downloadFile = async () => {
        let res = await fetch(
            "https://tia.eksad.com/tia-reporting-dev/public/attachment/download_file?fileName=CompanyTemplate&&fileType=xlsx"
        )
        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 = 'Template Perusahaan.xlsx';
            a.click();
        }
    }

    downloadDataTable = async () => {
        let res = await fetch(
            "https://tia.eksad.com/tia-reporting-dev/public/company/export_company"
        )
        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 = 'Perusahaan.xlsx';
            a.click();
        }
    }

    uploadPerusahaan() {
        api.create().uploadPerusahaan(this.state.payload).then(response => {
            console.log(response)
            this.getData()
            this.setState({ visiblePerusahaan: true })
        })
    }

    render() {
        const columns = [{
            name: "Action",
            options: {
                customBodyRender: (val, tableMeta) => {
                    return (
                        <div style={{ display: 'flex' }}>
                            <button
                                style={{
                                    backgroundColor: 'transparent',
                                    cursor: 'pointer',
                                    borderColor: 'transparent'
                                }}
                                // onClick={() => this.setState({ visibleEdit: true, data: tableMeta.rowData })}
                                onClick={() => this.openPopUp(tableMeta.rowIndex, 'edit')}
                            >
                                <img src={Images.editCopy} />
                            </button>
                        </div >
                    );
                }
            }
        }, {
            name: "ID",
            options: {
                customBodyRender: (val, tableMeta) => {
                    return (
                        <div style={{ display: 'flex' }}>
                            <span style={{ color: tableMeta.rowData[6] === "Aktif" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{val}</span>
                        </div >
                    );
                }
            }
        }, {
            name: "Nama Perusahaan",
            options: {
                customBodyRender: (val, tableMeta) => {
                    return (
                        <div style={{ display: 'flex' }}>
                            <span style={{ color: tableMeta.rowData[6] === "Aktif" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{val}</span>
                        </div >
                    );
                }
            }
        }, {
            name: "Parent Company",
            options: {
                customBodyRender: (val, tableMeta) => {
                    return (
                        <div style={{ display: 'flex' }}>
                            <span style={{ color: tableMeta.rowData[6] === "Aktif" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{val}</span>
                        </div >
                    );
                }
            }
        }, {
            name: "Unit Bisnis",
            options: {
                customBodyRender: (val, tableMeta) => {
                    return (
                        <div style={{ display: 'flex' }}>
                            <span style={{ color: tableMeta.rowData[6] === "Aktif" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{val}</span>
                        </div >
                    );
                }
            }
        }, {
            name: "Jumlah Laporan",
            options: {
                customBodyRender: (val, tableMeta) => {
                    return (
                        <div style={{ display: 'flex' }}>
                            <span style={{ color: tableMeta.rowData[6] === "Aktif" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{val}</span>
                        </div >
                    );
                }
            }
        }, {
            name: "Status",
            options: {
                customBodyRender: (val, tableMeta) => {
                    return (
                        <div style={{ display: 'flex' }}>
                            <span style={{ color: tableMeta.rowData[6] === "Aktif" ? "#656565" : 'rgba(0, 0, 0, 0.25)' }}>{val}</span>
                        </div >
                    );
                }
            }
        }]
        const data = [
            ["", "1", "Triputra Agro Persada Group", "Triputra Investindo Arya", "Agrobisnis", "5", "Aktif"],
            ["", "2", "Gawi Bahandep Sawit Mekar", "Triputra Agro Persada Group", "Agrobisnis", "2", "Aktif"],
            ["", "3", "Puninar Group", "Triputra Investindo Arya", "Service", "5", "Aktif"],
            ["", "4", "Puninar Infinite Raya", "Puninar Group", "Service", "5", "Non Aktif"],
            ["", "-", "-", "-", "-", "-"],
        ]
        return (
            <div style={{ height: this.props.height }}>
                {/* <Row> */}
                <div className={"main-color"} style={{ height: 199, width: '100%' }} />
                {this.state.visiblePerusahaan === true ?
                    <div>
                        <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', paddingRight: 25, paddingLeft: 25, marginTop: -150 }}>
                            <label style={{ color: 'white', fontSize: 16, alignSelf: 'center', width: '20%' }}>Master Data - Perusahaan</label>
                            <div style={{ color: 'white', width: '50%', height: 37, display: 'flex', backgroundColor: 'white', borderWidth: 2, alignItems: 'center', borderRadius: 6, paddingLeft: 5, paddingRight: 5, alignSelf: 'center' }}>
                                <img src={Images.searchBlack} style={{ marginRight: 10 }} />
                                <InputBase
                                    style={{ width: '100%' }}
                                    placeholder="Search"
                                    value={this.state.search}
                                    onChange={(e) => this.handleInputChange(e.target.value)}
                                    inputProps={{ 'aria-label': 'naked' }}
                                />
                            </div>
                            <div style={{ width: '20%', justifyContent: 'space-around', display: 'flex', flexFlow: 'wrap' }}>
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent',
                                        margin: 5
                                    }}
                                    onClick={() => this.downloadFile()}
                                >
                                    <img src={Images.template} />
                                </button>
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent',
                                        margin: 5
                                    }}
                                    onClick={() => this.setState({ visibleUpload: true })}
                                >
                                    <img src={Images.upload} />
                                </button>
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent',
                                        margin: 5
                                    }}
                                    onClick={() => this.downloadDataTable()}
                                >
                                    <img src={Images.download} />
                                </button>
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent',
                                        margin: 5
                                    }}
                                    onClick={() => null}
                                >
                                    <img src={Images.visualisasi} onClick={() => this.setState({ visibleVisual: true, visiblePerusahaan: false })} />
                                </button>
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent',
                                        margin: 5
                                    }}
                                    onClick={() => this.setState({ visibleCreate: true })}
                                >
                                    <img src={Images.add} />
                                </button>
                            </div>
                        </div>
                        <div style={{ padding: 25 }}>
                            <MuiThemeProvider theme={getMuiTheme()}>
                                <MUIDataTable
                                    theme={getMuiTheme()}
                                    data={this.state.dataTable}
                                    columns={columns}
                                    options={options}
                                />
                            </MuiThemeProvider>

                        </div>
                    </div>
                    :
                    this.state.visibleVisual == true ?
                        <VisualPerusahaan
                            onClickClose={() => this.setState({ visibleVisual: false, visiblePerusahaan: true })}
                            height={this.props.height}
                        />
                        :
                        <div>
                            <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', paddingRight: 25, paddingLeft: 25, marginTop: -150 }}>
                                <label style={{ color: 'white', fontSize: 16, alignSelf: 'center' }}>Preview Data</label>
                            </div>
                            <div style={{ padding: 25 }}>
                                {this.state.dataLoaded && (
                                    <MuiThemeProvider theme={getMuiTheme()}>
                                        <MUIDataTable
                                            theme={getMuiTheme()}
                                            data={this.state.rows}
                                            columns={this.state.cols}
                                            options={options2}
                                        />
                                    </MuiThemeProvider>
                                )}
                            </div>
                            <div style={{ display: 'flex', width: '100%', placeContent: 'flex-end', padding: 20 }}>
                                <button
                                    type="button"
                                    onClick={() => this.setState({ visiblePerusahaan: true })}
                                    style={{ marginRight: 20 }}
                                >
                                    <div style={{ width: 102, height: 30, border: 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                        <span style={{ color: '#354960', fontSize: 11 }}>Batal</span>
                                    </div>
                                </button>
                                <button
                                    type="button"
                                    onClick={() => this.state.buttonError ? this.setState({ popupError: true }) : this.uploadPerusahaan()}
                                    style={{}}
                                >
                                    <div style={{ width: 102, height: 30, backgroundColor: '#354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                        <span style={{ color: '#fff', fontSize: 11 }}>Simpan</span>
                                    </div>
                                </button>
                            </div>
                        </div>
                }

                {this.state.visibleCreate && (
                    <CreatePerusahaan
                        onClickClose={() => this.setState({ visibleCreate: false })}
                        type={"create"}
                        createPerusahaan={this.createPerusahaan.bind(this)}
                    />
                )}

                {this.state.visibleEdit && (
                    <EditPerusahaan
                        type={"edit"}
                        onClickClose={() => this.setState({ visibleEdit: false })}
                        data={this.state.listData[this.state.selectIndex]}
                        updatePerusahaan={this.updatePerusahaan.bind(this)}
                    />
                )}

                {this.state.popupError && (
                    <PopUpFailedSave onClickClose={() => this.setState({ popupError: false })} />
                )}

                {this.state.visibleUpload && (
                    <div className="test app-popup-show">
                        <div className="popup-content background-white border-radius" style={{ borderRadius: 8 }}>
                            <div className="popup-panel grid grid-2x" style={{ backgroundColor: '#51c6ea', height: 64, borderTopRightRadius: 8, borderTopLeftRadius: 8 }}>
                                <div className="col-1" style={{ maxWidth: "inherit", display: 'flex', alignItems: 'center' }}>
                                    <div className="popup-title">
                                        <span style={{ color: '#fff', fontSize: 16, fontWeight: 'bold' }}>Upload File</span>
                                    </div>
                                </div>
                                <div className="col-2 content-right" style={{ maxWidth: "inherit", alignSelf: 'center' }}>
                                    <button
                                        type="button"
                                        className="btn btn-circle btn-white"
                                        onClick={() => this.setState({ visibleUpload: false })}
                                    >
                                        <img src={Images.close}/>
                                    </button>
                                </div>
                            </div>
                            <UploadFile
                                type={this.state.uploadStatus}
                                percentage={this.state.percentage}
                                result={this.state.result}
                                acceptedFiles={["pdf"]}
                                onHandle={(dt) => {
                                    this.fileHandler(dt)
                                    this.setState({ uploadStatus: 'idle', percentage: '0' })
                                }}
                                onUpload={() => this.setState({ visibleUpload: false, visiblePerusahaan: false })}
                            />
                        </div>
                    </div>
                )}
            </div>
        );
    }
}