<template>
    <div>
        <notification-component ref="notification"></notification-component>
        <loading-component  v-show="isLoading"></loading-component>
        <div class="row m-t-20" v-show="!isEdit">
            <div class="col">
                <div class="b-l b-success p-l-15 m-b-15" style="border-left-width: 3px;">
                    <h6 class="bold all-caps no-margin text-success">New Company</h6>
                    <div class="muted all-caps fs-12">Create A New Company</div>
                </div>
            </div>
        </div>
        <form @submit.prevent="updateCompany">
            <div class="row">
                <div class="col no-padding">
                    <div class="form-group form-group-default required">
                        <label class="muted">Marking</label>
                        <input class="form-control" name="marking" v-model="company.marking" autocomplete="off">
                    </div>
                    <div class="form-group form-group-default required">
                        <label class="muted">Company Name</label>
                        <input class="form-control" name="name" v-model="company.name" autocomplete="off">
                    </div>
                    <div class="form-group form-group-default required">
                        <label class="muted">Email Address</label>
                        <input class="form-control" name="email" v-model="company.email" autocomplete="off">
                    </div>
                    <div class="row">
                        <div class="col p-l-0">
                            <div class="form-group form-group-default required">
                                <label class="muted">Registration Number</label>
                                <input class="form-control" name="registration_no"  v-model="company.registration_no" autocomplete="off">
                            </div>
                        </div>
                        <div class="col p-r-0">
                            <div class="form-group form-group-default required">
                                <label class="muted">Tax Number</label>
                                <input class="form-control" name="tax_no" v-model="company.tax_no" autocomplete="off">
                            </div>
                        </div>
                    </div>
                    <address-component v-on:changeAddress="updateAddress($event)" ref="address" :data="address()"></address-component>
                    <div class="form-group form-group-default required">
                        <label class="muted">Registration Certificate</label>
                        <file-selector v-on:changeFile="updateRegistrationCertificate($event)" ref="fileUpload" :data="files()" multiple></file-selector>
                    </div>
                    <div class="row">
                        <div class="col text-right no-padding">
                            <div v-show="!isEdit">
                                <button class="btn b-rad-none btn-success">Add Company</button>
                            </div>
                            <div v-show="isEdit">
                                <button class="btn b-rad-none btn-success" data-dismiss="modal" >Save Changes</button>
                                <button type="button" class="btn b-rad-none btn-default" @click="collapseEdit()">Cancel</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</template>
<script>
    import notificationConstant from '../../../../js/notification';
    export default {
        props: {
            'data': {
                type: Object,
                default: null
            }
        },
        data() {
            return {
                company: {
                    id: '',
                    name: '',
                    marking: '',
                    email: '',
                    registration_no: '',
                    tax_no: '',
                    street_one: '',
                    street_two: '',
                    city: '',
                    state: '',
                    post_code: '',
                    country: '',
                    registration_certificate: ''
                },
				isLoading: false,
                isEdit: false
            }
        },
        created() {
            if(this.data !== null){
                this.isEdit = true;
                this.company = this.data;
            }

        },
        mounted: function() {
            $(this.$el).find('form').validate({
                rules: {
                    marking: "required",
                    name: "required",
                    email: {
                        required: true,
                        isEmail: this
                    },
                    registration_no: "required",
                    tax_no: "required",
                    street_one: "required",
                    city: "required",
                    state: "required",
                    post_code: "required",
                },
                messages: {
                    marking: 'The marking field is required',
                    email: {
                        required: "The email address field is required",
                        isEmail: "Enter a valid email address"
                    },
                    password: "The password field is required"
                },
                errorPlacement: function ( error, element ) {

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

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

                    var url = this.isEdit ? route('api.company.update', {id: this.company.id}) : route('api.company.create'),
                        method = this.isEdit ? 'put' : 'post';

                    fetch(url, {
                        method: method,
                        body: JSON.stringify(this.company),
                        headers: {
                            'content-type': 'application/json'
                        }
                    }).then((response) => {
                        let notification = this.$refs.notification;
                        if(!this.isEdit){
                            Event.$emit('updateCompanyList');
                            this.clearForm();
                            notification.title = notificationConstant.IMPORTER.DETAILS.CREATED.TITLE;
                            notification.message = notificationConstant.IMPORTER.DETAILS.CREATED.MESSAGE;
                        }
                        else {
                            notification.title = notificationConstant.IMPORTER.DETAILS.UPDATED.MESSAGE;
                            notification.message = notificationConstant.IMPORTER.DETAILS.UPDATED.MESSAGE;
                        }
                        notification.execute();

                        //turn off loading animation
                        this.isLoading = false;
                        $('.modal').modal('hide');
                        this.collapseEdit();
                    })
                }

            },
			updateRegistrationCertificate(files){
				this.company.registration_certificate = files;
				this.$emit('updateLayout');
			},
            updateAddress(address){
                this.company.street_one = address.street_one;
                this.company.street_two = address.street_two;
                this.company.city = address.city;
                this.company.state = address.state;
                this.company.post_code = address.post_code;
                this.company.country = address.country;
            },
            collapseEdit(){
                this.$emit('collapseEdit');
            },
            address(){
                return {
                    street_one: this.company.street_one,
                    street_two: this.company.street_two,
                    city: this.company.city,
                    state: this.company.state,
                    post_code: this.company.post_code,
                    country: this.company.country
                };
            },
            files(){
                return $.map(this.company.registration_certificate, function(obj){
                    return {
                        name: obj.name,
                        location: 'uploads/registration_certificates'
                    }
                });
            },
            clearForm(){
                this.company = {
                    id: '',
                    name: '',
                    email: '',
                    registration_no: '',
                    tax_no: '',
                    street_one: '',
                    street_two: '',
                    city: '',
                    state: '',
                    post_code: '',
                    country: '',
                    registration_certificate: ''
                };

                this.$refs.address.resetAddress();
                this.$refs.fileUpload.removeFile();
            }
        }
    }
</script>