<template>
  <div>
    <div class="ay-c-form-card-grid">
      <form-card
        title="TRM"
        color-scheme="scheme_primary"
        icon="i-calendar"
      >
        <form
          class="ay-form"
          data-vv-scope="form-trm-create"
          @submit.prevent="onSubmitScope('form-trm-create')"
          @reset="onReset"
        >
          <v-input
            ref="vInputTrmCreate"
            v-model="form.mtrm_fecha"
            :label="$ml.get('field.current_trm_date')"
            name="trm"
            type="date"
            validate="required"
            scope="form-trm-create"
          />
          <v-input
            ref="vInputLocalTrmCreate"
            v-model="form.mtrm_valorusd"
            :label="$ml.get('field.local_trm_value')"
            name="localTrm"
            type="number"
            validate="required"
            scope="form-trm-create"
          />
          <v-input
            ref="vInputOfficialTrmCreate"
            v-model="form.mtrm_valorusd_oficial"
            :label="$ml.get('field.official_trm_value')"
            name="officialTrm"
            type="number"
            validate="required"
            scope="form-trm-create"
          />
          <button
            class="ay-btn ay-btn-ico i-plus"
            type="submit"
            :disabled="errors.any('form-trm-create')"
          >
            {{ $ml.get('btn.add') }}
          </button>
          <button
            class="ay-btn ay-btn-ico i-edit"
            type="reset"
          >
            {{ $ml.get('btn.clear') }}
          </button>
        </form>
      </form-card>
    </div>
    <div class="ay-c-form-card-grid">
      <table
        class="ay-table.ay-table_center h-horizontal-align"
        sumary="Resumen del contenido de una tabla"
      >
        <thead class="ay-table__head">
          <tr class="ay-table__row">
            <th
              id="n-id"
              class="ay-table__head-cell"
            >
              #
            </th>
            <th
              v-for="(field, index) in table.fields"
              id="n-fee"
              :key="index"
              class="ay-table__head-cell"
            >
              {{ field.label }}
            </th>
            <th
              id="n-accions"
              class="ay-table__head-cell"
            >
              Acciones
            </th>
          </tr>
        </thead>
        <tbody
          ref="tbodyTRMContainer"
          class="ay-table__body"
        >
          <tr
            v-for="(item, index) in table.items"
            :key="item.key"
            class="ay-table__row ay-table__row_error"
          >
            <td
              class="ay-table__cell"
              headers="n-id"
            >
              {{ index + 1 }}
            </td>
            <td
              class="ay-table__cell"
              headers="n-id"
            >
              {{ item.mtrm_fecha }}
            </td>
            <td
              class="ay-table__cell"
              headers="n-fee"
            >
              {{ item.mtrm_valorusd }}
            </td>
            <td
              class="ay-table__cell"
              headers="n-fee"
            >
              {{ item.mtrm_valorusd_oficial }}
            </td>
            <td
              class="ay-table__cell"
              headers="n-accions"
            >
              <button
                class="ay-btn ay-btn_primary ay-btn-ico i-edit"
                style="{padding: 10px 16px;}"
                type="button"
                @click="editItem(index)"
              >
                {{ $ml.get('btn.edit') }}
              </button>
              <button
                class="ay-btn ay-btn_tertiary"
                type="button"
                @click="deleteItem(item)"
              >
                {{ $ml.get('btn.remove') }}
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <v-modal
      title="Actualizar TRM"
      :class="{'ay-c-modal_show' : modal.visibility === true}"
      @close="closeModal"
    >
      <form
        class="ay-form"
        data-vv-scope="form-trm-edit"
        @submit.prevent="onSubmitScope('form-trm-edit')"
        @reset="onReset"
      >
        <div class="ay-c-modal__set">
          <p class="ay-c-modal__txt">
            {{ $ml.get('message.do_you_want_to_continue_with_the_trm_update') }}
          </p>
          <v-input
            ref="vInputTrmEdit"
            v-model="formEdit.mtrm_fecha"
            :label="$ml.get('field.current_trm_date')"
            name="trm"
            type="date"
            validate="required"
            scope="form-trm-edit"
          />
          <v-input
            ref="vInputLocalTrmEdit"
            v-model="formEdit.mtrm_valorusd"
            :label="$ml.get('field.local_trm_value')"
            name="localTrm"
            type="number"
            validate="required"
            scope="form-trm-edit"
          />
          <v-input
            ref="vInputOfficialTrmEdit"
            v-model="formEdit.mtrm_valorusd_oficial"
            :label="$ml.get('field.official_trm_value')"
            name="officialTrm"
            type="number"
            validate="required"
            scope="form-trm-edit"
          />
        </div>
        <div class="ay-c-modal__actions">
          <button
            class="ay-btn ay-btn_outline"
            type="submit"
            :disabled="errors.any('form-trm-edit')"
          >
            {{ $ml.get('btn.save') }}
          </button>
          <button
            class="ay-btn ay-btn_tertiar"
            type="button"
            @click="closeModal"
          >
            {{ $ml.get('btn.cancel') }}
          </button>
        </div>
      </form>
    </v-modal>
  </div>
