import React, { Component } from 'react'
import Images from '../../assets/Images'
import { TextField, withStyles, Snackbar } 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'
import PropagateLoader from "react-spinners/PropagateLoader"

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

export default class CreateManagementDoc 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,
            errorPeriode: false,
            msgErrorPeriode: '',
            listMonth: null,
            monthId: null,
            errorMonth: false,
            msgErrorMonth: '',
            description: '',
            errorDesc: false,
            msgErrorDesc: '',
            file: null,
            alert: false,
            tipeAlert: '',
            messageAlert: '',
            fileType: '',
            konfirmasi: false,
            docId: '',
            sizeUpload: "1",
            disabledPeriode: false
        }
    }

    componentDidMount() {
        this.getDataCompany()
        this.getDataDocument()
        this.getPeriode()
        this.getMonth()
        this.getFileSize()
    }

    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") {
                    if (response.data.data.length == 0) {
                        this.setState({
                            sizeUpload: "1"
                        })
                    } else {
                        this.setState({
                            sizeUpload: response.data.data[0].value
                        })
                    }
                    // 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);
                        }
                    })
                }
            }
        })
    }

    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
                        }
                    })
                    // typeData.push({
                    //     company_id: 0,
                    //     company_name: 'Default'
                    // })
                    let typeProps = {
                        options: typeData.sort((a, b) => a.company_name - b.company_name),
                        getOptionLabel: (option) => option.company_name,
                    };
                    this.setState({ perusahaan: typeProps, perusahaanData: response.data.data })
                } 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) => {
                        if (String(item.value).toLocaleLowerCase().includes('manual book tia')){
                            if( this.props.allsubcoCreate ){
                                typeData.push( {
                                    document_category_id: item.setting_id,
                                    document_category_name: item.value
                                })
                            }
                        } else {
                            typeData.push( {
                                document_category_id: item.setting_id,
                                document_category_name: item.value
                            })
                        }
                    })
                    // console.log(typeData)
                    let typeProps = {
                        options: typeData.sort((a, b) => a.document_category_id - b.document_category_id),
                        getOptionLabel: (option) => option.document_category_name,
                    };
                    this.setState({ document: typeProps, documentData: response.data.data })
                } 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 == year)
                    this.setState({ listPeriode: defaultProps, periode: index == -1 ? periodeData[0] : periodeData[index] })
                } 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);
                        }
                    })
                }
            }
        })
    }

    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_id: item.month_id,
                            month_name: item.month_name
                        }
                    })
                    let defaultProps = {
                        options: monthData,
                        getOptionLabel: (option) => option.month_name,
                    };
                    // let index = data.sort((a, b) => a - b).findIndex((val) => val == bulan)
                    // this.setState({ listMonth: defaultProps, month: index == -1 ? monthData[0] : monthData[index] })
                    this.setState({ listMonth: defaultProps })
                } 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);
                        }
                    })
                }
            }
        })
    }

    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 (this.state.disabledPeriode === true) {
            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();
                formData.append("file", this.state.file);
                formData.append("companyId", 1);
                formData.append("settingId", this.state.getDocument.document_category_id);
                formData.append("description", this.state.description);
                formData.append("extension", this.state.fileType);
                formData.append("documentPeriode", null);
                formData.append("documentMonth", null);
                this.setState({ formData }, () => {
                    this.props.createDocument(this.state.formData, this.props.setting_id, this.props.name)
                })
                var object = {};
                formData.forEach(function (value, key) {
                    object[key] = value;
                });
                var json = JSON.stringify(object);
                // console.log(object)
            }

        } else {
            if (R.isNil(this.state.getPerusahaan)) {
                this.setState({ errorPerusahaan: true, msgErrorPerusahaan: 'Company Cannot be Empty' })
            } else if (R.isNil(this.state.getDocument)) {
                this.setState({ errorDocument: true, msgErrorDocument: 'Category Cannot be Empty' })
            } 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.file)) {
                this.setState({ alert: true, messageAlert: 'File Cannot be Empty', tipeAlert: 'warning' })
            } else {
                const formData = new FormData();
                formData.append("file", this.state.file);
                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("documentPeriode", this.state.periode.periode);
                formData.append("documentMonth", this.state.monthId.month_id);
                this.setState({ formData }, () => {
                    this.props.createDocument(this.state.formData, this.props.setting_id, this.props.name)
                })
            }
        }
        this.props.handleLoading(0)
    }

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

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

    render() {
        const loadingComponent = (
            <div style={{ position: 'absolute', zIndex: 110, top: 0, left: 0, width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', background: 'rgba(255,255,255,0.8)' }}>
                <PropagateLoader
                    // css={override}
                    size={20}
                    color={"#274B80"}
                    loading={this.state.loading}
                />
            </div>
        );
        return (
            <div>
                <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' }}>Create</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 }}>
                            <UploadFile
                                type={this.state.uploadStatus}
                                percentage={this.state.percentage}
                                result={this.state.result}
                                acceptedFiles={["xls", "xlsx", "pdf", "PDF", "docx", "doc", "pptx", "ppt", "ods", "odf", "txt", "csv", "zip", "rar"]}
                                intent={"management"}
                                onHandle={(dt) => {
                                    this.fileHandler(dt)
                                    this.setState({ uploadStatus: 'idle', percentage: '0' })
                                }}
                                onDelete={(e) => {
                                    this.deleteFile(e)
                                }}
                                onUpload={() => alert('sukses')}
                                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.decription}
                                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="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.props.handleLoading(1) 
                                            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>
        )
    }
}
