<template>
  <b-row>
    <b-col md="12">
      <table class="table">
        <thead>
          <tr class="text-center">
            <th @click="setColumnOrder('name')" :class="getClass('name')">
              <text-input
                v-if="searchBy == 'name'"
                ref="input-name"
                v-model="textToSearch"
                title
                placeholder="NOME"
                @blur="hiddenSearchBy"
                @change="searchOnKeyUP"
              />

              <span v-else @click="setSearchBy('name')">Nome</span>
            </th>

            <th>
              <text-input
                v-if="searchBy == 'cpf'"
                ref="input-cpf"
                v-model="textToSearch"
                title
                placeholder="CPF"
                @blur="hiddenSearchBy"
                @change="searchOnKeyUP"
              />

              <span v-else @click="setSearchBy('cpf')">CPF</span>
            </th>
            <th>
              <text-input
                v-if="searchBy == 'cellphone'"
                ref="input-cellphone"
                v-model="textToSearch"
                title
                placeholder="CELULAR"
                @blur="hiddenSearchBy"
                @change="searchOnKeyUP"
              />

              <span v-else @click="setSearchBy('cellphone')">CELULAR</span>
            </th>
            <th>
              <text-input
                v-if="searchBy == 'campaign'"
                ref="input-campaign"
                v-model="textToSearch"
                title
                placeholder="CAMPANHA"
                @blur="hiddenSearchBy"
                @change="searchOnKeyUP"
              />

              <span v-else @click="setSearchBy('campaign')">CAMPANHA</span>
            </th>
            <th>
              <text-input
                v-if="searchBy == 'city'"
                ref="input-city"
                v-model="textToSearch"
                title
                placeholder="CIDADE"
                @blur="hiddenSearchBy"
                @change="searchOnKeyUP"
              />

              <span v-else @click="setSearchBy('city')">CIDADE</span>
            </th>
            <th>
              <text-input
                v-if="searchBy == 'sector'"
                ref="input-sector"
                v-model="textToSearch"
                title
                placeholder="SETOR"
                @blur="hiddenSearchBy"
                @change="searchOnKeyUP"
              />

              <span v-else @click="setSearchBy('sector')">SETOR</span>
            </th>
            <th @click="setColumnOrder('created_at')" :class="getClass('created_at')">Data</th>
            <th>&nbsp;</th>
          </tr>
        </thead>

        <tbody>
          <tr
            v-for=" selfSignUp in selfSignUpsComputed"
            :key="selfSignUp.id"
            :class="{'bg-danger': !selfSignUp.completed, 'text-white': !selfSignUp.completed ||  selfSignUp.approved_at, 
    'bg-success': selfSignUp.completed && selfSignUp.approved_at}"
            @click="showSelfsignup(selfSignUp)"
          >
            <td>{{selfSignUp.name}}</td>
            <td>{{selfSignUp.cpf}}</td>
            <td>
              ({{selfSignUp.contact.ddd}}) {{selfSignUp.contact.number}}
              <font-awesome-icon
                class="text-success"
                icon="check"
                v-if="selfSignUp.contact.is_verified"
              />
            </td>

            <td v-if="selfSignUp.campaign">{{selfSignUp.campaign.name}}</td>
            <td v-else>-</td>

            <td
              v-if="selfSignUp.shipping_address"
            >{{selfSignUp.shipping_address.city.name}}/{{selfSignUp.shipping_address.city.state.uf}}</td>
            <td v-else>-</td>
            <td v-if="selfSignUp.sector">{{selfSignUp.sector.name}}</td>
            <td v-else>-</td>
            <td>{{selfSignUp.created_at | formatDateTimeDDMMAAAA}}</td>
            <td></td>
          </tr>
        </tbody>
      </table>
      <p v-if="loading" class="text-center">
        <b-spinner style="width: 3rem; height: 3rem;" label="Large Spinner" type="grow"></b-spinner>
      </p>

      <div class="text-center">
        <paginate
          :totalPages="pagination.totalPages"
          :activePage="pagination.currentPage"
          @to-page="toPage"
          @per-page="perPage"
        />
      </div>

      <p
        v-if="selfSignUpsComputed.length==0 && !loading"
        class="text-center"
      >Não há registro para a consulta</p>
    </b-col>

    <message-modal :message="alertMessage" />
    <show-selfsignup-modal :id="idToShow" @closed="searchSelfSignups" />
  </b-row>
