<template>
    <div>
        <el-alert type="error" title="ERROR"
            :description="error.message + '\n' + error.file + ':' + error.line"
            v-show="error.message"
            style="margin-bottom:15px;">
        </el-alert>

        <form @submit.prevent="update">
            <div class="form-group text-center">
                <input type="hidden" v-model="formData.document">
                <el-upload :action="api_url + '/contract/upload?contract_id=' + formData.id + '&api_token=' + api_token"
                    ref="upload"
                    :on-success="updateSignedDocument"
                    :multiple="false" :limit="1">
                    <el-button type="primary">Click to upload signed document</el-button>
                </el-upload>
                <div class="error-feedback" v-if="formErrors.document">{{formErrors.document[0]}}</div>
            </div>
            <br>
            <div class="form-group text-center">
                <button class="btn btn-secondary" @click.prevent="closeDialog"><i class="el-icon-close"></i> CANCEL</button>
            </div>
        </form>
    </div>
</template>

<script>
export default {
    props: ['data'],
    computed: {
        formData() {
            return this.data
        }
    },
    data: function() {
        return {
            api_url: API_URL,
            api_token: USER.api_token,
            error: {},
            formErrors: []
        }
    },
    methods: {
        closeDialog: function() {
            this.error = {};
            this.formErrors = [];
            if (this.$refs.upload) {
                this.$refs.upload.clearFiles();
            }
            this.$emit('close-dialog')
        },
        updateSignedDocument: function(response, file, fileList) {
            if (response.success) {
                this.$message({
                    message: response.message,
                    type: 'success'
                });
                this.formData.document = response.file;
                this.formErrors.document = null;
                this.closeDialog()
            } else {
                this.$message({
                    message: response.message,
                    type: 'error'
                });
                this.formErrors.document = [response.message];
            }

            this.$forceUpdate();
        },
        onProgressUpload: function() {
            this.$store.state.loading = true;
        }
    }
}
</script>

<style lang="css">
</style>
