import React, { Component } from 'react';
import { TextField, Typography } from '@material-ui/core';
import { DateTimePicker, KeyboardDatePicker, DatePicker} from "@material-ui/pickers";
import Autocomplete from '@material-ui/lab/Autocomplete';
import * as R from 'ramda'
import format from "date-fns/format";
import api from "../../api";

const operator = [
  {
    value: '-',
    label: '-',
  },
  {
    value: 'AND',
    label: 'AND',
  },
  {
    value: 'OR',
    label: 'OR',
  },
];
export default class EditApprovalMatrix extends Component {
    constructor(props) {
        super(props)
        this.state = {
            id: '',
            order: '',
            startDate: null,
            endDate: null,
            date: new Date(),
            approvedBy: null,
            getApprovedBy: null,
            types: null,
            getTypes: null,
            operators: null,
            getOperators: null
        }
    }

    componentDidMount() {
        if (this.props.type === 'edit') {
            let data = this.props.data
            // let getApprovedBy = {
            //     user_id: data.user_id,
            //     fullname: data.fullname
            // }
            this.setState({
                id: data.approval_matrix_id,
                startDate: data.start_date,
                endDate: data.end_date,
                order: data.orders,
                getUserId: data.user_id,
                getTypeId: data.approval_type_id,
                getOperatorId: data.operator_type_id,

            }, () => this.getUserData(), this.getTypeData(), this.getOperatorData())
        }
        // console.log(this.props.data)
    }

    getUserData() {
        api.create().getApprovedByAM().then((response) => {
            if (response.data.status == 'success') {
                let data = response.data.data
                let userData = data.map((item) => {
                    return {
                        user_id: item.user_id,
                        fullname: item.fullname
                    }
                })
                let index = userData.findIndex((val) => val.user_id == this.state.getUserId)
                let defaultProps = {
                    options: userData,
                    getOptionLabel: (option) => option.fullname,
                  };
                this.setState({ approvedBy: defaultProps, userData: response.data.data, getApprovedBy: index == -1 ? userData[0]: userData[index] })
            } else {
                alert(response.data.message)
            }
        })
    }

    getOperatorData() {
        api.create().getOperatorAM().then((response) => {
            if (response.data.status == 'success') {
                let data = response.data.data
                let operatorData = data.map((item) => {
                    return {
                        operator_type_id: item.operator_type_id,
                        operator_type_name: item.operator_type_name
                    }
                })
                let index = operatorData.findIndex((val) => val.operator_type_id == this.state.getOperatorId)
                let operatorProps = {
                    options: operatorData,
                    getOptionLabel: (option) => option.operator_type_name,
                  };
                this.setState({ operators: operatorProps, operatorData: response.data.data, getOperators: index == -1 ? operatorData[0]: operatorData[index] })
            } else {
                alert(response.data.message)
            }
        })
    }

    getTypeData() {
        api.create().getTypeAM().then((response) => {
            if (response.data.status == 'success') {
                let data = response.data.data
                let typeData = data.map((item) => {
                    return {
                        approval_type_id: item.approval_type_id,
                        approval_type_name: item.approval_type_name
                    }
                })
                let index = typeData.findIndex((val) => val.approval_type_id == this.state.getTypeId)
                let typeProps = {
                    options: typeData,
                    getOptionLabel: (option) => option.approval_type_name,
                  };
                this.setState({ types: typeProps, typeData: response.data.data, getTypes: index == -1 ? typeData[0]: typeData[index] })
            } else {
                alert(response.data.message)
            }
        })
    }


    handleChange(e, type) {
        let data = this.state
        let isDate = type !== '' ? true : false
        if (isDate && type == 'start_date') {
            this.setState({ startDate: format(e, 'yyyy-MM-dd') }, () => {
                // console.log(this.state.startDate)
            })
        } else if (isDate && type == 'end_date') {
            this.setState({ endDate: format(e, 'yyyy-MM-dd') }, () => {
                // console.log(this.state.endDate)
            })
        } else {
            // this.setState({...data, tempData: {...this.state.tempData, [e.target.name] :  e.target.value}})
        }

    }

