<template>
  <div class="soft-control vld-parent">
    <loading :active.sync="pending" :is-full-page="false"></loading>
    <div class="card">
      <div v-if="showControl" class="card-header">
        <div class="row align-items-center list-control">
          <div class="col-sm-12 col-sm-9 flex">
            <div class="row control">
              <div class="col-6 col-sm-4 col-md-2">
                <button @click="doFind" class="btn btn-info btn-block">
                  <i class="fa fa-binoculars"></i> Lọc Dữ Liệu
                </button>
              </div>
              <div class="col-6 col-sm-4 col-md-2">
                <button @click="doAddNew" class="btn btn-success btn-block">
                  <i class="fa fa-plus"></i> Thêm
                </button>
              </div>
              <div class="col-6 col-sm-4 col-md-2">
                <button
                  @click="doEdit"
                  :disabled="countChecked != 1"
                  class="btn btn-primary btn-block"
                >
                  <i class="fa fa-pencil-alt"></i> Sửa
                </button>
              </div>
              <div class="col-6 col-sm-4 col-md-2">
                <div class="dropdown d-block">
                  <button
                    class="btn btn-info dropdown-toggle btn-block"
                    type="button"
                    id="dropdownMenuButton"
                    data-toggle="dropdown"
                    aria-haspopup="true"
                    aria-expanded="false"
                  >
                    <i class="fa fa-print"></i> In
                  </button>
                  <div
                    class="dropdown-menu"
                    aria-labelledby="dropdownMenuButton"
                  >
                    <a class="dropdown-item" href="#" @click="doPrint(0)">
                      <i class="fa fa-check text-primary"></i>
                      In dòng đã chọn ({{ countChecked }})</a
                    >
                    <a class="dropdown-item" href="#" @click="doPrint(1)">
                      <i class="fa fa-check-double text-info"></i>
                      In Tất cả</a
                    >
                  </div>
                </div>
              </div>
              <div class="col-6 col-sm-4 col-md-2">
                <div class="dropdown d-block">
                  <button
                    class="btn btn-success dropdown-toggle btn-block"
                    type="button"
                    id="dropdownMenuButton"
                    data-toggle="dropdown"
                    aria-haspopup="true"
                    aria-expanded="false"
                  >
                    <i class="fa fa-file-export"></i> Xuất
                  </button>
                  <div
                    class="dropdown-menu"
                    aria-labelledby="dropdownMenuButton"
                  >
                    <a class="dropdown-item" href="#" @click="doExport(0)">
                      <i class="far fa-file-pdf text-warning"></i>
                      Xuất PDF dòng đã chọn ({{ countChecked }})</a
                    >
                    <a class="dropdown-item" href="#" @click="doExport(1)">
                      <i class="far fa-file-excel text-success"></i>
                      Xuất EXCEL dòng đã chọn ({{ countChecked }})</a
                    >
                  </div>
                </div>
              </div>
              <div class="col-6 col-sm-4 col-md-2">
                <div class="dropdown d-block">
                  <button
                    class="btn btn-primary dropdown-toggle btn-block"
                    type="button"
                    id="dropdownMenuButton"
                    data-toggle="dropdown"
                    aria-haspopup="true"
                    aria-expanded="false"
                  >
                    Tuỳ chọn
                  </button>
                  <div
                    class="dropdown-menu"
                    aria-labelledby="dropdownMenuButton"
                  >
                    <a
                      class="dropdown-item"
                      :class="{ disabled: countChecked != 1 }"
                      @click="doCopyItem"
                      href="#"
                    >
                      <i class="far fa-copy"></i>
                      Sao chép
                    </a>
                    <a class="dropdown-item" @click="doDelete" href="#">
                      <i class="far fa-trash-alt text-danger"></i>
                      Xóa dòng đã chọn ({{ countChecked }})
                    </a>
                    <a v-if="help" class="dropdown-item" @click="help" href="#">
                      <i class="fa fa-question-circle text-warning"></i>
                      Hướng dẫn
                    </a>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="col-sm-12 col-sm-3 text-right">
            <div class="row search">
              <base-input
                class="input-group-alternative mb-0 text-right"
                placeholder="Nhập nội dung để tìm..."
                addon-left-icon="fa fa-search"
                v-model="keyword"
              ></base-input>
            </div>
          </div>
        </div>
      </div>

      <div class="table-responsive">
        <table
          class="table table-soft table-striped tablesorter"
          :class="tableClass"
        >
          <thead :class="theadClasses">
            <tr>
              <th class="checkbox col-fix">
                <input
                  @change="doCheckedAll"
                  :checked="dataTable.length == countChecked"
                  class="check-input"
                  type="checkbox"
                />
              </th>
              <slot name="columns" :columns="columns">
                <th v-for="column in columns" :key="column">{{ column }}</th>
              </slot>
            </tr>
          </thead>
          <tbody :class="tbodyClasses">
            <tr
              v-for="(item, index) in dataTable"
              :key="index"
              :class="{
                '': selectedRow == index,
                'checked-row': item.checked
              }"
              @click="doClickRow(index, item, $event)"
            >
              <td class="checkbox">
                <input
                  class="check-input"
                  v-model="item.checked"
                  type="checkbox"
                  value=""
                  name="checkbox"
                />
              </td>
              <slot :row="item" :index="index"></slot>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="card-footer d-flex justify-content-end">
        <ul class="pagination justify-content-end mb-0">
          <li class="page-item" :class="{ disabled: table.currentPage == 1 }">
            <a class="page-link" href="#" @click="doFirstPage" tabindex="-1">
              <i class="fas fa-angle-double-left"></i>
              <span class="sr-only">Previous</span>
            </a>
          </li>
          <li class="page-item" :class="{ disabled: table.currentPage == 1 }">
            <a class="page-link" href="#" @click="doPreviousPage" tabindex="-1">
              <i class="fas fa-angle-left"></i>
              <span class="sr-only">Previous</span>
            </a>
          </li>
          <li class="page-item page-number">
            <span class="k-pager-input k-label">
              Trang
              <input
                type="number"
                class="k-textbox"
                v-model="table.currentPage"
              />/
              {{ table.totalPage }}
            </span>
          </li>
          <li
            class="page-item"
            :class="{ disabled: table.currentPage == table.totalPage }"
          >
            <a class="page-link" @click="doNextPage" href="#">
              <i class="fas fa-angle-right"></i>
              <span class="sr-only">Next</span>
            </a>
          </li>
          <li
            class="page-item"
            :class="{ disabled: table.currentPage == table.totalPage }"
          >
            <a class="page-link" @click="doLastPage" href="#">
              <i class="fas fa-angle-double-right"></i>
              <span class="sr-only">Next</span>
            </a>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "soft-table",
  props: {
    columns: {
      type: Array,
      default: () => [],
      description: "Table columns"
    },
    data: {
      type: Array,
      default: () => [],
      description: "Table data"
    },
    help: {
      type: Function
    },
    pagination: {
      type: Object,
      default: () => {
        return {
          total: 0,
          perPage: 100
        };
      },
      description: "Phân trang"
    },
    pending: {
      type: Boolean, // striped | hover
      default: true,
      description: "Show / Hidden Control"
    },
    showControl: {
      type: Boolean, // striped | hover
      default: true,
      description: "Show / Hidden Control"
    },
    type: {
      type: String, // striped | hover
      default: "",
      description: "Whether table is striped or hover type"
    },
    theadClasses: {
      type: String,
      default: "",
      description: "<thead> css classes"
    },
    tbodyClasses: {
      type: String,
      default: "",
      description: "<tbody> css classes"
    }
  },
  data() {
    return {
      selectedRow: -1,
      countChecked: 0,
      keyword: "",
      dataTable: [],
      delayTimer: null,
      table: {
        currentPage: 1,
        totalPage: Math.ceil(this.pagination.total / this.pagination.perPage)
      }
    };
  },
  computed: {
    tableClass() {
      return this.type && `table-${this.type}`;
    }
  },
  methods: {
    addCheckBox(item) {
      if (!item.checked) item.checked = false;
    },
    doClickRow(index, item, $event) {
      if ($event.target.name == "checkbox") {
        if (item.checked) {
          item.checked = false;
          this.countChecked -= 1;
          this.selectedRow = -1;
        } else {
          item.checked = true;
          this.countChecked += 1;
          this.selectedRow = index;
        }
      } else {
        if ($event.ctrlKey) {
          if (item.checked) {
            item.checked = false;
            this.countChecked -= 1;
            this.selectedRow = -1;
          } else {
            item.checked = true;
            this.countChecked += 1;
            this.selectedRow = index;
          }
        } else if ($event.shiftKey) {
          if (this.selectedRow == -1) {
            this.dataTable.forEach(element => {
              if (element.checked) element.checked = false;
            });
            item.checked = true;
            this.countChecked = 1;
            this.selectedRow = index;
          } else {
            let begin = this.selectedRow > index ? index : this.selectedRow;
            let end = this.selectedRow > index ? this.selectedRow : index;
            this.countChecked += end - begin;
            for (let idex = begin; idex <= end; idex++) {
              const element = this.dataTable[idex];
              element.checked = true;
            }
            this.selectedRow = index;
          }
        } else {
          this.dataTable.forEach(element => {
            if (element.checked) element.checked = false;
          });
          item.checked = true;
          this.countChecked = 1;
          this.selectedRow = index;
        }
        this.$emit("rowClicked", item);
      }
    },
    doCheckedAll(e) {
      var dataTmp = this.dataTable;
      if (e.target.checked) {
        this.countChecked = dataTmp.length;
        dataTmp.forEach(element => {
          element.checked = true;
        });
      } else {
        this.countChecked = 0;
        dataTmp.forEach(element => {
          if (element.checked) element.checked = false;
        });
      }
      this.dataTable = [];
      this.dataTable = dataTmp;
      this.selectedRow = -1;
    },
    doChangePage() {
      console.log("doChange page", this.table.currentPage);
      this.$emit("doChangePage", this.table.currentPage);
    },
    doLastPage() {
      this.table.currentPage = this.table.totalPage;
    },
    doNextPage() {
      this.table.currentPage = Number(this.table.currentPage) + 1;
    },
    doPreviousPage() {
      this.table.currentPage = Number(this.table.currentPage) - 1;
    },
    doFirstPage() {
      this.table.currentPage = 1;
    },
    removeElementsNotIn(a, b) {
      return a.filter(function(item) {
        return b.indexOf(item) < 0; // Returns true for items not found in b.
      });
    },
    doSearch(keyword) {
      let self = this;
      clearTimeout(this.delayTimer);
      this.delayTimer = setTimeout(function() {
        self.$emit("doSearch", keyword);
      }, 350);

      // this.delayTimer = setTimeout(function() {
      //   if (keyword == "") {
      //     self.dataTable = self.data;
      //     return;
      //   } else {
      //     self.dataTable = self.data.filter(user => {
      //       let keys = Object.keys(user);
      //       let keysCheck = self.removeElementsNotIn(keys, [
      //         "password",
      //         "id",
      //         "createdAt",
      //         "updatedAt",
      //         "active"
      //       ]);
      //       for (let i = 0; i < keysCheck.length; i++) {
      //         const key = keysCheck[i];
      //         let value = user[key];
      //         if (
      //           value &&
      //           value
      //             .toString()
      //             .toLowerCase()
      //             .includes(keyword.toLowerCase())
      //         ) {
      //           return true;
      //         }
      //       }
      //       return false;
      //     });
      //   }
      // }, 350);
    },
    doEdit() {
      if (this.selectedRow >= 0) {
        this.$emit("doEdit", this.dataTable[this.selectedRow]);
      }
    },
    doPrint(type) {
      if (type == 0) {
        if (this.countChecked == 0) {
          this.$swal({
            title: "Chưa chọn dòng nào",
            text: "Vui lòng chọn ít nhất 1 dòng để thực hiện thao tác này !",
            type: "warning",
            confirmButtonText: "OK, Tôi hiểu rồi !"
          });
        } else {
          let dataSelected = [];
          this.dataTable.forEach(element => {
            if (element.checked) dataSelected.push(element.id);
          });
          this.$emit("doPrint", dataSelected);
        }
      } else {
        let dataSelected = [];
        this.dataTable.forEach(element => {
          dataSelected.push(element.id);
        });
        this.$emit("doPrint", dataSelected);
      }
    },
    doExport(type) {
      if (this.countChecked == 0) {
        this.$swal({
          title: "Chưa chọn dòng nào",
          text: "Vui lòng chọn ít nhất 1 dòng để thực hiện thao tác này !",
          type: "warning",
          confirmButtonText: "OK, Tôi hiểu rồi !"
        });
      } else {
        let dataSelected = [];
        this.dataTable.forEach(element => {
          if (element.checked) dataSelected.push(element.id);
        });
        if (type == 0) this.$emit("doExport", "PDF", dataSelected);
        else this.$emit("doExport", "EXCEL", dataSelected);
      }
    },
    doCopyItem() {
      if (this.countChecked == 0) {
        this.$swal({
          title: "Chưa chọn dòng nào",
          text: "Vui lòng chọn 1 dòng để thực hiện thao tác này !",
          type: "warning",
          confirmButtonText: "OK, Tôi hiểu rồi !"
        });
      } else {
        if (this.selectedRow >= 0) {
          this.$emit("doCopyItem", this.dataTable[this.selectedRow]);
        }
      }
    },
    doDelete() {
      var self = this;
      if (this.countChecked == 0) {
        this.$swal({
          title: "Chưa chọn dòng nào",
          text: "Vui lòng chọn 1 dòng để thực hiện thao tác này !",
          type: "warning",
          confirmButtonText: "OK, Tôi hiểu rồi !"
        });
      } else {
        this.$swal({
          title: "Bạn có chắc thực hiện thao tác này?",
          text: "Bạn sẽ không thể hoàn nguyên điều này!!",
          type: "warning",
          showCancelButton: true,
          confirmButtonText: "OK",
          cancelButtonText: "Không",
          reverseButtons: true
        }).then(function(result) {
          if (result.value) {
            let dataSelected = [];
            self.dataTable.forEach(element => {
              if (element.checked) dataSelected.push(element.id);
            });
            self.$emit("doDelete", dataSelected);
          }
        });
      }
    },
    doFind() {
      this.$emit("doFind");
    },
    doAddNew() {
      this.$emit("doAddNew");
    }
  },
  watch: {
    "table.currentPage": function(newValue, oldValue) {
      if (newValue > this.table.totalPage || newValue < 1) {
        this.table.currentPage = oldValue;
      } else {
        if (this.table.totalPage >= oldValue && oldValue != 0) {
          this.doChangePage();
        }
      }
    },
    data: function() {
      this.dataTable = this.data;
    },
    keyword: function(keyword) {
      this.doSearch(keyword);
    }
  }
};
</script>