</template>

<script>
import SelfSignUp from "@/services/resources/SelfSignUpAuthenticatedService";
import showSelfsignupModal from "@/components/modals/selfSignUp/show";
import MessageModal from "@/components/modals/MessageModal.vue";
import TextInput from "@/components/shared-components/inputs/TextInput.vue";
import Paginate from "@/components/shared-components/Paginate";

const service = SelfSignUp.build();

export default {
  name: "self-signup-list",
  props: {
    tab: {
      type: String,
      required: true,
      validator: value =>
        ["COMPLETE", "INCOMPLETE", "ALL", "APPROVED", "DISAPPROVED"].includes(
          value
        )
    }
  },
  components: {
    MessageModal,
    showSelfsignupModal,
    TextInput,
    Paginate
  },
  data() {
    return {
      alertMessage: "",
      loading: false,
      selfSignUps: [],
      idToShow: 0,
      textToSearch: "",
      searchBy: "",
      columnOrder: "created_at",
      columnOrderDirection: "DESC",
      pagination: {
        totalPages: 1,
        currentPage: 1,
        perPage: 20,
        total: 0
      }
    };
  },
  computed: {
    selfSignUpsComputed() {
      this.selfSignUps.forEach(selfSignUp => {
        if (
          selfSignUp.shipping_address &&
          selfSignUp.document_identification_type &&
          selfSignUp.document_identification_selfie_url &&
          selfSignUp.document_identification_photo_front_url &&
          selfSignUp.document_identification_photo_back_url
        ) {
          selfSignUp.completed = true;
        } else {
          selfSignUp.completed = false;
        }
      });

      return this.selfSignUps;
    },
    globalFilter() {
      let filter = {
        with:
          "billingAddress.city.state,shippingAddress.city.state,contact,sector,campaign,approvedBy,crm",
        no_registered: true,
        order_by: "created_at",
        order: "DESC",
        paginate: true,
        current_page: this.pagination.currentPage,
        per_page: this.pagination.perPage
      };

      if (this.tab === "COMPLETE") {
        filter.complete = true;
      } else if (this.tab === "INCOMPLETE") {
        filter.incomplete = true;
      } else if (this.tab === "APPROVED") {
        filter.approved = true;
      } else if (this.tab === "DISAPPROVED") {
        filter.disapproved = true;
      }

      return filter;
    }
  },
  watch: {
    pagination: {

      deep: true,
      handler(newValue){
        
        this.$emit("changeTotal", newValue.total);
      }
    }
  },
  methods: {
    toPage(page) {
      this.pagination.currentPage = page;
      this.searchSelfSignups();
    },
    perPage(qty) {
      this.pagination.currentPage = 1;
      this.pagination.perPage = qty;
      this.searchSelfSignups();
    },
    searchOnKeyUP: function searchOnKeyUP() {
      if (this.textToSearch.length == 0) {
        return;
      }
      clearTimeout(searchOnKeyUP.timeout);
      var vm = this;
      searchOnKeyUP.timeout = setTimeout(function() {
        vm.searchSelfSignups();
      }, 500);
    },
    setColumnOrder(column) {
      if (this.columnOrder == column) {
        this.columnOrderDirection =
          this.columnOrderDirection == "ASC" ? "DESC" : "ASC";
      } else {
        this.columnOrder = column;
        this.columnOrderDirection = "ASC";
      }
      this.searchSelfSignups();
    },
    getClass(column) {
      if (this.columnOrder == column) {
        let classOrder =
          this.columnOrderDirection == "ASC"
            ? "headerSortUp"
            : "headerSortDown";
        return classOrder;
      }
      return "";
    },
    hiddenSearchBy() {
      if (this.textToSearch.length == 0) {
        this.searchBy = "";
        this.searchSelfSignups();
      }
    },
    setSearchBy(column) {
      this.searchBy = column;
      this.textToSearch = "";
      this.$nextTick(() => {
        this.$refs["input-" + column].$el
          .getElementsByTagName("input")[0]
          .focus();
      });
    },
    searchSelfSignups() {
      let filter = Object.assign(this.globalFilter);

      if (this.columnOrder.length > 0) {
        filter.order_by = this.columnOrder;
        filter.order = this.columnOrderDirection;
      }

      if (this.searchBy.length > 0) {
        filter[this.searchBy] = this.textToSearch;
      }

      this.loadSelfSignup(filter);
    },
    loadSelfSignup(filter) {
      var vm = this;
      this.loading = true;
      vm.selfSignUps = [];
      this.pagination.totalPages = 1;
      service
        .search(filter)
        .then(response => {
          vm.selfSignUps = response.data;
          vm.pagination.totalPages = response.last_page;
          vm.pagination.total = response.total;
          vm.loading = false;
        })
        .catch(err => {
          let resp = JSON.parse(err.response.data);
          vm.$fire({
            title: "Falha ao consultar dados",
            text: resp.msg,
            type: "error"
          });
          vm.loading = false;
        });
    },
    showSelfsignup(selfSignUp) {
      this.idToShow = selfSignUp.id;
      this.$modal.show("show-selfsignup");
    }
  },
  mounted() {
    this.loadSelfSignup(this.globalFilter);
  }
};
</script>

