<template>
  <div class="main-content">
    <breadcumb :page="$t('Societe')" :folder="$t('hrm')" />

    <div v-if="isLoading" class="loading_page spinner spinner-primary mr-3"></div>
    <b-card class="wrapper" v-if="!isLoading">
      <b-row>
        <b-col lg="3" md="3" sm="12">
          <b-form-group :label="$t('Facturation')">
            <v-select @input="Selected_Facture" v-model="Filter_IsFacture" :reduce="label => label.value"
              :placeholder="$t('Choose_Facturation')" :options="[
                { label: 'Facturé', value: 1 },
                { label: 'Non facturé', value: 0 },
              ]"></v-select>
          </b-form-group>
        </b-col>
        <b-col lg="3" md="3" sm="12">
          <b-form-group :label="$t('Date')">
            <date-range-picker v-model="dateRange" :startDate="startDate" :endDate="endDate" @update="Filter_dateRange"
              :locale-data="locale">

              <template v-slot:input="picker" style="min-width: 350px;">
                {{ picker.startDate.toJSON().slice(0, 10) }} - {{ picker.endDate.toJSON().slice(0, 10) }}
              </template>
            </date-range-picker>
          </b-form-group>
        </b-col>
      </b-row>
      <vue-good-table mode="remote" :columns="columns" :totalRows="totalRows" :rows="societes" :group-options="{
        enabled: true,
        headerPosition: 'bottom',
      }" @on-page-change="onPageChange" @on-per-page-change="onPerPageChange" @on-sort-change="onSortChange"
        @on-search="onSearch" :search-options="{
          enabled: true,
          placeholder: $t('Search_this_table'),
        }" :select-options="{
          enabled: true,
          clearSelectionText: '',
        }" @on-selected-rows-change="selectionChanged" :pagination-options="{
          enabled: true,
          mode: 'records',
          nextLabel: 'next',
          prevLabel: 'prev',
        }" styleClass="table-hover tableOne vgt-table">
        <!-- 
          <div slot="selected-row-actions">
            <button class="btn btn-danger btn-sm" @click="delete_by_selected()">{{$t('Del')}}</button>
          </div>
          <div slot="table-actions" class="mt-2 mb-3">
            <b-button
              @click="New_Societe()"
              class="btn-rounded"
              variant="btn btn-primary btn-icon m-1"
            >
              <i class="i-Add"></i>
              {{$t('Add')}}
            </b-button>
          </div>
         -->

        <template slot="table-row" slot-scope="props">
          <span v-if="props.column.field == 'actions'">
            <a @click="Edit_Societe(props.row)" class="cursor-pointer" title="Edit" v-b-tooltip.hover>
              <i class="i-Edit text-25 text-success"></i>
            </a>
            <a title="Delete" v-b-tooltip.hover class="cursor-pointer" @click="Remove_Societe(props.row.id)">
              <i class="i-Close-Window text-25 text-danger"></i>
            </a>
          </span>
        </template>
      </vue-good-table>
    </b-card>

    <validation-observer ref="Create_Societe">
      <b-modal hide-footer size="lg" id="New_Societe" :title="editmode ? $t('Edit') : $t('Add')">
        <b-form @submit.prevent="Submit_Societe">
          <b-row>
            <!-- Name -->
            <b-col md="6">
              <validation-provider name="Name" :rules="{ required: true }" v-slot="validationContext">
                <b-form-group :label="$t('Name') + ' ' + '*'">
                  <b-form-input :placeholder="$t('Enter_Societe_Name')" :state="getValidationState(validationContext)"
                    aria-describedby="Name-feedback" label="Name" v-model="societe.name"></b-form-input>
                  <b-form-invalid-feedback id="Name-feedback">{{ validationContext.errors[0]
                    }}</b-form-invalid-feedback>
                </b-form-group>
              </validation-provider>
            </b-col>

            <!-- Email -->
            <b-col md="6">
              <b-form-group :label="$t('Email')">
                <b-form-input :placeholder="$t('Enter_email_address')" label="Email"
                  v-model="societe.email"></b-form-input>
              </b-form-group>
            </b-col>

            <!-- Number -->
            <b-col md="6">
              <b-form-group :label="$t('Number')">
                <b-form-input :placeholder="$t('Enter_Societe_Number')" label="Number"
                  v-model="societe.number"></b-form-input>
              </b-form-group>
            </b-col>

            <!-- ICE -->
            <b-col md="6">
              <b-form-group :label="$t('ICE')">
                <b-form-input :placeholder="$t('Enter_Societe_ICE')" label="ICE" v-model="societe.ice"></b-form-input>
              </b-form-group>
            </b-col>

            <!-- Address -->
            <b-col md="12">
              <b-form-group :label="$t('Address')">
                <b-form-input :placeholder="$t('Enter_Societe_Address')" label="Address"
                  v-model="societe.address"></b-form-input>
              </b-form-group>
            </b-col>

            <b-col md="12" class="mt-3">
              <b-button variant="primary" type="submit" :disabled="SubmitProcessing"><i
                  class="i-Yes me-2 font-weight-bold"></i> {{ $t('submit') }}</b-button>
              <div v-once class="typo__p" v-if="SubmitProcessing">
                <div class="spinner sm spinner-primary mt-3"></div>
              </div>
            </b-col>

          </b-row>
        </b-form>
      </b-modal>
    </validation-observer>
  </div>