    validasi() {
        if (R.isNil(this.state.getTypeId)) return alert("Tipe Persetujuan is Required.");
        if (R.isEmpty(this.state.order)) return alert("Order is Required.");
        if (R.isNil(this.state.getUserId)) return alert("Pemberi Persetujuan is Required.");
        if (R.isNil(this.state.getOperatorId)) return alert("Operator is Required.");
        if (!R.isEmpty(this.state.startDate) && !R.isEmpty(this.state.endDate) && (this.state.startDate > this.state.endDate)) return alert("Masa Berlaku Tidak Boleh Kurang Dari Tanggal Mulai");
        if (R.isEmpty(this.state.startDate)) return alert("Tanggal Mulai is Required.");
        if (R.isEmpty(this.state.endDate)) return alert("Tanggal Berakhir is Required.");
        console.log('masuk');
        if (this.props.type == 'edit') {
        let payload = {
                "approval_matrix_id": this.state.id,
                "approval_type_id": this.state.getTypes.approval_type_id,
                "orders": this.state.order,
                "user_id": this.state.getApprovedBy.user_id,
                "operator_type_id": this.state.getOperators.operator_type_id,
                "start_date": this.state.startDate,
                "end_date": this.state.endDate
            }
            this.props.updateAM(payload)
        }
        // console.log(payload)

    }

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