<style lang="scss" >
table {
  border-collapse: collapse;
  td {
    border: none !important;
  }
  tr:first-child td:first-child {
    border-top-left-radius: 10px;
  }
  tr:first-child td:last-child {
    border-top-right-radius: 10px;
  }
  tr:last-child td:first-child {
    border-bottom-left-radius: 10px;
  }
  tr:last-child td:last-child {
    border-bottom-right-radius: 10px;
  }
  td,
  th {
    padding: 8px !important;
  }
  thead {
    font-size: 0.7em;
    letter-spacing: 0.35px;
    color: #3e3e3e;
    text-align: left;
    tr {
      th {
        border: none !important;
        input {
          font-size: 1.2em !important;
          padding: 4px !important;
          margin: 0px !important;
          float: left !important;
          width: 90% !important;
        }
      }
    }
  }
  tbody {
    background: #ffffff 0% 0% no-repeat padding-box;
    box-shadow: 0px 0px 4px #00000022;

    tr {
      background: white;
      border-bottom: solid 4px #ededed;
      cursor: pointer;
      &:hover {
        opacity: 0.9;
      }
    }
    .ref-tag {
      font-size: 0.8em;
    }
    .product-name {
      font-size: 0.8em;
    }

    .min-text {
      font-size: 0.625rem;
    }

    .regular-price,
    .catalog-price {
      letter-spacing: 0.25px;
      color: #3e3e3e;
      font-size: 0.8em;
      display: block;
      white-space: nowrap;
    }
    .regular-price {
      text-decoration: line-through;
      white-space: nowrap;
    }
    .price-to-pay {
      color: #ff9b64;
      letter-spacing: 0.45px;
      display: block;
      white-space: nowrap;
    }

    .amount-product {
      letter-spacing: 0.25px;
      color: #3e3e3e;
      font-size: 0.8em;
      white-space: nowrap;
    }

    .profit {
      letter-spacing: 0.25px;
      color: #278937;
      font-size: 0.8em;
      white-space: nowrap;
    }

    .trash {
      cursor: pointer;
    }
  }
}

.headerSortDown:after,
.headerSortUp:after {
  content: " ";
  position: relative;
  left: 10px;
  border: 7px solid transparent;
}
.headerSortDown:after {
  top: 10px;
  border-top-color: silver;
}
.headerSortUp:after {
  bottom: 15px;
  border-bottom-color: silver;
}
.headerSortDown,
.headerSortUp {
  padding-left: 20px;
}
</style>