<?php

/**
Copyright distrib (2018)

contact@opendistrib.net

Ce logiciel est un programme informatique servant à aider les producteurs
à distribuer leur production en circuits courts.

Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".

En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée.  Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme,  le
titulaire des de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
droits patrimoniaux et les concédants successifs.

A cet égard  l'attention de l'utilisateur est attirée sur les risques
associés au chargement,  à l'utilisation,  à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant  des  connaissances  informatiques approfondies.  Les
utilisateurs sont donc invités à charger  et  tester  l'adéquation  du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.

Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.
*/

\backend\assets\VuejsDistributionIndexAsset::register($this);

$this->setTitle('Distributions') ;
$this->setPageTitle('Distributions') ;

?>

<?php if($orderUpdate):
    $orderUpdateDistributionTimestamp = strtotime($orderUpdate->distribution->date);
?>
    <script>
        window.vueValues = {
            date: new Date(<?= date('Y', $orderUpdateDistributionTimestamp) ?>, <?= date('m', $orderUpdateDistributionTimestamp) - 1 ?>, <?= date('d', $orderUpdateDistributionTimestamp) ?>),
            dateFormat: '<?= date('d/m/Y', $orderUpdateDistributionTimestamp) ?>',
            showModalFormOrderUpdate: true,
            idOrderUpdate: <?= $orderUpdate->id ?>
        };
    </script>
<?php endif; ?>

