import React, { Component } from 'react';
import { Typography, Paper, TextField, MenuItem, Select, FormControlLabel, createMuiTheme, withStyles, MuiThemeProvider } from '@material-ui/core';
import MUIDataTable from 'mui-datatables';
import Images from '../../assets/Images';
import OperatingIndicatorDetail from './OperatingIndicatorDetail'
import api from '../../api';
import Autocomplete from '@material-ui/lab/Autocomplete';
import MuiAlert from '@material-ui/lab/Alert';
import { titleCase } from '../../library/Utils';
import { ExcelRenderer } from 'react-excel-renderer';
import UploadFile from "../../library/Upload";
import { format } from 'date-fns';
import Constant from '../../library/Constant';
import OperatingIndicatorMR from '../MonthlyReport/OperatingIndicatorMR';

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

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

export default class OperatingIndicator extends Component {
    constructor(props) {
        super(props)
        this.state = {
            perusahaan: 'TAP Group',
            listRevision: null,
            revision: null,
            visibleOperatingIndicator: true,
            visibleDetailOpt: false,
            visibleDetailMonthly: false,
            visibleDetailRolling: false,
            listPeriode: null,
            periode: null,
            month: null,
            listCompany: null,
            company: null,
            report_id: null,
            listAttachment: [],
            visibleUpload: false,
            operatingIndID: null,
            alert: false,
            tipeAlert: '',
            messageAlert: '',
            buttonCreate: true,
            buttonEdit: true,
            buttonDelete: true,
            lastPeriod: '',
            latestPeriode: '',
            statusDetail: ''
        }
        this.fileHandler = this.fileHandler.bind(this);
    }

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

    getPermission() {
        let payload = {
            menu: "operating indicator"
        }
        api.create().getPermission(payload).then(response => {
            console.log(response)
            if (response.data) {
                if (response.data.status === "success") {
                    this.setState({
                        buttonCreate: response.data.data.create,
                        buttonEdit: response.data.data.edit,
                        buttonDelete: response.data.data.delete,
                        load: true
                    })
                } else {
                    this.setState({ load: true })
                }
            }
        })
    }

    getLastPeriod() {
        api.create().getLastPeriodOI(this.state.company.company_id).then(response => {  
            // console.log(response);
            if (response.data.status === "success") {
                this.setState({ lastPeriod: response.data.data.last_periode, latestPeriode: response.data.data.latest_periode }, () => {
                    this.getPeriode()
                })
            }
        })
    }

