<template lang="html">
    <form @submit.prevent="formData.id == undefined ? store : update">
        <el-alert type="error" title="ERROR"
            :description="error.message + '\n' + error.file + ':' + error.line"
            v-show="error.message"
            style="margin-bottom:15px;">
        </el-alert>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Partners</label>
                    <div class="col-md-8">
                        <el-select filterable placeholder="Partners" v-model="formData.partners" style="width:100%;" multiple filterable allow-create default-first-option>
                            <el-option :value="p.id" :label="p.name" v-for="p in partners" :key="p.id"></el-option>
                        </el-select>
                        <div class="error-feedback" v-if="formErrors.partners">{{formErrors.partners[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Contract Type</label>
                    <div class="col-md-8">
                        <el-select :disabled="formData.id !== undefined" placeholder="Contract Type" v-model="formData.type" style="width:100%;">
                            <el-option :value="0" label="New"></el-option>
                            <el-option :value="1" label="Amandement"></el-option>
                        </el-select>
                        <div class="error-feedback" v-if="formErrors.type">{{formErrors.type[0]}}</div>
                    </div>
                </div>

                <div v-show="formData.type == 1" class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Main Agreement</label>
                    <div class="col-md-8">
                        <el-select placeholder="Main Agreement" v-model="formData.main_agreement" style="width:100%;" filterable default-first-option allow-create>
                            <el-option :value="p.number" :label="p.number" v-for="p in parentContracts" :key="p.id"></el-option>
                        </el-select>
                    </div>
                </div>

                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Creator</label>
                    <div class="col-md-8">
                        <el-input v-model="formData.user" disabled></el-input>
                    </div>
                </div>

                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Creation Date</label>
                    <div class="col-md-8">
                        <el-date-picker v-model="formData.creation_date" type="date" value-format="yyyy-MM-dd" placeholder="Creation Date" style="width:100%;"> </el-date-picker>
                        <div class="error-feedback" v-if="formErrors.creation_date">{{formErrors.creation_date[0]}}</div>
                    </div>
                </div>

                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Subject</label>
                    <div class="col-md-8">
                        <el-input placeholder="Subject" v-model="formData.subject"></el-input>
                        <div class="error-feedback" v-if="formErrors.subject">{{formErrors.subject[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Unit Request</label>
                    <div class="col-md-8">
                        <el-select placeholder="Unit Request" v-model="formData.unit_id" style="width:100%;" filterable default-first-option>
                            <el-option :value="u.id" :label="u.department" v-for="u in units" :key="u.id"></el-option>
                        </el-select>
                        <div class="error-feedback" v-if="formErrors.unit_id">{{formErrors.unit_id[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Unit Approver</label>
                    <div class="col-md-8">
                        <el-select placeholder="Unit Approver" v-model="formData.unit_approver" style="width:100%;" filterable default-first-option>
                            <el-option :value="u.department" :label="u.department" v-for="u in units" :key="u.id"></el-option>
                        </el-select>
                        <div class="error-feedback" v-if="formErrors.unit_approver">{{formErrors.unit_approver[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Distribute To</label>
                    <div class="col-md-8">
                        <el-select placeholder="Unit" v-model="formData.distributions" style="width:100%;" multiple filterable default-first-option>
                            <el-option :value="u.id" :label="u.department" v-for="u in units" :key="u.id"></el-option>
                        </el-select>
                        <div class="error-feedback" v-if="formErrors.distributions">{{formErrors.distributions[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Intern Office Receipt Date</label>
                    <div class="col-md-8">
                        <el-date-picker value-format="yyyy-MM-dd" v-model="formData.intern_office_receipt_date" type="date" placeholder="Intern Office Receipt Date" style="width:100%;"> </el-date-picker>
                        <div class="error-feedback" v-if="formErrors.intern_office_receipt_date">{{formErrors.intern_office_receipt_date[0]}}</div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Sign Off Date</label>
                    <div class="col-md-8">
                        <el-date-picker v-model="formData.doc_signed_date" type="date" value-format="yyyy-MM-dd" placeholder="Doc. Signed Date" style="width:100%;"> </el-date-picker>
                        <div class="error-feedback" v-if="formErrors.doc_signed_date">{{formErrors.doc_signed_date[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Document Type</label>
                    <div class="col-md-8">
                        <el-select placeholder="Document Type" v-model="formData.document_type" style="width:100%">
                            <el-option :value="'PERJ.'" label="PERJANJIAN"></el-option>
                            <el-option :value="'MOU'" label="MOU"></el-option>
                        </el-select>
                        <div class="error-feedback" v-if="formErrors.document_type">{{formErrors.document_type[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Contract Number</label>
                    <div class="col-md-8">
                        <el-input placeholder="Prefix" disabled style="width:170px" v-model="formData.prefix_number"></el-input>
                        <el-input placeholder="Number" style="width:226px" v-model="formData.number"></el-input>
                        <div class="error-feedback" v-if="formErrors.number">{{formErrors.number[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Contract Start</label>
                    <div class="col-md-8">
                        <el-date-picker v-model="formData.start" type="date" value-format="yyyy-MM-dd" placeholder="Contract Start" style="width:100%;"> </el-date-picker>
                        <div class="error-feedback" v-if="formErrors.start">{{formErrors.start[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Contract End</label>
                    <div class="col-md-8">
                        <el-date-picker v-model="formData.end" type="date" value-format="yyyy-MM-dd" placeholder="Contract End" :disabled="formData.all_obligation_complete" style="width:170px;margin-right:5px;"> </el-date-picker>
                        <el-checkbox v-model="formData.all_obligation_complete" style="margin-top:8px;">All Obligation Complete</el-checkbox>
                        <div class="error-feedback" v-if="formErrors.end">{{formErrors.end[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Agreement Period</label>
                    <div class="col-md-8">
                        <input type="text" class="form-control" placeholder="Agreement Period" v-model="formData.agreement_period" disabled>
                    </div>
                </div>
                <div class="form-group row" v-if="formData.id == undefined">
                    <label class="col-md-4 col-form-label col-form-label-md">Template</label>
                    <div class="col-md-8">
                        <input type="hidden" v-model="formData.template">
                        <el-upload :action="base_url + '/contractRevision/upload'"
                            ref="upload"
                            :on-success="updateTemplate"
                            :multiple="false" :limit="1">
                            <el-button size="small" type="primary">Click to upload file</el-button>
                        </el-upload>
                        <div class="error-feedback" v-if="formErrors.template">{{formErrors.template[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Remark</label>
                    <div class="col-md-8">
                        <textarea rows="3" class="form-control" placeholder="Remark" v-model="formData.remark"></textarea>
                        <div class="error-feedback" v-if="formErrors.remark">{{formErrors.remark[0]}}</div>
                    </div>
                </div>
                <div class="form-group row" v-if="formData.id != undefined">
                    <label class="col-md-4 col-form-label col-form-label-md">Status</label>
                    <div class="col-md-8">
                        <el-select placeholder="Contract Type" v-model="formData.status" style="width:100%;">
                            <el-option :value="0" label="Draft"></el-option>
                            <el-option :value="1" label="Final"></el-option>
                            <el-option :value="2" label="Finish"></el-option>
                            <el-option :value="3" label="Void"></el-option>
                        </el-select>
                        <div class="error-feedback" v-if="formErrors.status">{{formErrors.status[0]}}</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="form-group text-right">
            <button class="btn btn-primary" type="submit" @click.prevent="store" v-if="formData.id == undefined"><i class="el-icon-check"></i> SAVE</button>
            <button class="btn btn-primary" type="submit" @click.prevent="update" v-if="formData.id != undefined"><i class="el-icon-check"></i> SAVE</button>
            <button class="btn btn-secondary" @click.prevent="closeDialog"><i class="el-icon-close"></i> CANCEL</button>
        </div>
    </form>
</template>

<script>
import moment from 'moment'

export default {
    props: ['data'],
    computed: {
        partners() {
            return this.$store.state.partners
        },
        units() {
            return this.$store.state.units
        },
        formData() {
            return this.data
        }
    },
    data: function() {
        return {
            base_url: BASE_URL,
            parentContracts: [],
            formErrors: {},
            error: {}
        }
    },
    watch: {
        'formData.all_obligation_complete': function(v, o) {
            this.formData.end = '';
            this.formData.agreement_period = '';
        },
        'formData.end': function(v, o) {
            if (v) {
                var start = moment(this.formData.start);
                var end = moment(this.formData.end);
                var duration = moment.duration(end.diff(start));
                var days = duration.asDays();
                this.formData.agreement_period = Math.floor(days/30) + ' months ' + days%30 + ' days';
            }
        },
        'formData.type': function(v, o) {
            // 1 = Amandement
            if (v == 1) {
                this.getParentContracts();
            }
        },
        'formData.partners': function(v, o) {
            // 1 = Amandement
            if (v && this.formData.type == 1) {
                this.getParentContracts();
            }
        },
        'formData.status': function(v, o) {
            if (v === 1) {
                this.generatePrefix()
            }

            // get last number
            let newNumber = '3424'
            this.formData.doc_signed_date
            this.formData.number = '-3' + newNumber + '/' + moment(this.doc_signed_date).format('Y')
        },
    },
    methods: {
        closeDialog: function() {
            this.error = {};
            this.formErrors = {};
            if (this.$refs.upload) {
                this.$refs.upload.clearFiles();
            }
            this.$emit('close-dialog')
        },
        generatePrefix: function() {
            var number = 'GMF/'
            number += this.formData.document_type + '/'

            // new contract
            if (this.formData.type === 0) {
                number += this.formData.unit_approver
            }

            // amandement
            if (this.formData.type === 1) {
                number += 'AMAND-'
            }

            this.formData.prefix_number = number
        },
        store: function() {
            let _this = this;
            _this.$store.state.loading = true;

            axios.post(BASE_URL + '/contract', _this.formData)
                .then(function(r) {
                    _this.closeDialog()
                    _this.$store.state.loading = false;
                    _this.$message({
                        message: 'Data BERHASIL disimpan.',
                        type: 'success'
                    });
                    _this.$emit('refresh-data')
                })
                .catch(function(e) {
                    _this.$store.state.loading = false;
                    if (e.response.status == 422) {
                        _this.error = {};
                        _this.formErrors = e.response.data.errors;
                    }

                    if (e.response.status == 500) {
                        _this.formErrors = {};
                        _this.error = e.response.data;
                    }
                })
        },
        update: function() {
            let _this = this;
            _this.$store.state.loading = true;

            axios.put(BASE_URL + '/contract/' + _this.formData.id, _this.formData)
                .then(function(r) {
                    _this.closeDialog()
                    _this.$store.state.loading = false
                    _this.$message({
                        message: 'Data BERHASIL disimpan.',
                        type: 'success'
                    });
                    _this.$emit('refresh-data')
                })
                .catch(function(e) {
                    _this.$store.state.loading = false
                    if (e.response.status == 422) {
                        _this.error = {};
                        _this.formErrors = e.response.data.errors;
                    }

                    if (e.response.status == 500) {
                        _this.formErrors = {};
                        _this.error = e.response.data;
                    }
                })
        },
        getParentContracts: function() {
            let _this = this;
            let params = { partners: _this.formData.partners }

            axios.get(BASE_URL + '/api/contract', {params: params})
                .then(function(r) {
                    _this.parentContracts = r.data;
                })
                .catch(function(e) {
                    console.log(e);
                });
        },
        updateTemplate: function(response, file, fileList) {
            if (response.success) {
                this.formData.template = response.file;
                this.formErrors.template = null;
            } else {
                this.formErrors.template = [response.message];
            }

            this.$forceUpdate();
        },
    }
}
</script>

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