<template>
    <el-card class="box-card">
        <el-row>
            <el-col :span="8">
                <h3>USERS <small>Manage</small></h3>
            </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 USER</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="Username" sortable="custom"></el-table-column>
            <el-table-column prop="salutation" label="Salutation" sortable="custom">
                <template slot-scope="scope">
                    {{salutations[scope.row.salutation]}}
                </template>
            </el-table-column>
            <el-table-column prop="first_name" label="First Name" sortable="custom"></el-table-column>
            <el-table-column prop="last_name" label="Last Name" sortable="custom"></el-table-column>
            <el-table-column prop="email" label="Email" sortable="custom" width="250px"></el-table-column>
            <el-table-column prop="type" label="Type" sortable="custom">
                <template slot-scope="scope">
                    {{scope.row.type ? 'Admin' : 'User'}}
                </template>
            </el-table-column>
            <el-table-column prop="unit" label="Unit" sortable="custom"></el-table-column>
            <el-table-column prop="status" label="Status" sortable="custom">
                <template slot-scope="scope">
                    <span :class="scope.row.status ? 'badge badge-success' : 'badge badge-danger'">{{scope.row.status ? 'Active' : 'Suspended'}}</span>
                </template>
            </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="700px" 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-3 col-form-label col-form-label-md">Username</label>
                    <div class="col-md-9">
                        <el-input placeholder="Username" v-model="formData.name"></el-input>
                        <div class="error-feedback" v-if="formErrors.name">{{formErrors.name[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-3 col-form-label col-form-label-md">Display Name</label>
                    <div class="col-md-9">
                        <el-select placeholder="Type" v-model="formData.salutation" style="width:18%;">
                            <el-option :value="0" label="Mr."></el-option>
                            <el-option :value="1" label="Mrs."></el-option>
                            <el-option :value="2" label="Ms."></el-option>
                        </el-select>
                        <el-input style="width:40%" placeholder="First Name" v-model="formData.first_name"></el-input>
                        <el-input style="width:40%" placeholder="Last Name" v-model="formData.last_name"></el-input>
                        <div class="error-feedback" v-if="formErrors.salutation">{{formErrors.salutation[0]}}</div>
                        <div class="error-feedback" v-if="formErrors.first_name">{{formErrors.first_name[0]}}</div>
                        <div class="error-feedback" v-if="formErrors.last_name">{{formErrors.last_name[0]}}</div>
                    </div>
                </div>

                <div class="form-group row">
                    <label class="col-md-3 col-form-label col-form-label-md">Email</label>
                    <div class="col-md-9">
                        <el-input placeholder="Email" v-model="formData.email"></el-input>
                        <div class="error-feedback" v-if="formErrors.email">{{formErrors.email[0]}}</div>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-3 col-form-label col-form-label-md">Type</label>
                    <div class="col-md-9">
                        <el-select placeholder="Type" v-model="formData.type" style="width:100%;">
                            <el-option :value="0" label="User"></el-option>
                            <el-option :value="1" label="Admin"></el-option>
                        </el-select>
                        <div class="error-feedback" v-if="formErrors.type">{{formErrors.type[0]}}</div>
                    </div>
                </div>

                <div v-show="formData.type == 0" class="form-group row">
                    <label class="col-md-3 col-form-label col-form-label-md">Unit</label>
                    <div class="col-md-9">
                        <el-select placeholder="Unit" v-model="formData.unit_id" style="width:100%;">
                            <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-3 col-form-label col-form-label-md">Password</label>
                    <div class="col-md-9">
                        <el-input type="password" placeholder="Password" v-model="formData.password" style="width:50%"></el-input>
                        <el-input type="password" placeholder="Password Confirmation" v-model="formData.password_confirmation" style="width:49%"></el-input>
                        <div class="error-feedback" v-if="formErrors.password">{{formErrors.password[0]}}</div>
                    </div>
                </div>

                <div class="form-group row">
                    <label class="col-md-3 col-form-label col-form-label-md">Signature</label>
                    <div class="col-md-9">
                        <textarea rows="5" class="form-control" placeholder="Signature" v-model="formData.signature"></textarea>
                    </div>
                </div>

                <div class="form-group row">
                    <label class="col-md-3 col-form-label col-form-label-md">Status</label>
                    <div class="col-md-9">
                        <el-select placeholder="Status" v-model="formData.status" style="width:100%;">
                            <el-option :value="0" label="Suspended"></el-option>
                            <el-option :value="1" label="Active"></el-option>
                        </el-select>
                        <div class="error-feedback" v-if="formErrors.status">{{formErrors.status[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
        },
        units() {
            return this.$store.state.units
        },
        loading() {
            return this.$store.state.loading
        }
    },
    data: function() {
        return {
            salutations: ['Mr.', 'Mrs.', 'Ms.'],
            showForm: false,
            sortOrder: 'id',
            sortDirection: 'ASC',
            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 + '/user', _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 + '/user/' + _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 User'
            this.error = {}
            this.formErrors = {}
            this.formData = {
                type: 0,
                salutation: 0
            }
            this.showForm = true
        },
        editData: function(data) {
            this.formTitle = 'Edit User'
            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 + '/user/' + 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.',
                                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 + '/user', {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();
        this.$store.commit('getUnits')
    }
}
</script>

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