<template>
    <el-card class="box-card">
        <el-row>
            <el-col :span="8">
                <h2>PARTNERS <small>Manage</small></h2>
            </el-col>
            <el-col :span="16">
                <el-form :inline="true">
                    <el-form-item>
                        <el-button @click="addData" type="primary"><i class="el-icon-plus"></i> ADD NEW PARTNER</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-select class="pager-options" v-model="pageSize" placeholder="Page Size">
                            <el-option v-for="item in pagerOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item style="margin-right:0;">
                        <el-input placeholder="Search" prefix-icon="el-icon-search" v-model="keyword">
                            <el-button @click="refreshData" slot="append" icon="el-icon-refresh"></el-button>
                        </el-input>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>

        <el-table :data="tableData" stripe
        :default-sort = "{prop: sort, order: order}"
        v-loading="loading"
        @sort-change="sortChange">
            <el-table-column prop="name" label="Name" sortable="custom"></el-table-column>
            <el-table-column prop="address" label="Address" sortable="custom"></el-table-column>
            <el-table-column prop="country" label="Country" sortable="custom"></el-table-column>
            <el-table-column prop="phone" label="Phone" sortable="custom"></el-table-column>
            <el-table-column prop="fax" label="Fax" sortable="custom"></el-table-column>
            <el-table-column prop="email" label="Email" sortable="custom" width="200px"></el-table-column>
            <el-table-column prop="contact_person" label="Contact Person" sortable="custom" width="200px"></el-table-column>
            <el-table-column fixed="right" width="40px">
                <template slot-scope="scope">
                    <el-dropdown>
                        <span class="el-dropdown-link">
                            <i class="el-icon-more"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item @click.native.prevent="editData(scope.row)"><i class="el-icon-edit-outline"></i> Edit</el-dropdown-item>
                            <el-dropdown-item @click.native.prevent="deleteData(scope.row.id)"><i class="el-icon-delete"></i> Delete</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <br>

        <el-row>
            <el-col :span="12">
                <el-pagination @current-change="goToPage"
                    :page-size="pageSize"
                    background
                    layout="prev, pager, next"
                    :total="totalRow">
                </el-pagination>
            </el-col>
            <el-col :span="12" style="text-align:right">
                Showing {{ rowFrom }} to {{ rowTo }} of {{ totalRow }} rows
            </el-col>
        </el-row>

        <el-dialog :visible.sync="showForm" :title="formTitle" width="600px" v-loading="loading" :close-on-click-modal="false">
            <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="formData.id == undefined ? store : update">
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Name</label>
                    <div class="col-md-8">
                        <input type="text" :class="['form-control', formErrors.name ? 'is-invalid' : '']" placeholder="Name" v-model="formData.name">
                        <div class="invalid-feedback" v-if="formErrors.name">{{formErrors.name[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Address</label>
                    <div class="col-md-8">
                        <textarea rows="3" :class="['form-control', formErrors.address ? 'is-invalid' : '']" placeholder="Address" v-model="formData.address"></textarea>
                        <div class="invalid-feedback" v-if="formErrors.address">{{formErrors.address[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Country</label>
                    <div class="col-md-8">
                        <input type="text" :class="['form-control', formErrors.country ? 'is-invalid' : '']" placeholder="Country" v-model="formData.country">
                        <div class="invalid-feedback" v-if="formErrors.country">{{formErrors.country[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Phone</label>
                    <div class="col-md-8">
                        <input type="text" :class="['form-control', formErrors.phone ? 'is-invalid' : '']" placeholder="Phone" v-model="formData.phone">
                        <div class="invalid-feedback" v-if="formErrors.phone">{{formErrors.phone[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Fax</label>
                    <div class="col-md-8">
                        <input type="text" :class="['form-control', formErrors.fax ? 'is-invalid' : '']" placeholder="Fax" v-model="formData.fax">
                        <div class="invalid-feedback" v-if="formErrors.fax">{{formErrors.fax[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Email</label>
                    <div class="col-md-8">
                        <input type="text" :class="['form-control', formErrors.email ? 'is-invalid' : '']" placeholder="Email" v-model="formData.email">
                        <div class="invalid-feedback" v-if="formErrors.email">{{formErrors.email[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-4 col-form-label col-form-label-md">Contact Person</label>
                    <div class="col-md-8">
                        <input type="text" :class="['form-control', formErrors.contact_person ? 'is-invalid' : '']" placeholder="Contact Person" v-model="formData.contact_person">
                        <div class="invalid-feedback" v-if="formErrors.contact_person">{{formErrors.contact_person[0]}}</div>
                    </div>
                </div>
                <div class="form-group text-right">
                    <button class="btn btn-primary" type="submit" @click="store" v-if="formData.id == undefined"><i class="el-icon-check"></i> SAVE</button>
                    <button class="btn btn-primary" type="submit" @click="update" v-if="formData.id != undefined"><i class="el-icon-check"></i> SAVE</button>
                    <button class="btn btn-secondary" @click="showForm = false"><i class="el-icon-close"></i> CANCEL</button>
                </div>
            </form>
        </el-dialog>
    </el-card>
</template>

<script>
export default {
    watch: {
        keyword: function(v, o) {
            this.requestData()
        },
        pageSize: function(v, o) {
            this.requestData()
        }
    },
    computed: {
        pagerOptions() {
            return this.$store.state.pagerOptions
        },
        loading() {
            return this.$store.state.loading
        }
    },
    data: function() {
        return {
            showForm: false,
            formTitle: '',
            rowFrom: 0,
            rowTo: 0,
            totalRow: 0,
            formErrors: {},
            error: {},
            formData: {},
            keyword: '',
            page: 1,
            pageSize: 10,
            tableData: [],
            sort: 'name',
            order: 'ascending',
        }
    },
    methods: {
        sortChange: function(column) {
            if (this.sort !== column.prop || this.order !== column.order) {
                this.sort = column.prop;
                this.order = column.order;
                this.requestData();
            }
        },
        goToPage: function(p) {
            this.page = p;
            this.requestData();
        },
        store: function() {
            let _this = this;
            _this.$store.state.loading = true;
            _this.formData.api_token = USER.api_token
            axios.post(API_URL + '/partner', _this.formData)
                .then(function(r) {
                    _this.$store.state.loading = false;
                    _this.showForm = false;
                    _this.$message({
                        message: 'Data BERHASIL disimpan.',
                        type: 'success'
                    });
                    _this.requestData();
                })
                .catch(function(e) {
                    _this.$store.state.loading = false;

                    if (e.response.status == 422) {
                        _this.formErrors = e.response.data.errors;
                    }

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

            axios.put(API_URL + '/partner/' + _this.formData.id, _this.formData)
                .then(function(r) {
                    _this.$store.state.loading = false;
                    _this.showForm = false
                    _this.$message({
                        message: 'Data BERHASIL disimpan.',
                        type: 'success'
                    });
                    _this.requestData()
                })
                .catch(function(e) {
                    _this.$store.state.loading = false;

                    if (e.response.status == 422) {
                        _this.formErrors = e.response.data.errors;
                    }

                    if (e.response.status == 500) {
                        _this.error = e.response.data;
                    }
                })
        },
        addData: function() {
            this.formTitle = 'Add New Partner'
            this.error = {}
            this.formErrors = {}
            this.formData = {}
            this.showForm = true
        },
        editData: function(data) {
            this.formTitle = 'Edit Partner'
            this.formData = JSON.parse(JSON.stringify(data));
            this.error = {}
            this.formErrors = {}
            this.showForm = true
        },
        deleteData: function(id) {
            let _this = this;

            _this.$confirm('Anda yakin akan menghapus data ini?')
                .then(() => {
                    let params = { api_token: USER.api_token }
                    axios.delete(API_URL + '/partner/' + id, { params: params })
                        .then(function(r) {
                            _this.requestData();
                            _this.$message({
                                message: 'Data BERHASIL dihapus.',
                                type: 'success'
                            });
                        })
                        .catch(function(e) {
                            _this.$message({
                                message: 'Data GAGAL dihapus. ' + e.response.data.message,
                                type: 'error'
                            });
                        })
                })
                .catch(() => {

                });
        },
        refreshData: function() {
            this.keyword = '';
            this.page = 1;
            this.requestData();
        },
        requestData: function() {
            let _this = this;
            let params = {
                page: _this.page,
                keyword: _this.keyword,
                pageSize: _this.pageSize,
                sort: _this.sort,
                order: _this.order,
                api_token: USER.api_token
            }

            _this.$store.state.loading = true;

            axios.get(API_URL + '/partner', {params: params})
                .then(function(r) {
                    _this.$store.state.loading = false;
                    _this.tableData = r.data.data
                    _this.totalRow = r.data.total
                    _this.rowFrom = r.data.from
                    _this.rowTo = r.data.to
                })
                .catch(function(e) {
                    _this.$store.state.loading = false;

                    if (e.response.status == 500) {
                        _this.$message({
                            message: e.response.data.message + '\n' + e.response.data.file + ':' + e.response.data.line,
                            type: 'error'
                        });
                    }
                })
        }
    },
    mounted: function() {
        this.requestData();
    }
}
</script>

<style lang="css" scoped>
.el-form {
    text-align: right;
}
</style>