<div id="app-distribution-index" class="app-vuejs">
    <?php if(strlen($date)): ?>
        <span id="distribution-date"><?= $date; ?></span>
    <?php endif; ?>
    <div id="loading" v-if="showLoading">
        <img src="<?= Yii::$app->urlManagerBackend->getBaseUrl(); ?>/img/loader.gif" alt="Chargement ..." />
    </div>
    <div id="wrapper-app-distribution-index" :class="'wrapper-app-vuejs '+(loading ? '' : 'loaded')">
        <div class="col-md-4">
            <div id="calendar">
                <v-calendar
                    is-inline
                    is-expanded
                    v-model="date"
                    popover-visibility="hidden"
                    color="green"
                    :mode="calendar.mode"
                    :formats="calendar.formats"
                    :theme-styles="calendar.themeStyles"
                    :attributes="calendar.attrs"
                    @dayclick='dayClicked'>
                ></v-calendar>
            </div>
            <div class="clr"></div>
        </div>
        <div class="col-md-8">
            <div v-if="date">
                <div id="infos-top">
                    <div class="col-md-12">
                        <div class="info-box" id="info-box-distribution">
                            <span :class="'info-box-icon '+(distribution.active ? 'bg-green' : 'bg-red')"><i :class="'fa '+(distribution.active ? 'fa-check' : 'fa-remove')"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">
                                    <h4>
                                        Distribution du <strong>{{ dateFormat }}</strong>
                                        <a class="btn btn-default" :href="distribution.url_order" @click="copyLinkOrder($event, distribution.url_order)"><span class="glyphicon glyphicon-link"></span></a>
                                    </h4>
                                    <a @click="activeWeekDistribution" data-active="0" class="btn btn-default btn-active-week" v-if="oneDistributionWeekActive">Désactiver cette semaine</a>
                                    <a @click="activeWeekDistribution" data-active="1" class="btn btn-default btn-active-week" v-else>Activer cette semaine</a>
                                    
                                    <a @click="activeDistribution" data-active="0" class="btn btn-default" v-if="distribution.active">Désactiver ce jour</a>
                                    <a @click="activeDistribution" data-active="1" class="btn btn-default" v-else>Activer ce jour</a>
                                </span>
                            </div>
                        </div>
                    </div>

                    <!-- produits -->
                    <div class="col-md-6">
                        <div class="info-box col-md-4">
                            <span class="info-box-icon bg-yellow"><i class="fa fa-clone"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">
                                    {{ countActiveProducts }} Produits<br />
                                    <template v-if="isOneProductMaximumQuantityExceeded()"><span class="glyphicon glyphicon-alert"></span> Quantités max dépassées<br /></template>
                                    <br />
                                    <button class="btn btn-default" @click="showModalProducts = true">Configurer</button>
                                </span>
                            </div>
                        </div>
                    </div>
                    <modal v-if="showModalProducts" id="modal-products" @close="showModalProducts = false">
                        <h3 slot="header">Produits</h3>
                        <div slot="body">
                            <table class="table table-condensed table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <td>Actif</td>
                                        <td>Nom</td>
                                        <td class="quantity-ordered">Commandé</td>
                                        <td class="quantity-max">Maximum</td>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="product in products" v-if="getProductDistribution(product)">
                                        <td>
                                            <button class="btn btn-success" v-if="getProductDistribution(product).active == 1"><span class="glyphicon glyphicon-ok"></span></button>
                                            <button class="btn btn-default" v-else data-active-product="1" :data-id-product="product.id" @click="productActiveClick"><span class="glyphicon glyphicon-ok"></span></button>
                                            <button class="btn btn-danger" v-if="getProductDistribution(product).active == 0"><span class="glyphicon glyphicon-remove"></span></button>
                                            <button class="btn btn-default" v-else data-active-product="0" :data-id-product="product.id" @click="productActiveClick"><span class="glyphicon glyphicon-remove"></span></button>
                                        </td>
                                        <td>{{ product.name }}</td>
                                        <td class="quantity-ordered">
                                            <span v-if="isProductMaximumQuantityExceeded(product)" class="glyphicon glyphicon-alert"></span>
                                            {{ product.quantity_ordered ? product.quantity_ordered + ' '+ ((product.unit == 'piece') ? ' p.' : ' '+(product.unit == 'g' || product.unit == 'kg') ? 'kg' : 'litre(s)') : '&empty;' }}
                                        </td>
                                        <td class="quantity-max">
                                            <div class="input-group">
                                                <input type="text" class="form-control quantity-max" placeholder="&infin;" :data-id-product="product.id" v-model="getProductDistribution(product).quantity_max" @keyup="productQuantityMaxChange"  />
                                                <span class="input-group-addon">{{ (product.unit == 'piece') ? 'p.' : ' '+((product.unit == 'g' || product.unit == 'kg') ? 'kg' : 'litre(s)') }}</span>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div slot="footer">
                            <div class="actions-form">
                                <button class="modal-default-button btn btn-default" @click="closeModalProducts">Fermer</button>
                            </div>
                        </div>
                    </modal>

                    <div class="col-md-6">
                        <div class="info-box col-md-4">
                            <span class="info-box-icon bg-yellow"><i class="fa fa-map-marker"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">
                                    {{ countActivePointsSale }} Points de vente<br /><br />
                                    <button class="btn btn-default" @click="showModalPointsSale = true">Configurer</button>
                                </span>
                            </div>
                        </div>
                    </div>
                    <modal v-if="showModalPointsSale" id="modal-points-sale" @close="showModalPointsSale = false">
                        <h3 slot="header">Points de vente</h3>
                        <div slot="body">
                            <table class="table table-condensed table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <td>Actif</td>
                                        <td>Nom</td>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="pointSale in pointsSale" v-if="pointSale.status == 1">
                                        <td>
                                            <button class="btn btn-success" v-if="pointSale.pointSaleDistribution[0].delivery == 1"><span class="glyphicon glyphicon-ok"></span></button>
                                            <button class="btn btn-default" v-else data-delivery-point-sale="1" :data-id-point-sale="pointSale.id" @click="pointSaleActiveClick"><span class="glyphicon glyphicon-ok"></span></button>
                                            <button class="btn btn-danger" v-if="pointSale.pointSaleDistribution[0].delivery == 0"><span class="glyphicon glyphicon-remove"></span></button>
                                            <button class="btn btn-default" v-else data-delivery-point-sale="0" :data-id-point-sale="pointSale.id" @click="pointSaleActiveClick"><span class="glyphicon glyphicon-remove"></span></button>
                                        </td>
                                        <td>{{ pointSale.name }}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </modal>

                    <div class="col-md-6">
                        <div id="summary-ca-weight" class="info-box col-md-4">
                            <span class="info-box-icon bg-yellow"><i class="fa fa-euro"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">CA (TTC)</span>
                                <span class="info-box-number">{{ distribution.revenues }} <span class="normal" v-if="distribution.potential_revenues != '0,00 €'">/ {{ distribution.potential_revenues }}</span></span>
                                <span class="info-box-text">Poids</span>
                                <span class="info-box-number">{{ distribution.weight }} kg <span class="normal" v-if="distribution.potential_weight > 0">/ {{ distribution.potential_weight }} kg</span></span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-box col-md-4">
                            <span class="info-box-icon bg-yellow"><i class="fa fa-download"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">
                                    {{ countOrders }} Commande<span v-if="countOrders > 1">s</span><br />

                                    <template v-for="distributionExport in distribution.exports">
                                        <a v-if="countOrders > 0" :href="distributionExport.url" target="_blank" class="btn btn-xs btn-default">{{ distributionExport.label }}</a><br />
                                    </template>
                                    <!--<a :href="distribution.url_report+'&type=csv'" class="btn btn-xs btn-default" v-if="countOrders > 0">Tableau (CSV)</a>
                                    <a :href="distribution.url_report_csv2" class="btn btn-xs btn-default" v-if="countOrders > 0">Tableau 2 (CSV)</a>
                                    <br />
                                    <a :href="distribution.url_report_grid" class="btn btn-xs btn-default" v-if="producer && producer.option_distribution_export_orders_grid_pdf && countOrders > 0">Grille (PDF)</a>
                                    <a :href="distribution.url_export_shopping_cart_labels" class="btn btn-xs btn-default" v-if="countOrders > 0">Étiquettes (PDF)</a>
                                    <a :href="distribution.url_report_total_products" class="btn btn-xs btn-default" v-if="countOrders > 0">Total produits (CSV)</a>-->
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="callout callout-info" v-else>
                <h4><i class="fa fa-info"></i> Pour commencer</h4>
                <p>Veuillez choisir une date de distribution.</p>
            </div>
        </div>

      <div class="clr"></div>

        <div id="orders" class="panel panel-default" v-if="date">
            <div class="panel-heading">
                <h3 class="panel-title">Commandes <label class="label label-success" v-if="orders.length">{{ orders.length }}</label><label class="label label-danger" v-else>0</label></h3>
                <div class="buttons">
                </div>
            </div>
            <div class="panel-body">
                <order-form
                    v-if="showModalFormOrderCreate"
                    create="1"
                    :date="date"
                    :order="orderCreate"
                    :points-sale="pointsSale"
                    :id-active-point-sale="idActivePointSale"
                    :means-payment="meansPayment"
                    :users="users"
                    :products="products"
                    :producer="producer"
                    :orders="ordersUpdate"
                    :loading-update-product-order="loadingUpdateProductOrder"
                    :units="units"
                    @close="closeModalOrderForm(true)"
                    @ordercreatedupdated="orderCreatedUpdated"
                    @updateproductorderprices="updateProductOrderPrices"
                ></order-form>

                <div id="wrapper-nav-points-sale">
                        <ul id="nav-points-sale">
                                <li data-id-point-sale="0" data-id-point-sale="0" v-if="countActivePointsSale > 1" @click="pointSaleClick">
                                        <a class="btn btn-default btn-primary" v-if="idActivePointSale == 0">Tous <span class="label label-default">{{ orders.length }}</span> <span class="glyphicon glyphicon-triangle-bottom"></span></a>
                                        <a class="btn btn-default" v-else>Tous <span class="label label-default">{{ orders.length }}</span><span class="glyphicon glyphicon-triangle-bottom"></span></a>
                                </li>
                                <li v-for="pointSale in pointsSale" :data-id-point-sale="pointSale.id" v-if="pointSale.pointSaleDistribution[0].delivery == 1 && (pointSale.status == 1 || countOrdersByPointSale[pointSale.id] > 0)" @click="pointSaleClick">
                                        <a class="btn btn-default btn-primary" v-if="idActivePointSale == pointSale.id">{{ pointSale.name }} <span class="label label-default">{{ countOrdersByPointSale[pointSale.id] }}</span><span class="glyphicon glyphicon-triangle-bottom"></span></a>
                                        <a class="btn btn-default" v-else>{{ pointSale.name }} <span class="label label-default">{{ countOrdersByPointSale[pointSale.id] }}</span><span class="glyphicon glyphicon-triangle-bottom"></span></a>
                                </li>
                        </ul>
                    <div class="clr"></div>
                </div>

                    <div id="buttons-top-orders">
                            <div class="right">
                                    <div class="dropdown">
                                            <button class="btn btn-default btn-xs dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                                                    <span class="glyphicon glyphicon-file"></span> Documents
                                                    <span class="caret"></span>
                                            </button>
                                            <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
                                                    <li><a v-if="idActivePointSale > 0 && pointSaleActive.button_generate_delivery_note_point_sale == 1" @click="generateDeliveryNotePointSale" href="javascript:void(0);" >Générer un bon de livraison pour ce point de vente</a></li>
                                                    <li><a v-if="idActivePointSale > 0 && pointSaleActive.button_generate_delivery_note_each_user == 1" @click="generateDeliveryNoteEachUser" href="javascript:void(0);">Générer un bon de livraison pour chaque client</a></li>
                                                    <li><a @click="validateDeliveryNotes" href="javascript:void(0);">Valider les bons de livraisons</a></li>
                                            </ul>
                                    </div>
                                    <button id="btn-add-subscriptions" @click="addSubscriptions" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-plus"></span> Importer les abonnements</button>
                                    <template v-if="producer && producer.tiller == true">
                                            <button v-if="tillerIsSynchro" id="btn-tiller"  class="btn btn-success btn-xs" disabled><span class="glyphicon glyphicon-refresh"></span> Synchronisé avec Tiller</button>
                                            <button v-else id="btn-tiller" class="btn btn-xs btn-default" @click="synchroTiller"><span class="glyphicon glyphicon-refresh"></span> Synchroniser avec Tiller</button>
                                    </template>
                                    <button v-if="producer && producer.credit" id="btn-pay-orders" class="btn btn-default btn-xs" @click="payOrders"><span class="glyphicon glyphicon-euro"></span> Débiter les commandes</button>
                                    <button id="btn-add-order" @click="openModalFormOrderCreate" class="btn btn-xs btn-primary"><span class="glyphicon glyphicon-plus"></span> Ajouter une commande</button>
                            </div>
                            <div class="left">
                                    <a v-if="false && deliveryNoteExist(idActivePointSale)" :href="UrlManager.getBaseUrl()+'delivery-note/update?id='+deliveryNotes[idActivePointSale].id" class="btn btn-default btn-xs"><span class="glyphicon glyphicon-file"></span> Bon de livraison</a>
                            </div>
                            <div class="clr"></div>
                    </div>

                <div class="alert alert-info" v-if="missingSubscriptions && missingSubscriptions.length > 0">
                    <span class="glyphicon glyphicon-info-sign"></span>
                    {{ missingSubscriptions.length }} abonnement<template v-if="missingSubscriptions.length > 1">s</template> manquant<template v-if="missingSubscriptions.length > 1">s</template> :
                    <span v-for="(subscription, index) in missingSubscriptions">
                        {{ subscription.username }}<template v-if="index != missingSubscriptions.length - 1">, </template><template v-else>.</template>
                    </span>
                </div>

                <div class="alert alert-danger" v-if="distribution && !distribution.active && orders && orders.length > 0">
                    Attention, ce jour de distribution n'est pas activé et vous avez quand même des commandes enregistrées.
                </div>

                <div v-if="idActivePointSale > 0 && (totalActivePointSale() > 0 || weightActivePointSale() > 0)" class="point-sale-totals">
                    <div>
                        <span class="title">Totaux</span>
                        CA TTC : <strong>{{ totalActivePointSale() }} €</strong> / Poids : <strong>{{ weightActivePointSale() }} kg</strong>
                    </div>
                    <div v-if="producer.credit && pointSaleActive">
                        <span class="title">Crédit</span>
                        <template v-if="pointSaleActive.credit && pointSaleActive.credit == 1">
                            <template v-if="pointSaleActive.credit_functioning == 'mandatory'">Obligatoire</template>
                            <template v-else-if="pointSaleActive.credit_functioning == 'user'">Basé sur l'utilisateur</template>
                            <template v-else-if="pointSaleActive.credit_functioning == 'optional'">Optionnel</template>
                        </template>
                        <template v-else>Désactivé</template>
                    </div>
                </div>

                <table class="table table-condensed table-bordered table-hover" v-if="countOrdersByPointSale[idActivePointSale] > 0 || (idActivePointSale == 0 && orders.length > 0)">
                        <thead>
                                <tr>
                                        <th class="column-checkbox" v-if="idActivePointSale > 0">
                                                <input type="checkbox" v-model="checkboxSelectAllOrders" @change="selectAllOrdersEvent" />
                                        </th>
                                        <th class="column-origin">Origine</th>
                                        <th class="column-state">État</th>
                                        <th class="column-user">Utilisateur</th>
                                        <th class="column-point-sale" v-if="idActivePointSale == 0">Point de vente</th>
                                        <th class="column-amount">Montant</th>
                                        <th class="column-state-payment">Paiement</th>
                                        <th class="column-credit" v-if="!idActivePointSale || (pointSaleActive && pointSaleActive.credit == 1)">Crédit</th>
                                        <th class="column-actions">Actions</th>
                                        <th class="column-tiller" v-if="producer && producer.tiller">Tiller</th>
                                </tr>
                        </thead>
                    <tbody>
                        <template v-for="(order, key, index) in orders" v-if="idActivePointSale == 0 || idActivePointSale == order.id_point_sale">
                            <tr>
                                <td class="column-checkbox" v-if="idActivePointSale > 0">
                                        <input type="checkbox" v-model="order.selected" />
                                </td>
                                <td class="column-origin">
                                    <label class="label label-success" v-if="order.origin == 'user'">client</label>
                                    <label class="label label-default" v-else-if="order.origin == 'auto'">auto</label>
                                    <label class="label label-warning" v-else>admin</label>
                                </td>
                                <td class="column-state">
                                    <span class="label label-danger" v-if="order.date_delete"><span class="glyphicon glyphicon-trash"></span></span>
                                    <span class="label label-warning" v-if="order.date_update"><span class="glyphicon glyphicon-pencil"></span></span>
                                    <span class="label label-success" v-if="!order.date_update && !order.date_delete"><span class="glyphicon glyphicon-check"></span></span>
                                </td>
                                <td class="column-user">
                                    <span v-if="order.user">
                                            <template v-if="order.user.name_legal_person && order.user.name_legal_person.length">
                                                    {{ order.user.name_legal_person }}
                                            </template>
                                            <template v-else>
                                                {{ order.user.lastname+' '+order.user.name }}
                                            </template>
                                            <span class="shortcuts btn-group" role="group">
                                                <a :class="order.user.credit_active ? 'btn btn-success btn-sm' : 'btn btn-default btn-sm'" :href="baseUrl+'/user/credit?id='+order.id_user" data-toggle="popover" data-trigger="hover" data-placement="bottom" :data-content="order.user.credit.toFixed(2)+' €'"><span class="glyphicon glyphicon-euro"></span></a>
                                                <a class="btn btn-default btn-sm" :href="baseUrl+'/user/update?id='+order.id_user" data-toggle="popover" data-trigger="hover" data-placement="bottom" data-content="Modifier"><span class="glyphicon glyphicon-user"></span></a>
                                                <a class="btn btn-default btn-sm" :href="baseUrl+'/user/orders?id='+order.id_user" data-toggle="popover" data-trigger="hover" data-placement="bottom" data-content="Voir les commandes"><span class="glyphicon glyphicon-eye-open"></span></a>
                                            </span>
                                    </span>
                                    <span v-else class="no-user">{{ order.username }}</span>
                                    <span v-if="order.comment && order.comment.length > 0" class="glyphicon glyphicon-comment"></span>
                                    <span v-if="order.delivery_home && order.delivery_address && order.delivery_address.length > 0" class="glyphicon glyphicon-home"></span>
                                </td>
                                <td class="column-point-sale" v-if="idActivePointSale == 0">
                                    <template v-if="order.pointSale">
                                        {{ order.pointSale.name }}
                                    </template>
                                </td>
                                <td class="column-amount">
                                    {{ order.amount.toFixed(2)+'&nbsp;€' }}
                                    <div class="state-payment-mobile">
                                        <order-state-payment :order="order" :producer="producer"></order-state-payment>
                                    </div>
                                </td>
                                <td class="column-state-payment">
                                    <template v-if="!order.date_delete">
                                        <a href="javascript:void(0);" @click="orderPaymentModalClick" :data-id-order="order.id">
                                            <order-state-payment :order="order" :producer="producer"></order-state-payment>
                                        </a>
                                        <span class="glyphicon glyphicon-time" title="Débit automatique du crédit la veille de la distribution" v-if="order.amount != 0 && order.isCreditAutoPayment && (order.amount_paid == 0 || order.amount_paid < order.amount)"></span>

                                        <div v-if="order.amount_paid > 0 && order.amount_paid < order.amount">
                                            <span class="glyphicon glyphicon-alert"></span> Reste à payer
                                        </div>
                                        <div v-if="order.amount_paid > order.amount">
                                            <span class="glyphicon glyphicon-alert"></span> Surplus à rembourser
                                        </div>
                                    </template>
                                </td>
                                <td class="column-credit" v-if="!idActivePointSale || (pointSaleActive && pointSaleActive.credit == 1)">
                                    <template v-if="order.isCreditContext">
                                        <a :href="baseUrl+'/user/credit?id='+order.id_user" :class="order.user.credit >= 0 ? 'positive' : 'negative'">
                                            {{ order.user.credit.toFixed(2).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,")+'&nbsp;€' }}
                                        </a>
                                    </template>
                                </td>
                                <td class="column-actions">
                                    <span v-if="false && order.oneProductUnactivated" class="glyphicon glyphicon-warning-sign" title="Contient un produit non activé"></span>

                                    <a href="javascript:void(0);" class="btn btn-default btn-xs" :data-id-order="order.id" @click="orderViewClick"><span :class="'glyphicon ' + ((showViewProduct && idOrderView == order.id) ? 'glyphicon-eye-close' : 'glyphicon-eye-open')"></span></a>
                                    <a href="javascript:void(0);" class="btn btn-default btn-xs" :data-id-order="order.id" @click="updateOrderClick"><span class="glyphicon glyphicon-pencil"></span></a>

                                    <div class="wrapper-button-dropdown">
                                        <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                            € <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu">
                                            <template v-if="!order.isPaidViaInvoice">
                                                <li v-if="order.isCreditContext">
                                                    <a href="javascript:void(0);" @click="orderPaymentClick" :data-id-order="order.id" :data-type="getTypePayment(order)" data-mean-payment="credit">
                                                        <span class="glyphicon glyphicon-piggy-bank"></span> {{ getLabelPaymentRefund(order, 'Débiter', 'Recréditer', 'le crédit') }}
                                                    </a>
                                                </li>
                                                <template v-if="(!order.isCreditFunctioningMandatory && !order.isCreditFunctioningUser) || !order.id_user">
                                                    <li>
                                                        <a href="javascript:void(0);" @click="orderPaymentClick" :data-id-order="order.id" :data-type="getTypePayment(order)" data-mean-payment="money">
                                                            <span class="glyphicon glyphicon-euro"></span> {{ getLabelPaymentRefund(order, 'Payer', 'Rembourser', 'en espèce') }}
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a href="javascript:void(0);" @click="orderPaymentClick" :data-id-order="order.id" :data-type="getTypePayment(order)" data-mean-payment="cheque">
                                                            <span class="glyphicon glyphicon-euro"></span> {{ getLabelPaymentRefund(order, 'Payer', 'Rembourser', 'par chèque') }}
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a href="javascript:void(0);" @click="orderPaymentClick" :data-id-order="order.id" :data-type="getTypePayment(order)" data-mean-payment="transfer">
                                                            <span class="glyphicon glyphicon-euro"></span> {{ getLabelPaymentRefund(order, 'Payer', 'Rembourser', 'par virement') }}
                                                        </a>
                                                    </li>
                                                </template>
                                            </template>
                                            <li>
                                                <a href="javascript:void(0);" @click="orderPaymentModalClick" :data-id-order="order.id">
                                                    <span class="glyphicon glyphicon-th-list"></span> Historique
                                                </a>
                                            </li>
                                        </ul>
                                    </div>

                                    <div class="wrapper-button-dropdown">
                                        <button type="button" :class="'btn btn-xs dropdown-toggle ' + (countDocuments(order) ? 'btn-success' : 'btn-default')" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                            <span class="glyphicon glyphicon-file"></span> <template v-if="countDocuments(order)">{{ countDocuments(order) }}</template> <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu">
                                            <li v-if="!order.id_delivery_note">
                                                <a href="javascript:void(0);" class="" :data-id-order="order.id" @click="generateDeliveryNote">
                                                    <span class="glyphicon glyphicon-plus"></span> Générer un bon de livraison
                                                </a>
                                            </li>
                                            <li v-if="order.id_quotation">
                                                <a :href="UrlManager.getBaseUrl()+'quotation/update?id='+order.id_quotation">
                                                    <span class="glyphicon glyphicon-file"></span> Devis
                                                </a>
                                            </li>
                                            <li v-if="order.id_delivery_note">
                                                <a :href="UrlManager.getBaseUrl()+'delivery-note/update?id='+order.id_delivery_note">
                                                    <span class="glyphicon glyphicon-file"></span> Bon de livraison
                                                </a>
                                            </li>
                                            <li v-if="order.id_invoice">
                                                <a :href="UrlManager.getBaseUrl()+'invoice/update?id='+order.id_invoice">
                                                    <span class="glyphicon glyphicon-file"></span> Facture
                                                </a>
                                            </li>
                                        </ul>
                                    </div>

                                    <div class="wrapper-button-dropdown">
                                        <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu">
                                                <li><a href="javascript:void(0);" class="" :data-id-order="order.id" @click="deleteOrderClick"><span class="glyphicon glyphicon-trash"></span> Supprimer</a></li>
                                                <li v-if="order.id_subscription > 0"><a class="" :href="baseUrl+'/subscription/update?id='+order.id_subscription"><span class="glyphicon glyphicon-repeat"></span> Modifier l'abonnement lié</a></li>
                                                <li v-else><a class="add-subscription" :href="baseUrl+'/subscription/create?idOrder='+order.id"><span class="glyphicon glyphicon-plus"></span><span class="glyphicon glyphicon-repeat"></span>Créer un abonnement</a></li>
                                        </ul>
                                    </div>

                                    <order-form
                                        v-if="showModalFormOrderUpdate && idOrderUpdate == order.id"
                                        create="0"
                                        :date="date"
                                        :date-format="dateFormat"
                                        :points-sale="pointsSale"
                                        :id-active-point-sale="idActivePointSale"
                                        :means-payment="meansPayment"
                                        :users="users"
                                        :products="products"
                                        :order="ordersUpdate[key]"
                                        :orders="ordersUpdate"
                                        :producer="producer"
                                        :loading-update-product-order="loadingUpdateProductOrder"
                                        :units="units"
                                        @close="closeModalOrderForm(false)"
                                        @ordercreatedupdated="orderCreatedUpdated"
                                        @updateproductorderprices="updateProductOrderPrices"
                                        @updateinvoiceprices="updateInvoicePrices"
                                    ></order-form>

                                    <modal v-if="showModalPayment && idOrderPayment == order.id" class="modal-payment" @close="showModalPayment = false">
                                        <h3 slot="header">
                                            Commande du <strong>{{ dateFormat }}</strong> &gt;
                                            <strong><span v-if="order.user">{{ order.user.name +' '+order.user.lastname }}</span>
                                            <span v-else>{{ order.username }}</span></strong>
                                        </h3>
                                        <div slot="body">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="info-box">
                                                        <span :class="'info-box-icon ' +((order.isPaid) ? 'bg-green' : 'bg-red')"><i class="fa fa-check"></i></span>
                                                        <div class="info-box-content">
                                                            <span class="info-box-text">Montant</span>
                                                            <span class="info-box-number">
                                                            {{ order.amount.toFixed(2)+' €' }}
                                                        </span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-md-6" v-if="order.isCreditContext">
                                                    <div class="info-box">
                                                        <span :class="'info-box-icon ' +((order.user.credit > 0) ? 'bg-green' : 'bg-red')"><i class="fa fa-user"></i></span>
                                                        <div class="info-box-content">
                                                            <span class="info-box-text">Crédit utilisateur</span>
                                                            <span class="info-box-number">
                                                            {{ order.user.credit.toFixed(2).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,")+' €' }}
                                                        </span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="row">
                                                <div class="col-md-12">
                                                    <h4>Historique paiements</h4>
                                                    <table class="table table-condensed table-bordered table-hover" v-if="order.paymentsArray && order.paymentsArray.length > 0">
                                                        <thead>
                                                            <tr>
                                                                <td>Date</td>
                                                                <td>Origine action</td>
                                                                <td>Type</td>
                                                                <td>Moyen</td>
                                                                <td>Montant</td>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr v-for="payment in order.paymentsArray">
                                                                <td>{{ payment.date }}</td>
                                                                <td>{{ payment.user_action }}</td>
                                                                <td>{{ payment.wording_type }}</td>
                                                                <td>{{ payment.wording_mean_payment }}</td>
                                                                <td v-html="payment.amount"></td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                    <div class="alert alert-info" v-else>
                                                        Aucun paiement rattaché à commande.
                                                    </div>
                                                    <div class="alert alert-success" v-if="order.isPaidViaInvoice">
                                                        La commande est payée via la <a :href="UrlManager.getBaseUrl()+'invoice/update?id='+order.id_invoice">facture</a> à laquelle elle est rattachée.
                                                    </div>
                                                </div>
                                            </div>

                                        </div>
                                    </modal>
                                </td>
                                <td v-if="producer && producer.tiller" class="tiller column-tiller">
                                    <input v-if="order.tiller_synchronization == true" type="checkbox" checked="checked" :id="'checkbox-tiller-synchronization-'+order.id" :data-id-order="order.id" @change="changeSynchroTiller" />
                                    <input v-else type="checkbox" :id="'checkbox-tiller-synchronization-'+order.id" :data-id-order="order.id" @change="changeSynchroTiller" />
                                    <label :for="'checkbox-tiller-synchronization-'+order.id">Tiller</label>
                                </td>
                            </tr>
                            <tr class="view" v-if="showViewProduct && idOrderView == order.id">
                                <td colspan="6">
                                    <strong><span class="glyphicon glyphicon-menu-right"></span> Produits</strong>
                                    <ul>
                                        <li v-for="product in products" v-if="getProductDistribution(product) && order.productOrder[product.id].quantity > 0">
                                            {{ product.name }} : {{ order.productOrder[product.id].quantity }} {{ order.productOrder[product.id].unit == 'piece' ? ' pièce(s)' : ' '+order.productOrder[product.id].unit }} <span v-if="getProductDistribution(product).active == 0" class="glyphicon glyphicon-warning-sign" title="Ce produit n'est pas activé"></span>
                                        </li>
                                    </ul>
                                    <div v-if="order.comment && order.comment.length > 0" class="comment">
                                        <strong><span class="glyphicon glyphicon-menu-right"></span> Commentaire</strong><br />
                                        {{ order.comment }}
                                    </div>

                                    <div v-if="order.delivery_home && order.delivery_address && order.delivery_address.length > 0" class="delivery">
                                        <strong><span class="glyphicon glyphicon-menu-right"></span> Livraison à domicile</strong><br />
                                        {{ order.delivery_address }}
                                    </div>
                                </td>
                            </tr>
                        </template>
                    </tbody>
                </table>
                <div class="alert alert-warning" v-else>
                    Aucune commande
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/x-template" id="order-state-payment">
    <span v-html="order.paymentLabelShort"></span>
</script>

<!-- template for the order-form component -->
<script type="text/x-template" id="order-form-template">
    <modal class="modal-form-order" @close="$emit('close')">
        <h3 v-if="order.id" slot="header">
            <template v-if="order.id">Modifier</template>
            <template v-else>Ajouter</template>
            une commande - {{ dateFormat }}
        </h3>
        <div slot="body">
            <div class="callout callout-warning" v-if="errors.length">
                <ul>
                    <li v-for="error in errors">{{ error }}</li>
                </ul>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    <a v-if="producer && producer.credit && order.id_user > 0 && user.id_user == order.id_user" class="btn btn-xs btn-primary btn-credit" :href="baseUrl+'/user/credit?id='+user.id_user" v-for="user in users">{{ parseFloat(user.credit).toFixed(2).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,")+'&nbsp;€' }}</a>
                    <label class="control-label" for="select-id-user">
                        Utilisateur
                    </label>
                    <select class="form-control select2-order-form" v-model="order.id_user" @change="userChange">
                        <option value="0">--</option>
                        <option v-for="user in users" :value="user.id_user">
                                <template v-if="user.name_legal_person && user.name_legal_person.length">
                                        {{ user.name_legal_person  }} (personne morale)
                                </template>
                                <template v-else>
                                        {{ user.lastname +' '+ user.name }}
                                </template>
                        </option>
                    </select>
                    <input v-model="order.username" type="text" class="form-control" placeholder="Ou saisissez ici le nom de l'utilisateur" />
                </div>
                <div class="form-group">
                    <label class="control-label" for="select-id-point-sale">Point de vente</label>
                    <select class="form-control" id="select-id-point-sale" v-model="order.id_point_sale" @change="pointSaleChange">
                        <option value="0">--</option>
                        <option v-for="pointSale in pointsSale" v-if="pointSale.pointSaleDistribution[0].delivery == 1" :value="pointSale.id"">{{ pointSale.name }}</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="control-label" for="textarea-comment">Commentaire</label>
                    <textarea class="form-control" id="textarea-comment" v-model="order.comment"></textarea>
                </div>
                <div class="form-group" v-if="isPointSaleCreditFunctioningOptional(order.id_point_sale)">
                    <input type="checkbox" id="debit-credit" v-model="order.debitCredit" />
                    <label class="control-label" for="debit-credit">Débiter le crédit</label>
                </div>
            </div>
            <div class="col-md-8">
                <label class="control-label">Produits</label>
                <table class="table table-condensed table-bordered table-hover table-products">
                    <thead>
                        <tr>
                            <th></th>
                            <th>Nom</th>
                            <th>Prix unitaire</th>
                            <th>Quantité</th>
                            <th>Reste</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="product in products" v-if="product.status >= 0 || order.productOrder[product.id].quantity > 0" :class="(order.productOrder[product.id].quantity > 0) ? 'product-ordered' : ''">
                            <td>
                                <span class="label label-success" v-if="loadingUpdateProductOrder || order.productOrder[product.id].active">Actif</span>
                                <span class="label label-danger" v-else>Inactif</span>
                            </td>
                            <td>
                                {{ product.name }}
                                <template v-if="product.weight">({{ product.weight }} g)</template>
                            </td>
                            <td class="price">
                                    <div v-show="vatMode == 'all'" class="input-group">
                                        <input type="text" v-model="order.productOrder[product.id].price" class="form-control input-sm" @change="productPriceChange" :data-with-tax="false" :data-id-product="product.id" />
                                        <span class="input-group-addon" id="basic-addon2">€ HT&nbsp;&nbsp;</span>
                                    </div>
                                    <div class="input-group">
                                            <input type="text" v-model="order.productOrder[product.id].price_with_tax" class="form-control input-sm" @change="productPriceChange" :data-with-tax="true" :data-id-product="product.id" />
                                            <span class="input-group-addon" id="basic-addon2">€ TTC</span>
                                    </div>
                                    <div class="invoice-price" v-show="vatMode == 'all'" v-if="(order.id_invoice || order.id_delivery_note || order.id_quotation) && order.productOrder[product.id].quantity > 0">
                                        <span class="label-invoice-price">Prix facturé</span><br />
                                        <div class="input-group">
                                            <input v-if="order.isLinkedToValidInvoice" type="text" v-model="order.productOrder[product.id].invoice_price" class="form-control input-sm" :data-id-product="product.id" disabled="disabled" title="La commande est liée à une facture validée, le prix facturé n'est donc plus modifiable" />
                                            <input v-else type="text" v-model="order.productOrder[product.id].invoice_price" class="form-control input-sm" :data-id-product="product.id" />
                                            <span class="input-group-addon" id="basic-addon2">€ HT</span>
                                        </div>
                                    </div>
                            </td>
                            <td class="quantity">
                                <div class="input-group">
                                    <span class="input-group-btn">
                                        <button class="btn btn-default btn-moins" type="button" @click="productQuantityClick(product.id, order.productOrder[product.id].unit == 'piece' ? -1 : -parseFloat(product.step))"><span class="glyphicon glyphicon-minus"></span></button>
                                    </span>
                                    <input type="text" v-model="order.productOrder[product.id].quantity" class="form-control input-quantity" />
                                    <span class="input-group-addon">{{ order.productOrder[product.id].unit == 'piece' ? 'p.' : order.productOrder[product.id].unit }}</span>
                                    <span class="input-group-btn">
                                        <button class="btn btn-default btn-plus" type="button" @click="productQuantityClick(product.id, order.productOrder[product.id].unit == 'piece' ? 1 : parseFloat(product.step))"><span class="glyphicon glyphicon-plus"></span></button>
                                    </span>
                                </div>
                            </td>
                            <td class="quantity-remaining infinite" v-if="product.quantity_remaining === null || order.productOrder[product.id].unit != product.unit">&infin;</td>
                            <td class="quantity-remaining negative" v-else-if="getProductQuantityRemaining(product) <= 0">
                                {{ getProductQuantityRemaining(product) }} {{ order.productOrder[product.id].unit == 'piece' ? ' p.' : ' '+(order.productOrder[product.id].unit == 'g' || order.productOrder[product.id].unit == 'kg') ? 'kg' : 'litre(s)' }}
                                <span class="glyphicon glyphicon-alert" v-if="getProductQuantityRemaining(product) < 0"></span>
                            </td>
                            <td class="quantity-remaining has-quantity" v-else>{{ getProductQuantityRemaining(product) }} {{ order.productOrder[product.id].unit == 'piece' ? ' p.' : ' '+(order.productOrder[product.id].unit == 'g' || order.productOrder[product.id].unit == 'kg') ? 'kg' : 'litre(s)' }}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div slot="footer">
            <div class="actions-form">
                <button class="modal-default-button btn btn-danger" @click="$emit('close')">Fermer</button>

                <button class="modal-default-button btn btn-primary" @click="submitFormUpdate" v-if="order.id">Modifier</button>
                <button class="modal-default-button btn btn-primary" @click="submitFormCreate" v-if="!order.id">Créer</button>

                <div class="right">
                    <button class="modal-default-button btn btn-info btn-update-prices" @click="updateProductOrderPrices(true)">Recharger les prix</button>
                    <button v-if="order.id" class="modal-default-button btn btn-info btn-update-prices" @click="updateInvoicePrices(true)">
                        Réinitialiser les prix facturés
                    </button>
                    <button class="modal-default-button btn btn-info btn-display-prices-without-tax" @click="toggleVatMode()">
                        <template v-if="vatMode == 'all'">Cacher</template>
                        <template v-else>Afficher</template>
                        les prix HT
                    </button>
                </div>
            </div>
        </div>
    </modal>
</script>

<!-- template for the modal component -->
<script type="text/x-template" id="modal-template">
  <transition name="modal">
    <div class="modal-mask">
      <div class="modal-wrapper">
        <div class="modal-container">

          <div class="modal-header">
            <slot name="header"></slot>
          </div>

          <div class="modal-body">
            <slot name="body"></slot>
          </div>

          <div class="modal-footer">
            <slot name="footer">
              <button class="modal-default-button btn btn-default" @click="$emit('close')">Fermer</button>
            </slot>
          </div>
        </div>
      </div>
    </div>
  </transition>
</script>