</template>

<script>
import NProgress from "nprogress";

import DateRangePicker from 'vue2-daterange-picker'
//you need to import the CSS manually
import 'vue2-daterange-picker/dist/vue2-daterange-picker.css'
import moment from 'moment'

export default {
  components: {
    DateRangePicker,
  },
  metaInfo: {
    title: "Societe"
  },
  data() {
    return {
      isLoading: true,
      SubmitProcessing: false,
      serverParams: {
        columnFilters: {},
        sort: {
          field: "id",
          type: "desc"
        },
        page: 1,
        perPage: 10
      },
      selectedIds: [],
      totalRows: "",
      search: "",
      limit: "10",
      societes: [],
      editmode: false,
      societe: {
        name: "",
        email: "",
        ice: "",
        number: "",
        address: "",
      },

      today_mode: true,
      startDate: "",
      endDate: "",
      dateRange: {
        startDate: "",
        endDate: ""
      },
      locale: {
        //separator between the two ranges apply
        Label: "Apply",
        cancelLabel: "Cancel",
        weekLabel: "W",
        customRangeLabel: "Custom Range",
        daysOfWeek: moment.weekdaysMin(),
        //array of days - see moment documenations for details 
        monthNames: moment.monthsShort(), //array of month names - see moment documenations for details 
        firstDay: 1 //ISO first day of week - see moment documenations for details
      },

      Filter_IsFacture: "",
    };
  },

  computed: {
    columns() {
      return [
        {
          label: this.$t("Name"),
          field: "name",
          tdClass: "text-left",
          thClass: "text-left"
        },
        {
          label: this.$t("Number"),
          field: "number",
          tdClass: "text-left",
          thClass: "text-left"
        },
        {
          label: this.$t("ICE"),
          field: "ice",
          tdClass: "text-left",
          thClass: "text-left"
        },
        {
          label: this.$t("Email"),
          field: "email",
          tdClass: "text-left",
          thClass: "text-left"
        },
        {
          label: this.$t("Address"),
          field: "address",
          tdClass: "text-left",
          thClass: "text-left"
        },
        {
          label: this.$t("TotalSales"),
          field: "total_sales",
          tdClass: "text-left",
          thClass: "text-left"
        },
        {
          label: this.$t("TotalPurchases"),
          field: "total_purchases",
          tdClass: "text-left",
          thClass: "text-left"
        },
        {
          label: this.$t("Total Expenses"),
          field: "total_expenses",
          tdClass: "text-left",
          thClass: "text-left"
        },
        {
          label: this.$t("Profit"),
          field: "profit",
          tdClass: "text-left",
          thClass: "text-left"
        },
        /*{
          label: this.$t("Action"),
          field: "actions",
          html: true,
          tdClass: "text-right",
          thClass: "text-right",
          sortable: false
        }*/
      ];
    }
  },

  methods: {
    Selected_Facture(value) {
      if (value === null) {
        this.Filter_IsFacture = "";
      }
      console.log("Selected_Facture: v - ", value, " | f: ", this.Filter_IsFacture);

      this.Get_Societe(1);
    },

    get_data_loaded() {
      if (this.today_mode) {
        let today = new Date()

        this.startDate = new Date(today.getFullYear(), today.getMonth(), 1).toJSON().slice(0, 10);
        this.endDate = new Date(today.getFullYear(), today.getMonth() + 1, 0).toJSON().slice(0, 10);

        this.dateRange.startDate = new Date(today.getFullYear(), today.getMonth(), 1).toJSON().slice(0, 10);
        this.dateRange.endDate = new Date(today.getFullYear(), today.getMonth() + 1, 0).toJSON().slice(0, 10);
      }
    },

    //---------------------- Event Select DateRange ------------------------------\\
    Filter_dateRange() {
      this.startDate = this.dateRange.startDate.toJSON().slice(0, 10);
      this.endDate = this.dateRange.endDate.toJSON().slice(0, 10);
      this.today_mode = false;
      this.Get_Societe(1);
    },

    //---- update Params Table
    updateParams(newProps) {
      this.serverParams = Object.assign({}, this.serverParams, newProps);
    },

    //---- Event Page Change
    onPageChange({ currentPage }) {
      if (this.serverParams.page !== currentPage) {
        this.updateParams({ page: currentPage });
        this.Get_Societe(currentPage);
      }
    },

    //---- Event Per Page Change
    onPerPageChange({ currentPerPage }) {
      if (this.limit !== currentPerPage) {
        this.limit = currentPerPage;
        this.updateParams({ page: 1, perPage: currentPerPage });
        this.Get_Societe(1);
      }
    },

    //---- Event Select Rows
    selectionChanged({ selectedRows }) {
      this.selectedIds = [];
      selectedRows.forEach((row, index) => {
        this.selectedIds.push(row.id);
      });
    },

    //---- Event Sort Change

    onSortChange(params) {
      this.updateParams({
        sort: {
          type: params[0].type,
          field: params[0].field
        }
      });
      this.Get_Societe(this.serverParams.page);
    },

    //---- Event Search
    onSearch(value) {
      this.search = value.searchTerm;
      this.Get_Societe(this.serverParams.page);
    },

    //---- Validation State Form
    getValidationState({ dirty, validated, valid = null }) {
      return dirty || validated ? valid : null;
    },

    //------------- Submit Validation Create & Edit Societe
    Submit_Societe() {
      this.$refs.Create_Societe.validate().then(success => {
        if (!success) {
          this.makeToast(
            "danger",
            this.$t("Please_fill_the_form_correctly"),
            this.$t("Failed")
          );
        } else {
          if (!this.editmode) {
            this.Create_Societe();
          } else {
            this.Update_Societe();
          }
        }
      });
    },

    //------ Toast
    makeToast(variant, msg, title) {
      this.$root.$bvToast.toast(msg, {
        title: title,
        variant: variant,
        solid: true
      });
    },

    //------------------------------ Modal (create societe) -------------------------------\\
    New_Societe() {
      this.reset_Form();
      this.editmode = false;
      this.$bvModal.show("New_Societe");
    },

    //------------------------------ Modal (Update societe) -------------------------------\\
    Edit_Societe(societe) {
      this.Get_Societe(this.serverParams.page);
      this.reset_Form();
      this.societe = societe;
      this.editmode = true;
      this.$bvModal.show("New_Societe");
    },

    //--------------------------Get ALL societe ---------------------------\\

    Get_Societe(page) {
      // Start the progress bar.
      NProgress.start();
      NProgress.set(0.1);
      this.get_data_loaded();
      let date = "&from=" + this.startDate + "&to=" + this.endDate;
      axios
        .get(
          "societe?page=" +
          page +
          "&SortField=" +
          this.serverParams.sort.field +
          "&SortType=" +
          this.serverParams.sort.type +
          "&search=" +
          this.search +
          "&limit=" +
          this.limit +
          "&facturation=" +
          this.Filter_IsFacture + (this.today_mode == true ? '' : date)
        )
        .then(response => {
          this.societes = response.data.societes;
          this.totalRows = response.data.totalRows;

          // Complete the animation of theprogress bar.
          NProgress.done();
          this.isLoading = false;
        })
        .catch(response => {
          // Complete the animation of theprogress bar.
          NProgress.done();
          setTimeout(() => {
            this.isLoading = false;
          }, 500);
        });
    },

    //------------------------------- Create societe ------------------------\\
    Create_Societe() {

      this.SubmitProcessing = true;
      axios
        .post("societe", {
          name: this.societe.name,
          email: this.societe.email,
          ice: this.societe.ice,
          number: this.societe.number,
          address: this.societe.address,

        })
        .then(response => {
          this.SubmitProcessing = false;
          Fire.$emit("Event_Societe");
          this.makeToast(
            "success",
            this.$t("Created_in_successfully"),
            this.$t("Success")
          );
        })
        .catch(error => {
          this.SubmitProcessing = false;
          this.makeToast("danger", this.$t("InvalidData"), this.$t("Failed"));
        });
    },

    //------------------------------- Update societe ------------------------\\
    Update_Societe() {
      this.SubmitProcessing = true;
      axios
        .put("societe/" + this.societe.id, {
          name: this.societe.name,
          email: this.societe.email,
          ice: this.societe.ice,
          number: this.societe.number,
          address: this.societe.address,
        })
        .then(response => {
          this.SubmitProcessing = false;
          Fire.$emit("Event_Societe");

          this.makeToast(
            "success",
            this.$t("Updated_in_successfully"),
            this.$t("Success")
          );
        })
        .catch(error => {
          this.SubmitProcessing = false;
          this.makeToast("danger", this.$t("InvalidData"), this.$t("Failed"));
        });
    },

    //------------------------------- reset Form ------------------------\\
    reset_Form() {
      this.societe = {
        id: "",
        name: "",
        email: "",
        ice: "",
        number: "",
        address: "",
      };
    },

    //------------------------------- Delete societe ------------------------\\
    Remove_Societe(id) {
      this.$swal({
        title: this.$t("Delete.Title"),
        text: this.$t("Delete.Text"),
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        cancelButtonText: this.$t("Delete.cancelButtonText"),
        confirmButtonText: this.$t("Delete.confirmButtonText")
      }).then(result => {
        if (result.value) {
          axios
            .delete("societe/" + id)
            .then(() => {
              this.$swal(
                this.$t("Delete.Deleted"),
                this.$t("Deleted_in_successfully"),
                "success"
              );

              Fire.$emit("Delete_Societe");
            })
            .catch(() => {
              this.$swal(
                this.$t("Delete.Failed"),
                this.$t("Delete.Therewassomethingwronge"),
                "warning"
              );
            });
        }
      });
    },

    //---- Delete societe by selection

    delete_by_selected() {
      this.$swal({
        title: this.$t("Delete.Title"),
        text: this.$t("Delete.Text"),
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        cancelButtonText: this.$t("Delete.cancelButtonText"),
        confirmButtonText: this.$t("Delete.confirmButtonText")
      }).then(result => {
        if (result.value) {
          // Start the progress bar.
          NProgress.start();
          NProgress.set(0.1);
          axios
            .post("societe/delete/by_selection", {
              selectedIds: this.selectedIds
            })
            .then(() => {
              this.$swal(
                this.$t("Delete.Deleted"),
                this.$t("Deleted_in_successfully"),
                "success"
              );

              Fire.$emit("Delete_Societe");
            })
            .catch(() => {
              // Complete the animation of theprogress bar.
              setTimeout(() => NProgress.done(), 500);
              this.$swal(
                this.$t("Delete.Failed"),
                this.$t("Delete.Therewassomethingwronge"),
                "warning"
              );
            });
        }
      });
    }
  },

  //----------------------------- Created function-------------------\\

  created: function () {
    this.Get_Societe(1);

    Fire.$on("Event_Societe", () => {
      setTimeout(() => {
        this.Get_Societe(this.serverParams.page);
        this.$bvModal.hide("New_Societe");
      }, 500);
    });

    Fire.$on("Delete_Societe", () => {
      setTimeout(() => {
        this.Get_Societe(this.serverParams.page);
      }, 500);
    });
  }
};
</script>