import React, { Component } from 'react'
import Images from '../../assets/Images'
import { TextField, withStyles, Snackbar, Typography } from '@material-ui/core'
import MuiAlert from '@material-ui/lab/Alert';
import api from '../../api'
import Autocomplete from '@material-ui/lab/Autocomplete'
import Constant from '../../library/Constant'
import { format } from 'date-fns';
import UploadFile from "../../library/Upload";
import { ExcelRenderer } from 'react-excel-renderer';
import * as R from 'ramda'

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

export default class EditManagementDoc extends Component {
    constructor(props) {
        super(props)
        this.state = {
            perusahaan: null,
            perusahaanData: null,
            getPerusahaan: null,
            errorPerusahaan: false,
            msgErrorPerusahaan: '',
            document: null,
            documentData: null,
            getDocument: null,
            errorDocument: false,
            msgErrorDocument: '',
            listPeriode: null,
            periode: null,
            listMonth: null,
            monthId: null,
            description: '',
            errorDesc: false,
            msgErrorDesc: '',
            errorMonth: false,
            msgErrorMonth: '',
            errorPeriode: false,
            msgErrorPeriode: '',
            file: null,
            alert: false,
            tipeAlert: '',
            messageAlert: '',
            fileType: '',
            konfirmasi: false,
            docId: '',
            document_name: "",
            document_size: 0,
            loadUpload: false,
            sizeUpload: "1",
            name: '',
            disabledPeriode: false
        }
    }

    componentDidMount() {
        this.getFileSize()
        if (this.props.type === 'edit') {
            this.getDetailDoc()
        }
    }