    getReportAttachment() {
        let payload = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "revision": this.state.revision.revision,
        }
        api.create().getMasterBudgetAtt(payload).then(response => {
            if (response.data) {
                if (response.data.status === "success") {
                    this.setState({ listAttachment: response.data.data })
                }
            }
            // console.log(response);
        })
    }

    getReport() {
        let payload = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode,
            "report_type": "operating indicator",
        }
        console.log(payload);
        api.create().getAllOperatingInd(payload).then(response => {
            console.log(response);
            if (response.data) {
                if (response.data.status === "success") {
                    let dataTable = response.data.data.map((item, index) => {
                        return [
                            item.number,
                            item.report_name,
                            item.current_status === 'closed' ? "CLOSED" : item.current_status,
                            item.report_id,
                            item.is_can_upload
                        ]
                    })
                    // console.log(dataTable);
                    this.setState({ dataTable, dataReport: response.data.data })
                }
            }
        })
    }

    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 }, () => {
                            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({ superUser: false })
                    } else {
                        this.setState({ superUser: true })
                    }

                    let companyData = data.map((item) => {
                        return {
                            company_id: item.company_id,
                            company_name: item.company_name,
                        }
                    })

                    let arrayBaru = []
                    this.state.userCompany.map((item, index) => {
                        let indexID = companyData.findIndex((val) => val.company_id == item)
                        if (indexID !== -1) {
                            arrayBaru.push(companyData[indexID])
                        }
                    })

                    if (arrayBaru.length > 0) {
                        arrayBaru = arrayBaru.sort((a,b) => a.company_name.localeCompare(b.company_name))
                    }

                    let defaultProps = {
                        options: arrayBaru,
                        getOptionLabel: (option) => titleCase(option.company_name),
                    };

                    this.setState({ listCompany: defaultProps, company: arrayBaru.length < 1 ? companyData[0] : arrayBaru[0] }, () => {
                        this.getLastPeriod()
                    })
                } 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.problem, tipeAlert: 'error', listCompany: null, company: null })
            }
        })
    }

    getPeriode() {
        api.create().getPeriodeTransaction().then(response => {
            let dateNow = new Date
            let year = format(dateNow, 'yyyy')
            let currentYear = new Date().getFullYear()
            if (response.data) {
                if (response.data.status === "success") {
                    let data = []
                    response.data.data.map((item) => {
                        if (this.state.isApprover) {
                            if (item >= 2000 && item <= (Number(currentYear) + 1)) {
                                data.push(item)
                            }
                            // console.log('bibim')
                        } else {
                            if ((item >= 2000) && (item == this.state.lastPeriod || item < this.state.lastPeriod)) {
                                data.push(item)
                            }
                            // console.log('bubum')
                        }
                    })
                    // console.log(this.state.lastPeriod)
                    // console.log(this.state.lastPeriod)
                    // console.log(this.state.isApprover)
                    let periodeData = data.map((item) => {
                        return {
                            periode: item,
                        }
                    })
                    let defaultProps = {
                        options: periodeData,
                        getOptionLabel: (option) => option.periode,
                    };
                    // console.log(defaultProps)
                    let periode = (this.state.lastPeriod == "" ? String(Number(currentYear) + 1) : this.state.lastPeriod)
                    let index = data.sort((a, b) => a - b).findIndex((val) => val === periode)
                    this.setState({ listPeriode: defaultProps, periode: index == -1 ? periodeData[0] : periodeData[index] }, () => {
                        this.getOperatingID()
                    })
                }
            }
        })
    }

    getOperatingID() {
        let payload = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode
        }
        api.create().getOpetratingIndID(payload).then(response => {
            console.log(response);
            if (response) {
                // console.log(response.data.data)
                this.getLatestPeriodSubmit()
                if (response.data.data) {
                    this.setState({ operatingIndID: response.data.data.operating_indicator_id })
                } else {
                    this.setState({ operatingIndID: null })
                }
            }
        })
    }

    getLatestPeriodSubmit() {
        let body = {
            "company_id": this.state.company.company_id,
            "periode": this.state.periode.periode
        }
        api.create().getSubmitOI(body).then(response => {
            // console.log(response);
            if (response.data) {
                if (response.data.status === "success") {
                    this.setState({ isSubmit: response.data.data.is_can_submit }, () => {
                        this.getReport()
                        // this.getOperatingID()
                    })
                }
            }
        })
    }

    clickDetail(item, id) {
        let index = this.state.dataReport.findIndex((val) => val.report_name == item[1])
        if (index !== -1) {
            // this.setState({
            //     statusDetail: String(item[2]).toLocaleLowerCase(),
            //     dataDetail: { ...this.state.dataReport[index], periode: this.state.periode.periode, operatingIndID: this.state.operatingIndID, company: this.state.company },
            //     visibleOperatingIndicator: false,
            //     visibleDetailOpt: true,
            // })
            if (String(item[1]).toLocaleLowerCase().includes("master budget")) {
                this.setState({
                    statusDetail: String(item[2]).toLocaleLowerCase(),
                    dataDetail: { ...this.state.dataReport[index], periode: this.state.periode.periode, operatingIndID: this.state.operatingIndID, company: this.state.company },
                    visibleOperatingIndicator: false,
                    visibleDetailOpt: true,
                    visibleDetailMonthly: false,
                    visibleDetailRolling: false
                    
                })
            } else if (String(item[1]).toLocaleLowerCase().includes("monthly report")) {
                console.log(item);
                let month = String(item[1]).toLocaleLowerCase().includes('jan') ? 1 : 
                            String(item[1]).toLocaleLowerCase().includes('feb') ? 2 : 
                            String(item[1]).toLocaleLowerCase().includes('mar') ? 3 : 
                            String(item[1]).toLocaleLowerCase().includes('apr') ? 4 : 
                            String(item[1]).toLocaleLowerCase().includes('may') ? 5 : 
                            String(item[1]).toLocaleLowerCase().includes('jun') ? 6 : 
                            String(item[1]).toLocaleLowerCase().includes('jul') ? 7 : 
                            String(item[1]).toLocaleLowerCase().includes('aug') ? 8 : 
                            String(item[1]).toLocaleLowerCase().includes('sep') ? 9 : 
                            String(item[1]).toLocaleLowerCase().includes('oct') ? 10 : 
                            String(item[1]).toLocaleLowerCase().includes('nov') ? 11 :
                            String(item[1]).toLocaleLowerCase().includes('dec') ? 12 : null
                this.setState({
                    statusDetail: String(item[2]).toLocaleLowerCase(),
                    dataDetail: { ...this.state.dataReport[index], periode: this.state.periode.periode, operatingIndID: this.state.operatingIndID, company: this.state.company },
                    visibleOperatingIndicator: false,
                    visibleDetailOpt: false,
                    visibleDetailMonthly: true,
                    visibleDetailRolling: false,
                    months: month
                    
                })
                
            } else {
                this.setState({
                    statusDetail: String(item[2]).toLocaleLowerCase(),
                    dataDetail: { ...this.state.dataReport[index], periode: this.state.periode.periode, operatingIndID: this.state.operatingIndID, company: this.state.company },
                    visibleOperatingIndicator: false,
                    visibleDetailOpt: false,
                    visibleDetailMonthly: false,
                    visibleDetailRolling: true
                    
                })

            }
        }
    }

    handleChange(value, tableMeta) {
        let data = this.state.dataTable
        data[tableMeta.rowIndex][tableMeta.columnIndex] = value
    }

    fileHandler = (event) => {
        let fileObj = event
        ExcelRenderer(fileObj, (err, resp) => {
            // console.log(resp)
            if (err) {
                // console.log(err);
            }
            else {
                const formData = new FormData();
                formData.append("revision", Number(this.state.revision.revision));
                formData.append("companyId", this.state.company.company_id);
                formData.append("periode", Number(this.state.periode.periode));
                formData.append("file", event);
                this.setState({ formData })
            }
        })
    }

    uploadAttachment(formData) {
        api.create().uploadAttachment(formData).then(response => {
            if (response.data) {
                if (response.data.status === "success") {
                    this.setState({ visibleUpload: false }, () => {
                        this.getReport()
                        this.getReportAttachment()
                    })
                }
            }
            // console.log(response)
        })
    }

    saveOperatingInd(payload) {
        api.create().createOpetaingInd(payload).then((response) => {
            console.log(response);
            this.getReport()
            this.getOperatingID()
        })
    }

    saveMonthlyOI(payload) {
        api.create().createMonthlyReportOI(payload).then((response) => {
            console.log(response);
            this.getReport()
            this.getOperatingID()
        })
    }

    render() {
        const columns = ["#", "Report Type",
            // {
            //     name: "Revision",
            //     options: {
            //         customBodyRender: (val, tableMeta, updateValue) => {
            //             var list = [];
            //             for (var i = 0; i <= tableMeta.rowData[6]; i++) {
            //                 list.push(i);
            //             }
            //             return (
            //                 <div style={{ display: 'flex' }}>
            //                     <FormControlLabel
            //                         style={{ margin: 0 }}
            //                         value={val}
            //                         control={
            //                             <Select
            //                                 value={val}
            //                                 onChange={event => {
            //                                     // console.log(event.target)
            //                                     updateValue(event.target.value)
            //                                     this.handleChange(event.target.value, tableMeta)
            //                                 }}
            //                                 autoWidth
            //                             >
            //                                 {list.map((item, index) =>
            //                                     <MenuItem key={index} value={item}>{item}</MenuItem>
            //                                 )}
            //                             </Select>
            //                         }
            //                     />
            //                 </div >
            //             );
            //         }
            //     }
            // }, 
            {
                name: "Status",
                options: {
                    customBodyRender: (val, tableMeta) => {
                        return (
                            <div style={{ display: 'flex' }}>
                                {val === "submitted" || val === "approved" ?
                                    <span>COMPLETED</span> :
                                    val === "draft" ?
                                        <span>DRAFT</span> :
                                        val === "revision" ?
                                            <span>REVISION</span> :
                                            val === "approval_proccess" ?
                                                <span>APPROVAL PROCCESS</span> :
                                                val === "approval_review" ?
                                                    <span>APPROVAL REVIEW</span> :
                                                    val === "not-yet" ?
                                                        <span>OPEN</span> :
                                                        val === "CLOSED" ?
                                                            <span>CLOSED</span> :
                                                            <img src={Images.cross} style={{ width: 31, height: 24 }} />
                                }
                            </div >
                        );
                    }
                }
            },
            {
                name: "Action",
                options: {
                    customBodyRender: (val, tableMeta) => {
                        return (
                            <div style={{ display: 'flex' }}>
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: tableMeta.rowData[4] ? 'pointer' : null,
                                        borderColor: 'transparent'
                                    }}
                                    onClick={() =>
                                        tableMeta.rowData[4] ? 
                                        this.clickDetail(tableMeta.rowData, tableMeta.rowData[1], tableMeta.rowData[3], tableMeta.rowData[2]) 
                                        : 
                                        null
                                    }
                                >
                                    <Typography style={{ color: tableMeta.rowData[4] ? '#5198ea' : 'GrayText', fontSize: 12, }}>Detail</Typography>
                                </button>
                            </div >
                        );
                    }
                }
            }, {
                name: "",
                options: { display: false }
            }, {
                name: "",
                options: { display: false }
            }]
        const options = {
            filter: false,
            sort: false,
            responsive: "scroll",
            print: false,
            download: false,
            selectableRows: false,
            viewColumns: false,
            rowsPerPage: 50,
            pagination: false,
            rowsPerPageOptions: [5, 25, 100],
            search: false
        }
        const periode = [
            { value: '2021', label: '2021' },
            { value: '2020', label: '2020' },
            { value: '2019', label: '2019' },
            { value: '2018', label: '2018' },
            { value: '2017', label: '2017' },
            { value: '2016', label: '2016' },
        ]
        const perusahaan = [
            { value: 'TAP Group', label: 'TAP Group' },
            { value: '2019', label: '2019' },
            { value: '2018', label: '2018' },
            { value: '2017', label: '2017' },
            { value: '2016', label: '2016' },
        ]
        const revisi = [
            { value: '0', label: '0' },
            { value: '1', label: '1' },
        ]
        return (
            <div style={{ flex: 1, backgroundColor: '#f8f8f8' }}>
                {this.state.visibleOperatingIndicator && (
                    <div>
                        <div className={"main-color"} style={{ height: 78, display: 'flex', alignItems: 'center', paddingLeft: 20 }}>
                            <Typography style={{ fontSize: '16px', color: 'white' }}>Operating Indicator</Typography>
                        </div>
                        <div style={{ padding: 20, width: '100%' }}>
                            <Paper style={{ paddingTop: 10 }}>
                                <div style={{ borderBottom: 'solid 1px #c4c4c4' }} >
                                    <Typography style={{ fontSize: '12px', color: '#4b4b4b', margin: 10 }}>Operating Indicator</Typography>
                                </div>
                                <div style={{ padding: 20 }}>
                                    <div>
                                        <Autocomplete
                                            {...this.state.listPeriode}
                                            id="periode"
                                            onChange={(event, newInputValue) => this.setState({ periode: newInputValue }, () => {
                                                this.getOperatingID()
                                                // this.getReportAttachment()
                                            })}
                                            // debug
                                            clearOnEscape
                                            disableClearable
                                            style={{ width: 250 }}
                                            renderInput={(params) => <TextField {...params} label="Period" margin="normal" style={{ marginTop: 7 }} />}
                                            value={this.state.periode}
                                        />
                                    </div>
                                    <div style={{ marginTop: 20 }}>
                                        <Autocomplete
                                            {...this.state.listCompany}
                                            id="company"
                                            onChange={(event, newInputValue) => this.setState({ company: newInputValue }, () => {
                                                this.getOperatingID()
                                                // this.getReportAttachment()
                                            })}
                                            clearOnEscape
                                            disableClearable
                                            style={{ width: 250 }}
                                            renderInput={(params) =>
                                                <TextField
                                                    {...params}
                                                    label="Company"
                                                    margin="normal"
                                                    style={{ marginTop: 7 }}
                                                />}
                                            value={this.state.company}
                                        />
                                    </div>
                                    <div style={{ marginTop: 20 }}>
                                        <MuiThemeProvider theme={getMuiTheme()}>
                                            <MUIDataTable
                                                data={this.state.dataTable}
                                                columns={columns}
                                                options={options}
                                            />
                                        </MuiThemeProvider>
                                    </div>
                                </div>
                                {/* {this.state.isSubmit && (
                                    <div style={{ borderTop: 'solid 1px #c4c4c4', padding: 10, backgroundColor: '#f5f5f5', width: '100%', display: 'flex', justifyContent: 'flex-end' }} >
                                        <div style={{ backgroundColor: '#354960', width: 105, height: 25, borderRadius: 3, justifyContent: 'center', display: 'flex', alignItems: 'center' }}>
                                            <Typography style={{ fontSize: '11px', color: '#fff', textAlign: 'center' }}>Submit</Typography>
                                        </div>
                                    </div>
                                )} */}
                            </Paper>

                        </div>
                    </div>
                )}

                {this.state.visibleDetailOpt &&
                    <OperatingIndicatorDetail
                        open={this.props.open}
                        data={this.state.dataDetail}
                        height={this.props.height}
                        width={this.props.width}
                        onClickClose={() => this.setState({ visibleDetailOpt: false, visibleOperatingIndicator: true }, () => {
                            this.getOperatingID()
                            this.forceUpdate()
                        })}
                        getReport={() => this.getOperatingID()}
                        saveOperatingInd={this.saveOperatingInd.bind(this)}
                        isSubmit={this.state.statusDetail == 'closed'? false : this.state.isSubmit}
                        permission={{ create: this.state.buttonCreate, edit: this.state.buttonEdit, delete: this.state.buttonDelete }}
                    />
                }
                {this.state.visibleDetailMonthly &&
                    <OperatingIndicatorMR
                        open={this.props.open}
                        data={this.state.dataDetail}
                        height={this.props.height}
                        width={this.props.width}
                        months={this.state.months}
                        company={this.state.company}
                        onClickClose={() => this.setState({ visibleDetailMonthly: false, visibleOperatingIndicator: true }, () => {
                            this.getOperatingID()
                            this.forceUpdate()
                        })}
                        getReport={() => this.getOperatingID()}
                        saveMonthlyOI={this.saveMonthlyOI.bind(this)}
                        isSubmit={this.state.statusDetail == 'closed'? false : this.state.isSubmit}
                        permission={{ create: this.state.buttonCreate, edit: this.state.buttonEdit, delete: this.state.buttonDelete }}
                    />
                }

                {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 main-color" style={{ 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={["xlsx"]}
                                onHandle={(dt) => {
                                    this.fileHandler(dt)
                                    this.setState({ uploadStatus: 'idle', percentage: '0' })
                                }}
                                onUpload={() => this.uploadAttachment(this.state.formData)}
                            />
                        </div>
                    </div>
                )}
            </div >
        );
    }
}