import React, { Component } from 'react';
import { TextField, Typography, Snackbar, withStyles } from '@material-ui/core';
import * as R from 'ramda';
import api from '../../../api';
import Autocomplete from '@material-ui/lab/Autocomplete';
import { titleCase } from '../../../library/Utils';
import format from "date-fns/format";
import { DatePicker } from '@material-ui/pickers';
import Images from '../../../assets/Images';
import MuiAlert from '@material-ui/lab/Alert';
import Constant from '../../../library/Constant';
const Alert = withStyles({
})((props) => <MuiAlert elevation={6} variant="filled" {...props} />);

export default class CreateMasterDataCAT extends Component {
    constructor(props) {
        super(props)
        this.state = {
            company: null,
            parent: null,
            reportType: null,
            weight: '',
            alert: false,
            tipeAlert: '',
            messageAlert: '',
            listPeriode: null,
            periode: null,
            errorWeight: false,
            msgErrorWeight: '',
            getParent: []
        }
    }

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

    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) => {
            // console.log(response);
            if (response.data) {
                if (response.data.status === 'success') {
                    let data = response.data.data
                    let comID = this.state.rawData ? this.state.rawData.company_id : 0
                    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),
                    };
                    let index = arrayBaru.findIndex((val) => val.company_id == comID)
                    this.setState({ listCompany: defaultProps, company: arrayBaru.length < 1 ? companyData[0] : (index == -1 ? arrayBaru[0] : arrayBaru[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', listCompany: null, company: null })
            }
        })
    }

    getPeriode() {
        api.create().getPeriodeTransaction().then(response => {
            let currentYear = new Date().getFullYear()
            console.log(currentYear)
            console.log(response)
            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)
                        }
                        // } else {
                        //     if ((item >= 2000) && (item == this.state.lastPeriod || item < this.state.lastPeriod)) {
                        //         data.push(item)
                        //     }
                        // }
                    })
                    let periodeData = data.map((item) => {
                        return {
                            periode: item,
                        }
                    })
                    let defaultProps = {
                        options: periodeData,
                        getOptionLabel: (option) => option.periode,
                    };
                    // let periode = (this.state.lastPeriod == "" ? String(Number(currentYear) + 1) : this.state.lastPeriod)
                    let periode = String(Number(currentYear))
                    let index = data.sort((a, b) => a - b).findIndex((val) => val === periode)
                    // console.log(data)
                    // console.log(this.state.latestPeriode)
                    // console.log(periodeData)
                    console.log(index)
                    this.setState({ listPeriode: defaultProps, periode: index === -1 ? periodeData[0] : periodeData[index], loading: false })
                }
            }
        })
    }

    getParentIR() {
        let payload = {
            "report_id": 3,
            "years": this.state.periode.periode
        }
        api.create().getParentItemReport(payload).then(response => {
            console.log(payload)
            console.log(response)
            if (response.data) {
                if (response.data.status === "success") {
                    this.setState({ getParent: response.data.data.filter((val) => String(val.type_item_report_name).toLocaleLowerCase() != 'break')})
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
            }
        })
    }

    handleChange(e, item) {
        let dataSource = this.state.getParent
        let indexID = dataSource.findIndex((val) => val.item_report_id == item.item_report_id)
        // console.log(indexID)
        if (indexID != -1) {
            dataSource[indexID].weight = e.target.value
            this.setState({getParent: dataSource}, () => {
                console.log(this.state.getParent);
                this.clearMessage()
            })
        }
        // console.log(e.target.value)
    }

    handleReportName(item) {
        let indexString = String(item).indexOf('-')
        let gantiNama = String(item).substr(0, indexString)
        return gantiNama
    }

    validasi(getData) {
        console.log(getData)
        let jumlah = 0
        getData.map((item) => {
            jumlah += Number(item.weight)
        })
        console.log(jumlah)
        if ( jumlah > 100/100 ) {
            this.setState({ errorWeight: true, msgErrorWeight: 'Weight more than 100 %' })
        } else if (jumlah < 100/100) {
            this.setState({ errorWeight: true, msgErrorWeight: 'Weight less than 100 %' })
        }
        else {
            this.addReportItems(getData)
        }
    }

    addReportItems(getData) {
        // alert("test")
        let simpan = []
        getData.map((item) => {
            simpan.push({
                "report_id": item.report_id,
                "item_report_id": item.item_report_id,
                "weight": item.weight
            })
        })
        console.log(simpan)
        let payload = {
            "company_id": this.state.company.company_id,
            "years": this.state.periode.periode,
            "detail": simpan
        }
        console.log(payload)
        this.props.createReportItems(payload)
    }

    clearMessage() {
        this.setState({
            errorFormula: false, msgErrorFormula: '',
            errorWeight: false, msgErrorWeight: ''
        })
    }

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

    render() {

        return (
            <div className="test app-popup-show">
                <div className="popup-content background-white border-radius" style={{ borderRadius: 8, maxHeight: 600 }}>
                    <div>
                        <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 Data</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>
                    <div style={{ maxHeight: 500, overflow: 'scroll' }}>
                        <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
                            <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
                                {this.state.messageAlert}
                            </Alert>
                        </Snackbar>

                        <div className="grid grid-2x grid-mobile-none gap-15px" style={{ paddingLeft: 20, paddingRight: 20 }}>
                            <div className="column-1">
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }} >
                                    <Autocomplete
                                        {...this.state.listCompany}
                                        id="company"
                                        disabled={this.state.intent === 'Home' ? true : false}
                                        onChange={(event, newInputValue) => this.setState({ company: newInputValue, loading: true, previewTable: false }, () => {
                                            this.getParentIR()
                                        })}
                                        disableClearable
                                        style={{ width: 250 }}
                                        renderInput={(params) =>
                                            <TextField {...params}
                                                label="Company Name"
                                                InputLabelProps={{
                                                    style: {
                                                        fontSize: 11,
                                                        fontFamily: 'Nunito Sans, sans-serif',
                                                        color: '#7e8085'
                                                    }
                                                }}
                                                error={this.state.errorPerusahaan}
                                                helperText={this.state.msgErrorPerusahaan}
                                                InputProps={{ ...params.InputProps, style: { fontSize: 11, fontFamily: 'Nunito Sans, sans-serif' } }}
                                            />}
                                        value={this.state.company}
                                    />
                                </div>
                            </div>
                            <div className="column-2">
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <Autocomplete
                                        {...this.state.listPeriode}
                                        id="year"
                                        onChange={(event, newInputValue) => this.setState({ periode: newInputValue, loading: true, previewTable: false }, () => {
                                            this.getParentIR()
                                        })}
                                        disableClearable
                                        renderInput={(params) =>
                                            <TextField {...params}
                                                label="Year"
                                                InputLabelProps={{
                                                    style: {
                                                        fontSize: 11,
                                                        fontFamily: 'Nunito Sans, sans-serif',
                                                        color: '#7e8085'
                                                    }
                                                }}
                                                error={this.state.errorJenisLaporan}
                                                helperText={this.state.msgErrorJenisLaporan}
                                                InputProps={{ ...params.InputProps, style: { fontSize: 11, fontFamily: 'Nunito Sans, sans-serif' } }}
                                            />}
                                        value={this.state.periode}
                                    />
                                </div>
                            </div>
                        </div>

                        {this.state.getParent.map((item, index) => {
                            return (
                                <div>
                                    <div style={{ borderBottom: 'solid 1px #c4c4c4', margin: 20, marginBottom: 10 }} >
                                        <Typography style={{ fontSize: '12px', color: '#4b4b4b', padding: 10, fontWeight: 'bold' }}>{`Item Report - ${index + 1}`}</Typography>
                                    </div>

                                    <div className="grid grid-2x grid-mobile-none gap-15px" style={{ paddingLeft: 20, paddingRight: 20 }}>
                                        <div className="column-1">
                                            <div className="margin-top-10px" style={{ backgroundColor: '#e8e8e8', padding: 10, borderRadius: 5 }}>
                                                <TextField
                                                    style={{ width: '100%' }}
                                                    value={item.item_report_id}
                                                    id="ID"
                                                    label="ID"
                                                    disabled
                                                    inputProps={{
                                                        style: {
                                                            fontSize: 11,
                                                            fontFamily: 'Nunito Sans, sans-serif',
                                                        }
                                                    }}
                                                    InputLabelProps={{
                                                        style: {
                                                            fontSize: 11,
                                                            fontFamily: 'Nunito Sans, sans-serif',
                                                            color: '#7e8085',
                                                        }
                                                    }}
                                                />
                                            </div>
                                        </div>
                                        <div className="column-2">
                                            <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                                <TextField
                                                    style={{ width: '100%' }}
                                                    id="reportName1"
                                                    name="reportName1"
                                                    label="Report Name"
                                                    disabled
                                                    value={item.report_name}
                                                    inputProps={{
                                                        min: 0,
                                                        style: {
                                                            fontSize: 11,
                                                            fontFamily: 'Nunito Sans, sans-serif',
                                                        }
                                                    }}
                                                    InputLabelProps={{
                                                        style: {
                                                            fontSize: 11,
                                                            fontFamily: 'Nunito Sans, sans-serif',
                                                            color: '#7e8085',
                                                        }
                                                    }}
                                                >
                                                </TextField>
                                            </div>
                                        </div>
                                    </div>

                                    <div className="grid grid-2x grid-mobile-none gap-15px" style={{ paddingLeft: 20, paddingRight: 20 }}>
                                        <div className="column-1">
                                            <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                                <TextField
                                                    style={{ width: '100%' }}
                                                    id="itemReportName1"
                                                    name="itemReportName1"
                                                    label="Item Report Name"
                                                    disabled
                                                    value={this.handleReportName(item.description)}
                                                    inputProps={{
                                                        min: 0,
                                                        style: {
                                                            fontSize: 11,
                                                            fontFamily: 'Nunito Sans, sans-serif',
                                                        }
                                                    }}
                                                    InputLabelProps={{
                                                        style: {
                                                            fontSize: 11,
                                                            fontFamily: 'Nunito Sans, sans-serif',
                                                            color: '#7e8085',
                                                        }
                                                    }}
                                                >
                                                </TextField>
                                            </div>
                                        </div>
                                        <div className="column-2">
                                            <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                                <TextField
                                                    style={{ width: '100%' }}
                                                    id="weight1"
                                                    name="weight1"
                                                    label="Weight"
                                                    value={item.weight}
                                                    error={this.state.errorWeight}
                                                    helperText={this.state.msgErrorWeight}
                                                    onChange={(e) => this.handleChange(e, item)}
                                                    inputProps={{
                                                        style: {
                                                            fontSize: 11,
                                                            fontFamily: 'Nunito Sans, sans-serif',
                                                        }
                                                    }}
                                                    InputLabelProps={{
                                                        style: {
                                                            fontSize: 11,
                                                            fontFamily: 'Nunito Sans, sans-serif',
                                                            color: '#7e8085',
                                                        }
                                                    }}
                                                >
                                                </TextField>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )
                        })}

                        <div className="grid grid-2x grid-mobile-none gap-15px" style={{ paddingLeft: 20, paddingRight: 20 }}>
                            <div className="column-1">
                                <div className="margin-top-10px" style={{ backgroundColor: '#e8e8e8', padding: 10, borderRadius: 5 }}>
                                    <TextField
                                        style={{ width: '100%' }}
                                        defaultValue={"active"}
                                        id="status"
                                        label="Status"
                                        disabled
                                        inputProps={{
                                            style: {
                                                fontSize: 11,
                                                fontFamily: 'Nunito Sans, sans-serif',
                                            }
                                        }}
                                        InputLabelProps={{
                                            style: {
                                                fontSize: 11,
                                                fontFamily: 'Nunito Sans, sans-serif',
                                                color: '#7e8085',
                                            }
                                        }}
                                    />
                                </div>
                            </div>
                        </div>

                        <div className="margin-top-10px" style={{ paddingTop: 10, paddingBottom: 30, paddingRight: 30, paddingLeft: 30 }}>
                            <div style={{ display: 'flex' }}>
                                <Typography style={{ fontSize: 11, width: '13%' }}>Created By :</Typography>
                            </div>
                            <div style={{ display: 'flex' }}>
                                <Typography style={{ fontSize: 11, width: '13%' }}>Updated By :</Typography>
                            </div>
                        </div>
                    </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.validasi(this.state.getParent)}
                                >
                                    <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>
                </div>
            </div>
        )
    }
}
