<template>
    <el-card class="box-card">
        <el-row>
            <el-col :span="6">
                <h3>CONTRACTS <small>Manage</small></h3>
            </el-col>
            <el-col :span="18">
                <el-form :inline="true">
                    <el-form-item>
                        <el-button @click="addData" type="primary"><i class="el-icon-plus"></i> ADD NEW CONTRACT</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="exportToExcel" type="primary"><i class="el-icon-document"></i> EXPORT TO EXCEL</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="contracts.tableData" stripe
            :default-sort = "{prop: sort, order: order}"
            v-loading="loading"
            @filter-change="filterChange"
            @sort-change="sortChange">

            <el-table-column prop="creation_date" label="Creation Date" sortable="custom" width="150px" :filters="filterYear.creation_date | parseFilterYear" column-key="creation_date">
                <template slot-scope="scope">
                    {{scope.row.creation_date | readableDate}}
                </template>
            </el-table-column>

            <el-table-column prop="type" label="Type" sortable="custom" :filters="[{text: 'Amandement', value: 1}, {text: 'New', value: 0}]" column-key="type" width="110px">
                <template slot-scope="scope">
                    <span>{{scope.row.type ? 'Amandement' : 'New'}}</span>
                </template>
            </el-table-column>

            <el-table-column prop="partners" label="Partners" :filters="partners" column-key="partners" width="180px">
                <template slot-scope="scope">
                    <span v-for="(p,i) in scope.row.partners" :key="i">{{p.name}}<br></span>
                </template>
            </el-table-column>

            <el-table-column prop="subject" label="Subject" sortable="custom" width="180px"></el-table-column>

            <el-table-column prop="running_number" label="Number" sortable="custom" width="200px">
                <template slot-scope="scope">
                    {{scope.row.number}}
                </template>
            </el-table-column>

            <el-table-column prop="intern_office_receipt_date" label="Office Receipt Date" sortable="custom" width="190px" :filters="filterYear.intern_office_receipt_date | parseFilterYear" column-key="intern_office_receipt_date">
                <template slot-scope="scope">
                    {{scope.row.intern_office_receipt_date | readableDate}}
                </template>
            </el-table-column>

            <el-table-column prop="doc_signed_date" label="Sign Off Date" sortable="custom" width="150px" :filters="filterYear.doc_signed_date | parseFilterYear" column-key="doc_signed_date">
                <template slot-scope="scope">
                    {{scope.row.doc_signed_date | readableDate}}
                </template>
            </el-table-column>

            <el-table-column prop="start" label="Start" sortable="custom" width="130px" :filters="filterYear.start | parseFilterYear" column-key="start">
                <template slot-scope="scope">
                    {{scope.row.start | readableDate}}
                </template>
            </el-table-column>

            <el-table-column prop="end" label="End" sortable="custom" width="180px" :filters="filterYear.end | parseFilterYear" column-key="end">
                <template slot-scope="scope">
                    {{readableDate(scope.row.end)}}
                </template>
            </el-table-column>

            <el-table-column prop="agreement_period" label="Agreement Period" width="170px" sortable="custom" :filters="agreementPeriodFilters" :filter-multiple="false" column-key="agreement_period"> </el-table-column>

            <el-table-column prop="unit" label="Unit Request" sortable="custom" :filters="units" column-key="unit_id" width="140px"></el-table-column>

            <el-table-column prop="approver" label="Approver" sortable="custom" :filters="filterApprover" column-key="approver" width="140px"></el-table-column>

            <el-table-column prop="user" label="Creator" width="150px" sortable="custom" :filters="users" column-key="users"></el-table-column>

            <el-table-column prop="distributions" label="Distribution" :filters="units" column-key="distributions" width="110px">
                <template slot-scope="scope">
                    <span v-for="(d, i) in scope.row.distributions" :key="i">{{d.department}},</span>
                </template>
            </el-table-column>

            <el-table-column prop="revisi" label="Revisi" align="center" width="60px">
                <template slot-scope="scope">
                    {{scope.row.lastRevision ? scope.row.lastRevision.revision_number : 0}}
                </template>
            </el-table-column>

            <el-table-column prop="status" label="Status" sortable="custom" align="center" :filters="statuses" column-key="status" width="100px">
                <template slot-scope="scope">
                    <span :class="'badge badge-' + statuses[scope.row.status].color">{{statuses[scope.row.status].text}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="document" label="Signed Doc." align="center" :filters="[{value:1, text: 'Uploaded'}, {value: 0, text: 'Not uploaded'}]" column-key="document" width="110px">
                <template slot-scope="scope">
                    <i :class="scope.row.document ? 'el-icon-check text-success' : 'el-icon-close text-danger'"></i>
                </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" style="transform:rotate(-90deg);"></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="editRevision(scope.row)">
                                <i class="el-icon-tickets"></i> Edit Revision</el-dropdown-item>
                            <el-dropdown-item @click.native.prevent="showRevision(scope.row.id)">
                                <i class="el-icon-time"></i> Show Revisions
                            </el-dropdown-item>
                            <el-dropdown-item @click.native.prevent="uploadDocument(scope.row)">
                                <i class="el-icon-upload2"></i> Upload Signed Document
                            </el-dropdown-item>
                            <el-dropdown-item @click.native.prevent="showSupportDocument(scope.row)">
                                <i class="el-icon-document"></i> Support Document
                            </el-dropdown-item>
                            <el-dropdown-item v-if="scope.row.document" @click.native.prevent="viewDocument(scope.row.id)">
                                <i class="el-icon-document"></i> View Document
                            </el-dropdown-item>
                            <el-dropdown-item v-if="scope.row.document && scope.row.status == 1" @click.native.prevent="distribute(scope.row)">
                                <i class="el-icon-share"></i> Distribute
                            </el-dropdown-item>
                            <el-dropdown-item @click.native.prevent="composeMessage(scope.row.id)">
                                <i class="el-icon-edit-outline"></i> Send Email
                            </el-dropdown-item>
                            <el-dropdown-item v-if="scope.row.messageCount" @click.native.prevent="showMessages(scope.row.id)">
                                <i class="el-icon-message"></i> Show Email
                            </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="contracts.totalRow">
                </el-pagination>
            </el-col>
            <el-col :span="12" style="text-align:right">
                Showing {{ contracts.rowFrom }} to {{ contracts.rowTo }} of {{ contracts.totalRow }} rows
            </el-col>
        </el-row>


        <el-dialog :visible.sync="showDialog" :title="dialogTitle" :width="dialogWidth" v-loading="loading" :close-on-click-modal="false" :show-close="showClose">
            <keep-alive>
                <component :is="dialogComponent"
                @close-dialog="showDialog = false"
                @refresh-data="refreshData"
                :data="formData"
                ></component>
            </keep-alive>
        </el-dialog>
    </el-card>
</template>

<script>
import ContractForm from './contract/ContractForm'
import MessageForm from './contract/MessageForm'
import MessageList from './contract/MessageList'
import RevisionForm from './contract/RevisionForm'
import RevisionList from './contract/RevisionList'
import SupportDocument from './contract/SupportDocument'
import UploadDocumentForm from './contract/UploadDocumentForm'

export default {
    computed: {
        filterYear() {
            return this.$store.state.filterYear
        },
        filterApprover() {
            return this.$store.state.filterApprover
        },
        pagerOptions() {
            return this.$store.state.pagerOptions
        },
        contracts() {
            return this.$store.state.contracts
        },
        partners() {
            return this.$store.state.partners
        },
        users() {
            return this.$store.state.users
        },
        units() {
            return this.$store.state.units
        },
        loading() {
            return this.$store.state.loading
        },
        statuses() {
            return this.$store.state.statuses
        }
    },
    data: function() {
        return {
            dialogTitle: '',
            dialogWidth: '1300px',
            dialogComponent: ContractForm,
            pageSize: 10,
            keyword: '',
            page: 1,
            sort: 'id',
            order: 'descending',
            filters: {},
            showDialog: false,
            showClose: false,
            formData: {},
            agreementPeriodFilters: [
                {value: '<= 6 months', text: '<= 6 months'},
                {value: '<= 1 year', text: '<= 1 year'},
                {value: '>= 1 year', text: '>= 1 year'},
                {value: '>= 2 years', text: '>= 2 years'},
                {value: '>= 3 years', text: '>= 3 years'}
            ]
        }
    },
    methods: {
        readableDate: function(v) {
            return v ? moment(v).format('DD-MMM-YYYY') : 'All Obligation Complete';
        },
        goToPage: function(p) {
            this.page = p;
            this.requestData();
        },
        sortChange: function(column) {
            if (this.sort !== column.prop || this.order !== column.order) {
                this.sort = column.prop;
                this.order = column.order;
                this.requestData();
            }
        },
        filterChange: function(f) {
            let column = Object.keys(f)[0];
            this.filters[column] = Object.values(f[column]);
            this.refreshData();
        },
        advanceFilter: function() {
            this.dialogComponent = FilterForm
            this.formData = {}
            this.dialogTitle = 'Advance Filter'
            this.dialogWidth = '600px'
            this.showDialog = true;
        },
        refreshData: function() {
            this.keyword = '';
            this.page = 1;
            this.requestData();
        },
        requestData: function() {
            let params = {
                page: this.page,
                keyword: this.keyword,
                pageSize: this.pageSize,
                sort: this.sort,
                order: this.order,
                api_token: USER.api_token
            }

            this.$store.commit('getContracts', Object.assign(params, this.filters))
        },
        exportToExcel: function() {
            window.location = BASE_URL + '/contract/export?sort=' + this.sort + '&order=' + this.order + '&' + $.param(this.filters);
        },
        viewDocument: function(id) {
            window.open(BASE_URL + '/contract/document/' + id, '_blank');
        },
        editRevision: function(data) {
            this.dialogComponent = RevisionForm
            this.formData = {
                contract_id: data.id,
                contract_number: data.number,
                previous_revision: data.lastRevision ? data.lastRevision.revision_number : 0,
                revision_number: data.lastRevision ? parseInt(data.lastRevision.revision_number) + 1 : 1
            };
            this.dialogTitle = 'Edit Revision'
            this.dialogWidth = '500px'
            this.showDialog = true;
            this.showClose = false;
        },
        composeMessage: function(contract_id) {
            this.$store.commit('getContacts')
            this.dialogComponent = MessageForm
            this.formData = {
                contract_id: contract_id,
                to: []
            };
            this.dialogTitle = 'Send Message'
            this.dialogWidth = '700px'
            this.showDialog = true;
            this.showClose = false;
        },
        showMessages: function(contract_id) {
            this.$store.commit('getMessages', { contract_id: contract_id })
            this.dialogComponent = MessageList
            this.formData = contract_id
            this.dialogTitle = 'Messages'
            this.dialogWidth = '900px'
            this.showDialog = true;
            this.showClose = true;
        },
        showRevision: function(id) {
            this.$store.commit('getRevisions', { contract_id: id })
            this.dialogComponent = RevisionList
            this.formData = id
            this.dialogTitle = 'Contract Revision'
            this.dialogWidth = '700px'
            this.showDialog = true;
            this.showClose = true;
        },
        uploadDocument: function(data) {
            this.dialogComponent = UploadDocumentForm
            this.formData = data
            this.dialogTitle = 'Upload Document'
            this.dialogWidth = '500px'
            this.showDialog = true;
            this.showClose = false;
        },
        showSupportDocument: function(data) {
            this.$store.commit('getSupportDocuments', { contract_id: data.id })
            this.dialogComponent = SupportDocument
            this.formData = data
            this.dialogTitle = 'Support Documents'
            this.dialogWidth = '750px'
            this.showDialog = true;
            this.showClose = true;
        },
        addData: function() {
            this.dialogComponent = ContractForm
            this.formData = {
                creation_date: moment().format('YYYY-MM-DD'),
                user_id: USER.id,
                partners: [],
                distributions: []
            }

            this.dialogTitle = 'Add New Contract'
            this.dialogWidth = '1300px'
            this.showDialog = true
        },
        editData: function(data) {
            this.dialogComponent = ContractForm
            this.formData = JSON.parse(JSON.stringify(data));
            this.formData.partners = []
            this.formData.distributions = []
            var _this = this;

            data.partners.forEach(function(p) {
                _this.formData.partners.push(p.id);
            });

            data.distributions.forEach(function(p) {
                _this.formData.distributions.push(p.id);
            });

            this.dialogTitle = 'Edit Contract'
            this.dialogWidth = '1300px'
            this.showDialog = 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 + '/contract/' + 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(() => {

                });
        },
        distribute: function(data) {
            let _this = this;
            _this.$confirm('Are you sure you want to distribute this contract?')
                .then(() => {
                    _this.$store.state.loading = true;
                    _this.formData.api_token = USER.api_token
                    axios.post(API_URL + '/contract/distribute/' + data.id, _this.formData)
                        .then(function(r) {
                            _this.$store.state.loading = false;

                            if (r.data.success) {
                                _this.$message({
                                    message: 'Document has been distributed!.',
                                    type: 'success'
                                });
                            } else {
                                _this.$message({
                                    message: 'Failed to distribute document. ' + r.data.message,
                                    type: 'error'
                                });
                            }
                        })
                        .catch(function(e) {
                            console.log(e);
                            _this.$store.state.loading = false;
                            _this.$message({
                                message: 'Failed to distribute document!.',
                                type: 'error'
                            });
                        });
                }).catch(function(e) {

                })
        }
    },
    watch: {
        keyword: function(v, o) {
            this.requestData()
        },
        pageSize: function(v, o) {
            this.requestData()
        }
    },
    filters: {
        readableDate: function(v) {
            return v ? moment(v).format('DD-MMM-YYYY') : '';
        },
        parseFilterYear: function(v) {
            let a = []
            v.forEach(function(x) {
                a.push({value: x, text: x})
            });

            return a;
        }
    },
    mounted: function() {
        this.requestData()
        this.$store.commit('getUnits')
        this.$store.commit('getUsers')
        this.$store.commit('getPartners')
        this.$store.commit('getFilterYear')
        this.$store.commit('getFilterApprover')
    }
}
</script>

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