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

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

    componentDidMount() {
        this.getInputType()
        this.getReportType()
        let date = format(new Date, 'yyyy-MM-dd')
        this.setState({
            startDate: date,
            endDate: date
        })
        this.getPeriode()
        this.getDetailUser()
        this.getDetailMasterDataCat()
    }

    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.props.data[8]
                    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 == this.props.data[6])
                    // console.log(this.props.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()
            })
        }
    }

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

    validasi(getData) {
        console.log(getData)
        let jumlah = 0
        getData.map((item) => {
            jumlah += Number(item.weight)
        })
        console.log(fixNumber(jumlah,3))
        if ( fixNumber(jumlah,3) > 100/100 ) {
            this.setState({ errorWeight: true, msgErrorWeight: 'Weight more than 100%' })
        } else if (fixNumber(jumlah,3) < 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,
            "company_old": this.props.data[8],
            "years": this.state.periode.periode,
            "detail": simpan
        }
        console.log(payload)
        this.props.updateReportItems(payload)
    }


    getInputType() {
        api.create().getInputType().then((response) => {
            // console.log(response.data)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === 'success') {
                        let data = response.data.data
                        let inputData = data.map((item) => {
                            return {
                                type_item_report_id: item.type_item_report_id,
                                type_item_report_name: item.type_item_report_name
                            }
                        })
                        let defaultProps = {
                            options: inputData,
                            getOptionLabel: (option) => titleCase(option.type_item_report_name),
                        };
                        this.setState({ listInputType: defaultProps, inputData: 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);
                            }
                        })
                        // alert(response.data.message)
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    getReportType() {
        api.create().getReportType().then((response) => {
            // console.log(response)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === 'success') {
                        let data = response.data.data
                        let reportTypeData = data.map((item) => {
                            return {
                                report_id: item.report_id,
                                report_name: item.report_name,
                            }
                        })
                        let defaultProps = {
                            options: reportTypeData,
                            getOptionLabel: (option) => titleCase(option.report_name),
                        };
                        this.setState({ listReportType: defaultProps, reportTypeData: response.data.data })
                    } else {
                        // alert(response.data.message)
                        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.data.message, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    handleDate(item) {
        let value = format(item, 'dd MMMM yyyy')
        return value
    }

    getDetailMasterDataCat() {
        this.setState({ loading: true })
        api.create().getDetailMasterDataCat(this.props.data[8], this.props.data[6]).then((response) => {
            // 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'), created_by: response.data.data[0].created, updated_by: response.data.data[0].updated }, () => {
                        // console.log(this.state.getParent[0].created);
                        this.setState({ loading: false })
                    })
                } else {
                    // alert(response.data.message)
                    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' })
            }
        })
    }

    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' }}>Edit 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"
                                        onChange={(event, newInputValue) => this.setState({ company: newInputValue }, () => this.getParentIR(), this.clearMessage())}
                                        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
                                                    // onChange={(e) => this.handleChange(e, null)}
                                                    // value={this.state.order}
                                                    value={this.handleReportName(item.item_report_name)}
                                                    // error={this.state.errorOrder}
                                                    // helperText={this.state.msgErrorOrder}
                                                    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>
                                {!this.state.loading && <Typography style={{ fontSize: 11 }}>:  {this.state.created_by}</Typography>}
                            </div>
                            <div style={{ display: 'flex' }}>
                                <Typography style={{ fontSize: 11, width: '13%' }}>Updated By</Typography>
                                {!this.state.loading && <Typography style={{ fontSize: 11 }}>:  {this.state.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>
        )
    }
}