    render() {
        return (
            <div className="test app-popup-show" style={{ paddingTop: 100 }}>
                <div className="popup-content background-white border-radius" style={{ borderRadius: 8 }}>
                    <div className="popup-panel grid grid-2x" style={{ backgroundColor: '#51c6ea', 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()}
                            >
                                <i className="fa fa-lg fa-times" style={{ color: 'white' }} />
                            </button>
                        </div>
                    </div>

                    <div className="border-bottom" style={{ padding: 20 }}>
                        <div className="grid grid-2x grid-mobile-none gap-15px">
                            <div className="column-1">
                                <div style={{ backgroundColor: '#e8e8e8', padding: 10, borderRadius: 5 }}>
                                    <TextField
                                        style={{ width: '100%' }}
                                        id="id"
                                        label="ID"
                                        value={this.props.data.approval_matrix_id}
                                        disabled
                                        inputProps={{
                                            style: {
                                                fontSize: 11
                                            }
                                        }}
                                        InputLabelProps={{
                                            style: {
                                                fontSize: 11,
                                                color: '#7e8085'
                                            }
                                        }}
                                    />
                                </div>
                            </div>
                            <div className="column-2">
                                <div className="" style={{ padding: 10, borderRadius: 5 }}>
                                    <Autocomplete
                                        {...this.state.types}
                                        option
                                        disableClearable
                                        id="tipe"
                                        onChange={(event, newInputValue) => this.setState({getTypes:newInputValue})}
                                        renderInput={(params) => <TextField {...params} label="Tipe Persetujuan" />}
                                        value={this.state.getTypes}
                                    />
                                </div>
                            </div>
                        </div>
                        <div className="grid grid-2x grid-mobile-none gap-15px">
                            <div className="column-1">
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <TextField
                                        style={{ width: '100%' }}
                                        id="order"
                                        label="Order"
                                        value={this.state.order}
                                        onChange={(e) => this.setState({ order: e.target.value })}
                                        inputProps={{
                                            style: {
                                                fontSize: 11
                                            }
                                        }}
                                        InputLabelProps={{
                                            style: {
                                                fontSize: 11,
                                                color: '#7e8085'
                                            }
                                        }}
                                    >
                                    </TextField>
                                </div>
                            </div>
                            <div className="column-2">
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <Autocomplete
                                        {...this.state.approvedBy}
                                        option
                                        disableClearable
                                        id="approvedby"
                                        onChange={(event, newInputValue) => this.setState({getApprovedBy: newInputValue})}
                                        renderInput={(params) => <TextField {...params} label="Pemberi Persetujuan" />}
                                        value={this.state.getApprovedBy}
                                    />
                                </div>
                            </div>
                        </div>
                        <div className="grid grid-2x grid-mobile-none gap-15px">
                            <div className="column-1">
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <Autocomplete
                                        {...this.state.operators}
                                        option
                                        disableClearable
                                        id="operator"
                                        onChange={(event, newInputValue) => this.setState({getOperators: newInputValue})}
                                        renderInput={(params) => <TextField {...params} label="Operator" />}
                                        value={this.state.getOperators}
                                    />
                                </div>
                            </div>
                            <div className="column-2">
                                
                            </div>
                        </div>
                        <div className="grid grid-2x grid-mobile-none gap-15px">
                            <div className="column-1">
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <DatePicker
                                        margin="normal"
                                        id="startDate"
                                        label="Berlaku Mulai"
                                        format="dd MMMM yyyy"
                                        value={this.state.startDate}
                                        onChange={(e) => this.handleChange(e, 'start_date')}
                                        KeyboardButtonProps={{
                                            'aria-label': 'change date',
                                        }}
                                        inputProps={{
                                            style: {
                                                fontSize: 11
                                            }
                                        }}
                                        InputLabelProps={{
                                            style: {
                                                fontSize: 11,
                                                color: '#7e8085'
                                            }
                                        }}
                                        style={{padding: 0, margin: 0, width: '100%'}}
                                    />
                                </div>
                            </div>
                            <div className="column-2">
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <DatePicker
                                        margin="normal"
                                        id="endDate"
                                        label="Berlaku Hingga"
                                        format="dd MMMM yyyy"
                                        value={this.state.endDate}
                                        onChange={(e) => this.handleChange(e, 'end_date')}
                                        KeyboardButtonProps={{
                                            'aria-label': 'change date',
                                        }}
                                        inputProps={{
                                            style: {
                                                fontSize: 11
                                            }
                                        }}
                                        InputLabelProps={{
                                            style: {
                                                fontSize: 11,
                                                color: '#7e8085'
                                            }
                                        }}
                                        style={{padding: 0, margin: 0, width: '100%'}}
                                        />
                                </div>
                            </div>
                        </div>
                        <div className="grid grid-2x grid-mobile-none gap-15px">
                            <div className="column-1">
                                <div className="margin-top-10px" style={{ backgroundColor: '#e8e8e8', padding: 10, borderRadius: 5 }}>
                                    <TextField
                                        style={{ width: '100%' }}
                                        id="status"
                                        label="Status"
                                        value={this.props.data.status}
                                        disabled
                                        inputProps={{
                                            style: {
                                                fontSize: 11
                                            }
                                        }}
                                        InputLabelProps={{
                                            style: {
                                                fontSize: 11,
                                                color: '#7e8085'
                                            }
                                        }}
                                    >
                                    </TextField>
                                </div>
                            </div>
                            <div className="column-2">
                                {/* <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <TextField
                                        style={{ width: '100%' }}
                                        id="max-value"
                                        label="Max Value"
                                        value="10"
                                        onChange={(e) => this.handleChange(e, '')}
                                        inputProps={{
                                            style: {
                                                fontSize: 11
                                            }
                                        }}
                                        InputLabelProps={{
                                            style: {
                                                fontSize: 11,
                                                color: '#7e8085'
                                            }
                                        }}
                                    >
                                    </TextField>
                                </div> */}
                            </div>
                        </div>
                        <div className="margin-top-10px" style={{ padding: 10, paddingLeft: 0, borderRadius: 5 }}>
                            <div style={{ display: 'flex' }}>
                                <Typography style={{ fontSize: 11, width: '20%' }}>Dibuat</Typography>
                                <Typography style={{ fontSize: 11 }}>: {this.props.data.created}</Typography>
                            </div>
                            <div style={{ display: 'flex' }}>
                                <Typography style={{ fontSize: 11, width: '20%' }}>Diubah</Typography>
                                <Typography style={{ fontSize: 11 }}>: {this.props.data.updated == - null ? "" : this.props.data.updated}</Typography>
                            </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' }}>
                            <div onClick={() => this.props.onClickClose()} style={{ width: 102, height: 30, border: 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center', cursor:"pointer" }}>
                                <span style={{ color: '#354960', fontSize: 11 }} >Batal</span>
                            </div>
                        </div>
                        <div className="column-2" style={{display: 'flex', justifyContent: 'flex-end', alignItems: 'center'}}>
                            <div onClick={() => this.validasi()} style={{ width: 102, height: 30, backgroundColor: '#354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center', cursor:"pointer" }}>
                                <span style={{ color: '#fff', fontSize: 11 }}>Simpan</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}
