<template>
    <div class="card card-default no-border">
        <notification-component ref="notification"></notification-component>
        <loading-component  v-show="isLoading"></loading-component>
        <div class="card-block no-padding">
            <div class="row p-t-30">
                <div class="col no-padding">
                    <div class="b-l b-primary p-l-15 m-b-15" style="border-left-width: 3px;">
                        <h6 class="bold all-caps no-margin text-primary">New Order</h6>
                        <div class="muted all-caps fs-12">Create A New Order</div>
                    </div>
                </div>
            </div>
            <form method="post">
                <div class="row">
                    <div class="col no-padding">
                        <div class="form-group form-group-default input-group">
                            <div class="row w-100">
                                <div class="col no-padding">
                                    <label class="muted block">Order No.</label>
                                    <input class="form-control block" name="marking" v-model="order.marking">
                                </div>
                                <div class="col-auto no-padding" @click="generateMarking()">
                                    <div class="input-group-addon pointer inline">
                                        <div class="row align-items-center justify-content-center h-100">
                                            <div class="col">
                                                <i class="fa fa-random text-success"></i>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row m-b-10">
                            <div class="col no-padding">
                                <div class="row m-b-10"  v-show="this.showWarehouse">
                                    <div class="col no-padding">
                                        <div class="form-group form-group-default form-group-default-select2 b-rad-none m-b-0" >
                                            <label class="muted" style="z-index: 10000;">Warehouse</label>
                                            <select-component  :options="this.warehouses" name="warehouse_id"  v-model="order.warehouse_id"></select-component>
                                        </div>
                                    </div>
                                    <div class="col-auto padding-5 bg-master-lighter pointer hide" @click="showWarehouse = !showWarehouse; order.warehouse_id = null">
                                        <div class="row align-items-center justify-content-center h-100">
                                            <div class="col">
                                                <i class="fa fa-times text-danger m-l-5 m-r-5"></i>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <action-date-component v-model="complete_date"></action-date-component>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col text-right no-padding">
                                <div class="row">
                                    <div class="col no-padding">
                                        <button class="btn b-rad-none btn-default" data-dismiss="modal">Cancel</button>
                                        <button type="button" class="btn b-rad-none btn-primary" @click="addOrder()">Create Order</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</template>
<script>
    import notificationConstant from '../../../../js/notification';
    export default {
        props: {
            'data': {
                type: String,
                required: true
            }
        },
        data() {
            return {
                order: {
                    marking: '',
                    name: '',
                    warehouse_id: null
                },
                complete_date: null,
                warehouses: [],
                showWarehouse: true,
                showCompleteDate: false,
                isLoading: false
            }
        },

        mounted: function() {
            $(this.$el).find('form').validate({
                rules: {
                    marking: "required",
                    warehouse_id: "required"
                },
                errorPlacement: function ( error, element ) {

                    if(element.parents('.form-group').hasClass('form-group')){
                        error.insertAfter( element.parents('.form-group') );
                    } else {
                        error.insertAfter( element );
                    }

                },
                highlight: function(element) {
                    $(element).parents(".form-group").addClass('has-error');
                },
                unhighlight: function(element) {
                    $(element).parents(".form-group").removeClass('has-error')
                }
            })
        },
        created() {
            this.generateMarking();
            this.fetchWarehouses();
        },
        methods: {
            fetchWarehouses(){
                //turn on loading animation
                this.isLoading = true;

                fetch(route('api.warehouse.list', {'all': true})).then(response => response.json())
                    .then(response => {

                        this.warehouses = $.map(response.data, function(value){
                            return {'id': value.id, 'text': value.name};
                        });

                        //turn off loading animation
                        this.isLoading = false;

                    })
                    .catch(error => console.log(error))
            },
            addOrder() {
                if($(this.$el).find('form').valid()) {
                    let notification = this.$refs.notification;
                    //turn on loading animation
                    this.isLoading = true;
                    fetch(route('api.order.create', {companyId: this.data}), {
                        method: 'post',
                        responseType: 'json',
                        body: JSON.stringify(this.order),
                        headers: {
                            'content-type': 'application/json'
                        }
                    }).then(response => {
                        $('.modal').modal('hide');
                        this.clearForm();
                        //turn off loading animation
                        this.isLoading = false;
                        if(!response.ok){ throw response }

                    }).then( () => {
                        notification.title = notificationConstant.ORDER.CREATED.TITLE;
                        notification.message = notificationConstant.ORDER.CREATED.MESSAGE;

                        notification.execute();

                        Event.$emit('updateOrdersList');
                    }).catch(error => {
                        error.json().then( error => {
                            notification.type = 'error';
                            notification.title = notificationConstant.ORDER.CREATED.TITLE;
                            notification.message = error.message;
                            notification.execute();
                        })
                    })
                }
            },
            generateMarking(){
                this.order.marking = Math.floor(Math.random() * 79999999) + 20000000;
            },
            clearForm(){
                this.generateMarking();
                this.order.warehouse_id = null;
                this.complete_date = null;
                this.showCompleteDate = false;
            }
        }
    }
</script>