</template>

<script>
/**
 * @fileoverview  TRM
 * @version       0.1
 * @author        Miguel Ortiz <miguel.ortiz@decameron.com>
 */

/**
 * Coomponentes
 */
import FormCard from '@/FormCard';
import Input from '@/Input';
import Modal from '@/Modal';

/**
 * Constantes para este componente
 */
const VIEW_NAME = 'demo'

export default {
    name: VIEW_NAME,
    components: {
      'form-card': FormCard,
      'v-input': Input,
      'v-modal': Modal
    },
    props: {
      lang: {
          type: String,
          default: 'es'
      }
    },
    data() {
      return {
        modal: {
          visibility: false,
        },
        form: this.getDefaultForm(),
        formEdit: this.getDefaultForm(),
        show: true,
        update_post: {
          title: 'Juan'
        },
        base: {},
        table: {
          isBusy: false,
          sortBy: 'trm',
          sortDesc: false,
          fields: [
            { key: 'trm', label: this.$ml.get('field.current_trm_date'), sortable: true },
            { key: 'localTrm', label: this.$ml.get('field.local_trm_value'), sortable: true },
            { key: 'officialTrm', label: this.$ml.get('field.official_trm_value'), sortable: true },
          ],
          items: [
            { mtrm_id: 1, mtrm_fecha: '2019-04-30', mtrm_valorusd: '5', mtrm_valorusd_oficial: '6' },
            { mtrm_id: 2, mtrm_fecha: '2018-03-20', mtrm_valorusd: '2', mtrm_valorusd_oficial: '7' },
          ]
        },
        loaders:{
          table: null
        },
        isloading: false
      }
    },
    computed: {},
    watch: {},
    mounted () {
      this.$nextTick(() => {

        // Idioma
        this.$validator.localize(this.lang)
        this.$ml.change(this.lang)
      })   
    },
    methods: {
      /**
       * Alerta de confirmación
       */
      alertConfirmation({title, text, type, callback}) {
          this.$swal({
              title,
              text,
              type,
              showCancelButton: true,
              confirmButtonColor: '#3085d6',
              cancelButtonColor: '#d33',
              confirmButtonText: 'Continuar',
              cancelButtonText: 'Cancelar'
          }).then((result) => {
              if (result.value) {
                  callback();
              }
          });
      },
      /**
       * Alerta de confirmación
       */
      alertToastr({type, title, text}) {
        this.$swal({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000,
            type: type,
            title: title,
            text: text
        });
      },
      /**
       * Limpia los errores del validador
       */
      clearErrors () {
        if (this.errors.any()) {
          this.errors.clear()
        }
      },
      /**
       * Limpia el formulario
       */
      clearForm () {
        // Recorrer formulario dependiendo del tipo de dato
        this.form.mtipmda_id = null
        this.form.mtrm_fecha = null
        this.form.mtrm_valorusd = null
        this.form.mtrm_valorusd_oficial = null
      
        let self = this
        setTimeout(() => {
          self.clearErrors()
        }, 500)
      },
      /**
       * Edita el item de la tabla
       */
      editItem(index){

        // No se iguala el objeto ya que duplica los oyentes
        this.formEdit.mtrm_id = this.table.items[index].mtrm_id
        this.formEdit.mtrm_fecha = this.table.items[index].mtrm_fecha
        this.formEdit.mtrm_valorusd = this.table.items[index].mtrm_valorusd
        this.formEdit.mtrm_valorusd_oficial = this.table.items[index].mtrm_valorusd_oficial

        this.openModal()
      },
      /**
       * Retorna el prototipo FormTask vacio
       */
      getDefaultForm() {
        return {
           mtrm_fecha: null,
           mtrm_valorusd: null,
           mtrm_valorusd_oficial: null
        }
      },
      /**
       * Retorna un número aleatorio entre min (incluido) y max (excluido
       */
      getRandomArbitrary(min, max) {
         return Math.random() * (max - min) + min;
      },
      /**
       * Elimina el item de la tabla
       * @param   {Object} item
       * Corresponde al elemento de la tabla.
       * @returns {null}
       */
      deleteItem(item){
        this.alertConfirmation({
          title: '¿Estás seguro de continuar?',
          type: 'warning',
          callback: async () => {
            const searchItem = (elem) => elem === item; //Obtenemos el item completo
            const itemObj = this.table.items.find(searchItem); //Obtenemos el item completo
            const indexObj = this.table.items.findIndex(searchItem); //Obtenemos la posicion que ocupa en el array
              this.table.items = [
                ...this.table.items.slice(0, indexObj),
                ...this.table.items.slice(indexObj + 1)
              ];
              this.alertToastr({
                  type: 'success',
                  title: 'Eliminado Correctamente'
              });
          }
        });
      },
      onSubmitScope(scope){
        this.$validator.validateAll(scope).then((result) => {
          if (result) {
            if(scope == 'form-trm-create'){
              this.onSubmitCreate();
            } else {
              this.onSubmitUpdate();
            }
          } 
        });
      },
      onSubmitCreate() {
        // this.form.mtrm_id = this.table.items.length + Math.floor((Math.random() * 100) + 1);
        this.isloading = true;
        this.alertConfirmation({
          title: '¿Estás seguro de continuar?',
          type: 'success',
          callback: async () => {
              this.form.mtipmda_id = this.getRandomArbitrary(1,10000)
              this.table.items = [...this.table.items, {
                mtrm_id: this.form.mtrm_id,
                mtrm_fecha: this.form.mtrm_fecha,
                mtrm_valorusd: this.form.mtrm_valorusd,
                mtrm_valorusd_oficial: this.form.mtrm_valorusd_oficial
              }]
              
              this.alertToastr({
                type: 'success',
                title: 'Creado Correctamente'
              })

              this.clearForm();
              this.show = false
              this.$nextTick(() => {
                  this.show = true
                  this.isloading = false;
              })
          }
        });
      },
      onSubmitUpdate() {
        const searchItem = (elem) => elem.mtrm_id === this.formEdit.mtrm_id; //Obtenemos el item completo
        const itemObj = this.table.items.find(searchItem); //Obtenemos el item completo
        const indexObj = this.table.items.findIndex(searchItem); //Obtenemos la posicion que ocupa en el array
        this.isloading = true;
        this.closeModal();
        this.alertConfirmation({
          title: '¿Esta seguro de continuar?',
          type: 'warning',
          callback: async () => {
            this.table.items[indexObj].mtrm_fecha = this.formEdit.mtrm_fecha;
            this.table.items[indexObj].mtrm_valorusd = this.formEdit.mtrm_valorusd;
            this.table.items[indexObj].mtrm_valorusd_oficial = this.formEdit.mtrm_valorusd_oficial;

            this.alertToastr({
                type: 'success',
                title: 'Actualizado Correctamente'
            });
          }
        });
      },
      /**
       * Reset al formulario
       */
      onReset(evt) {
        evt.preventDefault()
        // Reset our form values
        this.clearForm();
        // Trick to reset/clear native browser form validation state
        this.show = false
        this.$nextTick(() => {
          this.show = true
        })
      },
      loading(container){
        return this.$loading.show({
          // Optional parameters
          container: this.$refs[container],
          color: '#469EC3',
          loader: 'dots',
          opacity: 0.5
        }); 
      },
      openModal () {
        this.modal.visibility = true
      },
      closeModal () {
        this.modal.visibility = false
      }
    }
}
</script>