    getFileSize(){
        let body = {
            group: 'MAX_FILE_SIZE',
            company_id: 0,
            type: 'MAX_FILE_SIZE'
        }
        api.create().getAllSettingByType(body).then(response => {
            // console.log(response);
            if (response.data) {
                if (response.data.status === "success") {
                    this.setState({
                        sizeUpload: response.data.data[0] ? response.data.data[0].value === undefined ? "1" : response.data.data[0].value : "1"
                    })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            }
        })
    }

    getDetailDoc() {
        api.create().getDetailDocument(this.props.idoc).then(response => {
            // console.log(response)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === "success") {
                        let data = response.data.data
                        this.setState({
                            companyId: data.company_id,
                            companyName: data.company_name,
                            categoryId: data.setting_id,
                            categoryName: data.values,
                            period: data.document_periode,
                            getMonthName: data.document_month,
                            description: data.description,
                            filePath: data.document_filepath,
                            file: data.document_filepath,
                            document_name: data.document_name,
                            document_size: data.document_size,
                            // id: data.approval_matrix_id,
                            // status: data.status,
                            fileType: data.document_type,
                            created: data.created,
                            updated: data.updated === null ? "" : data.updated,
                            loadUpload: true,
                            name: data.values,
                            disabledPeriode: data.values === 'Manual Book TIA 4.0' ? true : false
                        }, () => {
                            this.getDataCompany()
                            this.getDataDocument()
                            this.getPeriode()
                            this.getMonth()
                        })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    getDataCompany() {
        api.create().getPerusahaanUserActive().then((response) => {
            if (response.data) {
                if (response.data.status == 'success') {
                    let data = response.data.data
                    let typeData = data.map((item) => {
                        return {
                            company_id: item.company_id,
                            company_name: item.company_name
                        }
                    })
                    let typeProps = {
                        options: typeData,
                        getOptionLabel: (option) => option.company_name,
                    };
                    let index = typeData.findIndex((val) => val.company_id == this.state.companyId)
                    this.setState({ perusahaan: typeProps, perusahaanData: response.data.data, getPerusahaan: index === -1 ? typeData[0] : typeData[index] })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    getDataDocument() {
        // let payload = {
        //     "setting_group_id": 7,
        //     "setting_type_id": 167,
        //     "company_id": 0

        // }
        api.create().getDocumentCategory().then(response => {
            // console.log(response);
            if (response.data) {
                if (response.data.status == 'success') {
                    let data = response.data.data
                    let typeData = data.map((item) => {
                        return {
                            document_category_id: item.setting_id,
                            document_category_name: item.value
                        }
                    })
                    let typeProps = {
                        options: typeData,
                        getOptionLabel: (option) => option.document_category_name,
                    };
                    let index = typeData.findIndex((val) => val.document_category_id == this.state.categoryId)
                    this.setState({ document: typeProps, documentData: response.data.data, getDocument: index === -1 ? typeData[0] : typeData[index] })
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                        if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                            setTimeout(() => {
                                localStorage.removeItem(Constant.TOKEN)
                                window.location.reload();
                            }, 1000);
                        }
                    })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    getPeriode() {
        api.create().getPeriodeTransaction().then(response => {
            let dateNow = new Date
            let year = format(dateNow, 'yyyy')
            if (response.data) {
                if (response.data.status === "success") {
                    let data = response.data.data
                    let periodeData = data.map((item) => {
                        return {
                            periode: item,
                        }
                    })
                    let defaultProps = {
                        options: periodeData,
                        getOptionLabel: (option) => option.periode,
                    };
                    let index = data.sort((a, b) => a - b).findIndex((val) => val == this.state.period)
                    this.setState({ listPeriode: defaultProps, periode: index == -1 ? periodeData[0] : periodeData[index] })
                }
            }
        })
    }

    getMonth() {
        api.create().getMonthTransaction().then(response => {
            let dateNow = new Date
            // let bulan = format(dateNow, 'MMMM')
            if (response.data) {
                if (response.data.status === "success") {
                    let data = response.data.data
                    let monthData = data.map((item) => {
                        return {
                            month_name: item.month_name,
                            month_id: item.month_id
                        }
                    })
                    let index = monthData.findIndex((val) => val.month_name == this.state.getMonthName)
                    let defaultProps = {
                        options: monthData,
                        getOptionLabel: (option) => option.month_name,
                    };
                    // let index = data.sort((a, b) => a - b).findIndex((val) => val.month_name == this.state.getMonth)
                    this.setState({ listMonth: defaultProps, monthId: index == -1 ? monthData[0] : monthData[index] })
                }
            }
        })
    }

    clearMessage() {
        this.setState({
            errorPerusahaan: false,
            msgErrorPerusahaan: '',
            errorDocument: false,
            msgErrorDocument: '',
            errorMonth: false,
            msgErrorMonth: '',
            errorPeriode: false,
            msgErrorPeriode: '',
        })
    }

    fileHandler = (event) => {
        let fileObj = event
        let length = event.name.split(".").length
        let fileType = event.name.split(".")[length - 1]
        if (fileType === 'zip' || 'rar') {
            this.setState({ file: event, fileType: String(fileType) })
        } else {
            ExcelRenderer(fileObj, (err, resp) => {
                // console.log(fileType)
                if (err) {
                    // console.log(err);
                }
                else {
                    this.setState({ file: event, fileType: String(fileType) })
                }
            })
        }
    }

    validasi() {
        if (String(this.props.name).includes('Manual Book TIA')){
        } else {
            if (R.isNil(this.state.periode)) {
                this.setState({ errorPeriode: true, msgErrorPeriode: 'Period Cannot be Empty' })
            }  else if (R.isNil(this.state.monthId)) {
                this.setState({ errorMonth: true, msgErrorMonth: 'Month Cannot be Empty' })
            } else if (R.isNil(this.state.getPerusahaan)) {
                this.setState({ errorPerusahaan: true, msgErrorPerusahaan: 'Company Cannot be Empty' })
            }
        }
        if (R.isNil(this.state.getDocument)) {
            this.setState({ errorDocument: true, msgErrorDocument: 'Category Cannot be Empty' })
        } else if (R.isNil(this.state.file)) {
            this.setState({ alert: true, messageAlert: 'File Cannot be Empty', tipeAlert: 'warning' })
        } 
        
        else {
            const formData = new FormData();
            if (this.state.file == this.state.filePath){
                formData.append("updated", 0);
                formData.append("file", null);
            } else {
                formData.append("updated", 1);
                formData.append("file", this.state.file);
            }
            if (String(this.props.name).includes('Manual Book TIA')){
                formData.append("documentMonth", null);
                formData.append("documentPeriode", null);
                formData.append("companyId", 1);

            } else {
                formData.append("documentMonth", this.state.monthId.month_id);
                formData.append("documentPeriode", this.state.periode.periode);
                formData.append("companyId", this.state.getPerusahaan.company_id);
            }
            formData.append("settingId", this.state.getDocument.document_category_id);
            formData.append("description", this.state.description);
            formData.append("extension", this.state.fileType);
            formData.append("documentId", this.props.idoc);
            this.setState({ formData }, () => {
                this.props.updateDocument(this.state.formData)
            })
        }
    }

    deleteFile(e) {
        this.setState({ file: null })
    }

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

    render() {
        return (
            <div>
                <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' }}>Edit</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.props.onClickClose()}
                                >
                                    <img src={Images.close} />
                                </button>
                            </div>
                        </div>

                        <div className="grid grid-2x grid-mobile-none gap-15px" style={{ paddingLeft: 20, paddingRight: 20, paddingTop: 20 }}>
                            {this.state.disabledPeriode === false ?
                            <div className="column-1">
                                <div style={{ padding: 10, borderRadius: 5 }}>
                                    <Autocomplete
                                        {...this.state.perusahaan}
                                        debug
                                        // clearOnEscape
                                        id="tipe"
                                        onChange={(event, newInputValue) => this.setState({ getPerusahaan: newInputValue }, () => this.clearMessage())}
                                        renderInput={(params) =>
                                            <TextField {...params}
                                                error={this.state.errorPerusahaan}
                                                helperText={this.state.msgErrorPerusahaan}
                                                InputProps={{ ...params.InputProps, style: { fontSize: 11 } }}
                                                InputLabelProps={{ style: { fontSize: 11, color: '#7e8085' } }}
                                                label="Company Name" />}
                                        value={this.state.getPerusahaan}
                                    />
                                </div>
                            </div>
                            :true}
                            {this.state.disabledPeriode === false ?
                            <div className="column-2">
                                <div style={{ padding: 10, borderRadius: 5 }}>
                                    <Autocomplete
                                        {...this.state.document}
                                        // debug
                                        clearOnEscape
                                        id="tipe"
                                        onChange={(event, newInputValue) => this.setState({ getDocument: newInputValue }, 
                                        () => newInputValue === null ? this.setState({ disabledPeriode: false })
                                            : newInputValue.document_category_name === 'Manual Book TIA 4.0' ?
                                                this.setState({ disabledPeriode: true }, () => this.clearMessage())
                                            : this.setState({ disabledPeriode: false }, () => this.clearMessage())
                                        )}
                                        renderInput={(params) =>
                                            <TextField {...params}
                                                error={this.state.errorDocument}
                                                helperText={this.state.msgErrorDocument}
                                                InputProps={{ ...params.InputProps, style: { fontSize: 11 } }}
                                                InputLabelProps={{ style: { fontSize: 11, color: '#7e8085' } }}
                                                label="Category" />}
                                        value={this.state.getDocument}
                                    />
                                </div>
                            </div>
                            :
                            <div className="column-1">
                                <div style={{ padding: 10, borderRadius: 5 }}>
                                    <Autocomplete
                                        {...this.state.document}
                                        // debug
                                        clearOnEscape
                                        id="tipe"
                                        onChange={(event, newInputValue) => this.setState({ getDocument: newInputValue }, 
                                        () => newInputValue === null ? this.setState({ disabledPeriode: false })
                                            : newInputValue.document_category_name === 'Manual Book TIA 4.0' ?
                                                this.setState({ disabledPeriode: true }, () => this.clearMessage())
                                            : this.setState({ disabledPeriode: false }, () => this.clearMessage())
                                        )}
                                        renderInput={(params) =>
                                            <TextField {...params}
                                                error={this.state.errorDocument}
                                                helperText={this.state.msgErrorDocument}
                                                InputProps={{ ...params.InputProps, style: { fontSize: 11 } }}
                                                InputLabelProps={{ style: { fontSize: 11, color: '#7e8085' } }}
                                                label="Category" />}
                                        value={this.state.getDocument}
                                    />
                                </div>
                            </div>
                            }
                            {this.state.disabledPeriode === false ?
                            <div className="column-1">
                                <div style={{ padding: 10, borderRadius: 5 }}>
                                    <Autocomplete
                                        {...this.state.listMonth}
                                        // debug
                                        clearOnEscape
                                        id="month"
                                        onChange={(event, newInputValue) => this.setState({ monthId: newInputValue }, () => this.clearMessage())}
                                        style={{ width: 250 }}
                                        renderInput={(params) =>
                                            <TextField {...params} label="Period Month" margin="normal" style={{ marginTop: 7 }}
                                                InputProps={{ ...params.InputProps, style: { fontSize: 11 } }}
                                                InputLabelProps={{ style: { fontSize: 11, color: '#7e8085' } }}
                                                error={this.state.errorMonth}
                                                helperText={this.state.msgErrorMonth}
                                            />}
                                        value={this.state.monthId}
                                    />
                                </div>
                            </div>
                            : true }
                            {this.state.disabledPeriode === false ?
                            <div className="column-2">
                                <div style={{ padding: 10, borderRadius: 5 }}>
                                    <Autocomplete
                                        {...this.state.listPeriode}
                                        // debug
                                        clearOnEscape
                                        id="periode"
                                        onChange={(event, newInputValue) => this.setState({ periode: newInputValue }, () => this.clearMessage())}
                                        style={{ width: 250 }}
                                        renderInput={(params) =>
                                            <TextField {...params} label="Period Year" margin="normal" style={{ marginTop: 7 }}
                                                InputProps={{ ...params.InputProps, style: { fontSize: 11 } }}
                                                InputLabelProps={{ style: { fontSize: 11, color: '#7e8085' } }}
                                                error={this.state.errorPeriode}
                                                helperText={this.state.msgErrorPeriode}
                                            />}
                                        value={this.state.periode}
                                    />
                                </div>
                            </div>
                            : true}
                        </div>
                        <div style={{ paddingLeft: 30, paddingRight: 30, paddingTop: 10 }}>
                            {this.state.loadUpload && (
                                <UploadFile
                                    type={this.state.uploadStatus}
                                    percentage={this.state.percentage}
                                    result={this.state.result}
                                    acceptedFiles={["xls", "xlsx", "pdf", "PDF", "docx", "doc", "pptx", "ppt", "ods", "odf" ]}
                                    intent={"management"}
                                    onHandle={(dt) => {
                                        this.fileHandler(dt)
                                        this.setState({ uploadStatus: 'idle', percentage: '0' })
                                    }}
                                    onDelete={(e) => {
                                        this.deleteFile(e)
                                    }}
                                    onUpload={() => alert('sukses')}
                                    value={this.state.file}
                                    docSize={this.state.document_size}
                                    docName={this.state.document_name}
                                    sizeUpload={Number(this.state.sizeUpload)}
                                />
                            )}
                        </div>
                        <div className="margin-top-10px" style={{ paddingLeft: 30, paddingRight: 30, borderRadius: 5, paddingBottom: 20 }}>
                            <TextField
                                style={{ width: '100%' }}
                                id="description"
                                label="Description"
                                value={this.state.description}
                                inputProps={{
                                    min: 0,
                                    style: {
                                        fontSize: 11
                                    }
                                }}

                                InputLabelProps={{
                                    style: {
                                        fontSize: 11,
                                        color: '#7e8085'
                                    }
                                }}
                                name="Description"
                                onChange={(e) => {
                                    this.setState({
                                        description: e.target.value
                                    })
                                    this.clearMessage()
                                }}
                                error={this.state.errorDesc}
                                helperText={this.state.msgErrorDesc}
                            >
                            </TextField>
                        </div>
                        <div className="margin-top-10px" style={{ paddingLeft: 30, paddingRight: 30, borderRadius: 5, paddingBottom: 20 }}>
                            <div style={{ display: 'flex' }}>
                                <Typography style={{ fontSize: 11, width: '12%' }}>Created By</Typography>
                                <Typography style={{ fontSize: 11 }}>: {this.state.created}</Typography>
                            </div>
                            <div style={{ display: 'flex' }}>
                                <Typography style={{ fontSize: 11, width: '12%' }}>Updated By</Typography>
                                <Typography style={{ fontSize: 11 }}>: {this.state.updated == - null ? "" : this.state.updated}</Typography>
                            </div>
                        </div>
                        <div className="border-top grid grid-2x" style={{ height: 56, backgroundColor: '#f5f5f5', paddingLeft: 20, paddingRight: 20 }}>
                            <div className="column-1" style={{ alignSelf: 'center' }}>
                                <button
                                    type="button"
                                    onClick={() => this.props.onClickClose()}
                                >
                                    <div style={{ width: 102, height: 30, border: 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                        <span style={{ color: '#354960', fontSize: 11 }}>Cancel</span>
                                    </div>
                                </button>
                            </div>
                            <div className="column-2" style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
                                <button
                                    type="button"
                                    onClick={() => 
                                        this.setState({ loading: true }, () => {
                                            setTimeout(() => {
                                                this.validasi()
                                            }, 100);
                                        })
                                    }
                                >
                                    <div style={{ width: 102, height: 30, backgroundColor: '#354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                        <span style={{ color: '#fff', fontSize: 11 }}>Save</span>
                                    </div>
                                </button>
                            </div>
                        </div>
                    </div>
                    <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
                        <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
                            {this.state.messageAlert}
                        </Alert>
                    </Snackbar>
                </div>
            </div>
        )
    }
}
