<template>
  <div id="user">
    <base-header class="bg-primary pb-6 pt-0">
      <div class="row align-items-center py-2">
        <div class="col-lg-6 col-7">
          <breadcrumb
            :link="[{ name: 'Quản lý nhân viên', active: true }]"
          ></breadcrumb>
        </div>
      </div>
    </base-header>
    <div class="container-fluid mt--6 bg-secondary">
      <div class="row">
        <div class="col">
          <soft-table
            class="table align-items-center table-flush"
            tbody-classes="list"
            :pending="pending"
            :data="allUsers"
            :showControl="true"
            :help="doHelp"
            @doFind="doFind"
            @doAddNew="doAddNew"
            @doEdit="doEdit"
            @doPrint="doPrint"
            @doExport="doExport"
            @doCopyItem="doCopyItem"
            @doDelete="doDelete"
            @rowClicked="rowClicked"
            @doChangePage="doChangePage"
            @doSearch="doSearch"
            :pagination="{
              total: 300,
              perPage: 200
            }"
          >
            <template slot="columns">
              <th>Họ tên</th>
              <th class="col-fix">Email</th>
              <th class="col-fix">Số điện thoại</th>
              <th class="col-fix">Quyền</th>
              <th class="col-fix">Trạng thái</th>
              <th class="text-center col-fix">Hành động</th>
            </template>

            <template slot-scope="{ row }">
              <td scope="row">
                <div class="media align-items-center">
                  <a
                    href="#"
                    class="avatar rounded-circle  mr-3"
                    data-toggle="tooltip"
                    data-original-title="Romina Hadid"
                  >
                    <img alt="" :src="row.avatar" />
                  </a>
                  <div class="media-body">
                    <span class="name mb-0 text-sm">{{ row.name }}</span>
                  </div>
                </div>
              </td>
              <td>
                {{ row.email }}
              </td>
              <td>
                {{ row.phone }}
              </td>
              <td>
                <badge
                  class="badge-dot mr-4"
                  :type="row.role == 1 ? 'warning' : ''"
                >
                  <i :class="{ 'bg-warning': row.role == 1 }"></i>
                  <span class="status">{{ row.role_name }}</span>
                </badge>
              </td>
              <td class="text-center">
                <button
                  v-if="row.active"
                  @click="doEnable(row)"
                  class="btn btn-sm btn-success"
                >
                  Đang hoạt động
                </button>
                <button
                  v-else
                  @click="doEnable(row)"
                  class="btn btn-danger btn-sm"
                >
                  Chưa kích hoạt
                </button>
              </td>
              <td class="text-center">
                <button
                  title="Làm mới mật khẩu"
                  class="btn btn-warning btn-sm"
                  @click="doResetPassword(row)"
                >
                  <i class="fas fa-sync-alt"></i>
                </button>
                <button
                  title="Chỉnh sửa nhân viên"
                  class="btn btn-primary btn-sm"
                  data-toggle="modal"
                  @click="beginEdit(row)"
                  data-target="#add-new"
                >
                  <i class="fa fa-edit"></i>
                </button>
                <button
                  title="Xóa nhân viên"
                  class="btn btn-danger btn-sm"
                  @click="doDelete(row)"
                >
                  <i class="fa fa-trash-alt"></i>
                </button>
              </td>
            </template>
          </soft-table>
        </div>
      </div>
    </div>
    <!-- Modal Find User-->
    <div
      class="modal fade"
      id="modalFindUser"
      tabindex="-1"
      role="dialog"
      aria-labelledby="modelTitleId"
      aria-hidden="true"
    >
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header mt-xl-3 mb-xl-3">
            <h5 class="modal-title ml-xl-2">Lọc Dữ Liệu</h5>
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <ValidationObserver ref="formSaveUser">
              <form role="form" @submit.prevent="doSaveUser">
                <!-- Input groups with icon -->
                <div class="row">
                  <div class="col-md-12">
                    <ValidationProvider
                      name="họ tên"
                      rules="required"
                      v-model="user.username"
                      v-slot="{ errors }"
                    >
                      <base-input
                        class="input-group input-group-merge mb-3"
                        placeholder="Họ tên"
                        v-model="user.name"
                        :error="errors[0]"
                        :valid="errors.length == 0 && user.name.length > 0"
                      ></base-input>
                    </ValidationProvider>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-12">
                    <base-input
                      class="input-group input-group-merge mb-3"
                      placeholder="Số điện thoại"
                      v-model="user.phoneNumber"
                    ></base-input>
                  </div>
                  <div class="col-md-12">
                    <base-input
                      class="input-group input-group-merge mb-3"
                      placeholder="Email"
                      v-model="user.email"
                    >
                    </base-input>
                  </div>
                  <div class="col-md-12">
                    <Select2
                      :required="true"
                      v-model="user.role"
                      :settings="{
                        ajax: {
                          transport: function(params, success, failure) {
                            getListRole(params, success, failure);
                          }
                        },
                        placeholder: 'Chọn quyền',
                        templateResult: formatSelect2,
                        templateSelection: formatSelectionSelecte2
                      }"
                    />
                    <div
                      v-if="user.role == ''"
                      class="text-danger invalid-feedback mt-2"
                      style="display: block; padding: 0px 5px 10px 10px; font-style: italic; opacity: 0.7;"
                    >
                      Vui lòng chọn quyền cho nhân viên
                    </div>
                  </div>
                </div>
              </form>
            </ValidationObserver>
          </div>
          <div class="modal-footer mb-xl-2">
            <button
              type="button"
              class="btn btn-secondary"
              data-dismiss="modal"
            >
              Đóng
            </button>
            <button type="button" class="btn btn-primary">Lọc Dữ Liệu</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Modal Add New User-->
    <div
      class="modal fade"
      id="modalSaveUser"
      tabindex="-1"
      role="dialog"
      aria-labelledby="modelTitleId"
      aria-hidden="true"
    >
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header  mt-xl-3 mb-xl-3">
            <h5 class="modal-title ml-xl-2">
              <span v-if="user.id && user.id != ''">
                Cập nhật thông tin cho : <strong>{{ user.name }}</strong>
              </span>
              <span v-else>Thêm mới nhân viên</span>
            </h5>
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <ValidationObserver ref="formSaveUser">
              <form role="form" @submit.prevent="doSaveUser">
                <!-- Input groups with icon -->
                <div class="row">
                  <div class="col-xl-12">
                    <ValidationProvider
                      name="họ tên"
                      rules="required"
                      v-slot="{ errors }"
                    >
                      <base-input
                        class="input-group input-group-merge mb-3"
                        placeholder="Tên hiển thị"
                        addon-left-icon="fas fa-user"
                        v-model="user.name"
                        :error="errors[0]"
                        :valid="errors.length == 0 && user.name.length > 0"
                      ></base-input>
                    </ValidationProvider>
                  </div>
                  <div class="col-xl-12">
                    <ValidationProvider
                      name="Email"
                      vid="email"
                      :rules="{ required: true, email: true }"
                      v-slot="{ errors }"
                    >
                      <base-input
                        class="input-group input-group-merge mb-3"
                        placeholder="Email"
                        addon-left-icon="fas fa-envelope"
                        v-model="user.email"
                        :error="errors[0]"
                        :valid="errors.length == 0 && user.email.length > 0"
                      ></base-input>
                    </ValidationProvider>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-12">
                    <ValidationProvider
                      name="tên đăng nhập"
                      vid="username"
                      rules="required|onlyletter"
                      v-slot="{ errors }"
                    >
                      <base-input
                        class="input-group input-group-merge mb-3"
                        placeholder="Tên đăng nhập (viết liền không dấu)"
                        addon-left-icon="fas fa-user"
                        v-model="user.username"
                        :error="errors[0]"
                        :valid="errors.length == 0 && user.username.length > 0"
                      ></base-input>
                    </ValidationProvider>
                  </div>
                  <div class="col-md-12" v-if="user.isNewRecord">
                    <ValidationProvider
                      name="mật khẩu"
                      rules="required|onlyletter"
                      v-slot="{ errors }"
                    >
                      <base-input
                        class="input-group input-group-merge mb-3"
                        placeholder="Mật khẩu"
                        v-model="user.password"
                        :type="ty_password"
                        :error="errors[0]"
                        :valid="errors.length == 0 && user.password.length > 0"
                      >
                        <template slot="addonLeft" style="cursor: pointer;">
                          <i
                            @mousedown="ty_password = 'text'"
                            @mouseup="ty_password = 'password'"
                            class="fas fa-eye"
                          ></i>
                        </template>
                      </base-input>
                    </ValidationProvider>
                  </div>
                </div>
                <!-- Input groups with icon -->
                <div class="row">
                  <div class="col-md-6">
                    <base-input
                      class="input-group input-group-merge mb-3 text-right"
                      placeholder="Số điện thoại"
                      addon-left-icon="fas fa-phone"
                      v-model="user.phone"
                    ></base-input>
                  </div>
                  <div class="col-md-6">
                    <ValidationProvider name="mật khẩu" rules="required">
                      <!-- :options="roles" -->
                      <Select2
                        :required="true"
                        v-model="user.role"
                        :settings="{
                          ajax: {
                            transport: function(params, success, failure) {
                              getListRole(params, success, failure);
                            }
                          },
                          placeholder: 'Chọn quyền',
                          templateResult: formatSelect2,
                          templateSelection: formatSelectionSelecte2
                        }"
                      />
                      <div
                        v-if="user.role == ''"
                        class="text-danger invalid-feedback mt-2"
                        style="display: block; padding: 0px 5px 10px 10px; font-style: italic; opacity: 0.7;"
                      >
                        Vui lòng chọn quyền cho nhân viên
                      </div>
                    </ValidationProvider>
                  </div>
                </div>
              </form>
            </ValidationObserver>
          </div>
          <div class="modal-footer mb-xl-2">
            <button
              type="button"
              @click="doCloseSaveUser"
              class="btn btn-secondary"
              data-dismiss="modal"
            >
              Đóng
            </button>
            <button
              type="button"
              @click.prevent="doSaveUser"
              class="btn btn-primary"
            >
              Lưu lại
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import $ from "jquery";
import { userService, roleService } from "@/_services";
export default {
  name: "tables",
  components: {},
  data() {
    return {
      allUsers: [],
      keyword: "",
      pending: true,
      user: {
        name: "",
        avatar: "",
        phone: "",
        username: "",
        email: "",
        password: "",
        role: 0,
        isNewRecord: true
      },
      userTmp: {},
      roles: [],
      ty_password: "password"
    };
  },
  mounted() {
    this.getListUser();
  },
  methods: {
    formatSelect2(item) {
      if (item.loading) {
        return "Vui lòng đợi chúng tôi lấy lại dữ liệu ...";
      }
      var $container = $(`<div class='clearfix' style="padding:4px 3px;">
                        <div class='select2-result-repository__avatar' style="float: left;width: 30px;margin-right: 10px;">
                           <img style="width: 100%;height: auto;" src='https://cdn.onlinewebfonts.com/svg/img_315540.png' />
                        </div>
                        <div style="margin-left: 40px;" class='select2-result-repository__meta'>
                          <strong>${item.name}</strong> <br>
                          <span>${item.description}</span>
                        </div>
                    </div>
      `);
      return $container;
    },
    formatSelectionSelecte2(item) {
      return item.name || item.text;
    },
    getListUser() {
      userService
        .adminGetAllUser({})
        .then(res => {
          this.pending = false;
          this.allUsers = res.data;
        })
        .catch(err => {
          this.pending = false;
          this.$alertify.error(err.message, {
            duration: 4000
          });
        });
    },
    doChangePage(currentPage) {
      userService
        .adminGetAllUser({ page: currentPage })
        .then(res => {
          this.pending = false;
          this.allUsers = res.data;
        })
        .catch(error => {
          console.log("error", error);
          this.$alertify.error(error.message, {
            duration: 4000
          });
        });
    },
    getListRole(params, success) {
      roleService
        .getlist({})
        .then(res => {
          var results = res.data;
          if (params.data.q) {
            results = res.data.filter(item => {
              return (
                item.name.toLowerCase().includes(params.data.q.toLowerCase()) ||
                item.description
                  .toLowerCase()
                  .includes(params.data.q.toLowerCase())
              );
            });
          }

          success({
            results: results,
            pagination: {
              more: params.page * 30 < res.data.length
            }
          });
          // res.data.forEach(element => {
          //   self.roles.push({
          //     id: element.id,
          //     text: element.name + " - " + element.description
          //   });
          // });
          console.log(res);
        })
        .catch(err => {
          this.pending = false;
          this.$alertify.error(err.message, {
            duration: 4000
          });
        });
    },
    doSaveUser() {
      var self = this;
      this.$refs.formSaveUser.validate().then(success => {
        if (!success || self.user.role == "") return;
        userService
          .register(self.user)
          .then(res => {
            if (self.user.isNewRecord) {
              self.$alertify.success(res.message, {
                duration: 4000
              });
              self.allUsers.unshift(res.data);
              self.user.name = "";
              self.user.email = "";
              self.user.username = "";
              self.user.password = "";
              self.user.phone = "";
              self.user.rol = "";
              self.user.isNewRecord = true;
              $("#add-new").modal("toggle");
            } else {
              self.$alertify.success(res.message, {
                duration: 4000
              });
              $("#add-new").modal("toggle");
            }
            $("#modalSaveUser").modal("hide");
          })
          .catch(err => {
            if (err.data.param == "email") {
              self.$refs.formSaveUser.setErrors({
                email: [err.message]
              });
            }
            if (err.data.param == "username") {
              self.$refs.formSaveUser.setErrors({
                username: [err.message]
              });
            }
            self.$alertify.error(err.message, {
              duration: 4000
            });
          });
      });
    },
    beginEdit(row) {
      this.user = row;
      this.userTmp = Object.assign({}, row);
      this.user.isNewRecord = false;
    },
    doCloseSaveUser() {
      if (!this.user.isNewRecord) {
        var index = this.allUsers.findIndex(x => x.id == this.user.id);
        this.allUsers[index] = this.userTmp;
        this.user = this.userTmp;
      }
    },
    doSearch(keyword) {
      userService
        .adminGetAllUser({ filter: keyword })
        .then(res => {
          this.pending = false;
          this.allUsers = res.data;
        })
        .catch(error => {
          console.log("error", error);
          this.$alertify.error(error.message, {
            duration: 4000
          });
        });
    },
    doFind() {
      $("#modalFindUser").modal("show");
    },
    doEnable(item) {
      var self = this;
      let text = item.active
        ? "<span class='badge badge-danger'>vô hiệu hoá</span>"
        : "<span class='badge badge-success'>kích hoạt</span>";

      var editItem = Object.assign({}, item);
      editItem.active = item.active ? "0" : "1";
      editItem.isNewRecord = false;
      this.$swal({
        title: "Bạn có chắc thực hiện thao tác này?",
        html: `<span style="font-size:18px">Bạn đang ${text} tài khoản : <b>${item.name}</b></span>`,
        showCancelButton: true,
        confirmButtonText: "OK",
        cancelButtonText: "Không",
        reverseButtons: true
      }).then(function(result) {
        if (result.value) {
          userService
            .register(editItem)
            .then(res => {
              item.active = editItem.active;
              self.$alertify.success(res.message, {
                duration: 4000
              });
            })
            .catch(err => {
              self.$alertify.error(err.message, {
                duration: 4000
              });
            });
        }
      });
    },
    doAddNew() {
      $("#modalSaveUser").modal("show");
      this.user.name = "";
      this.user.id = undefined;
      this.user.email = "";
      this.user.username = "";
      this.user.password = "";
      this.user.phone = "";
      this.user.role = "";
      this.user.isNewRecord = true;
    },
    doEdit(val) {
      $("#modalSaveUser").modal("show");
      this.user = val;
      this.userTmp = Object.assign({}, val);
      console.log("doEdit", val);
    },
    doPrint(val) {
      console.log("doPrint", val);
    },
    doExport(type, val) {
      console.log("doExport", type, val);
    },
    doCopyItem(val) {
      console.log("doCopyItem", val);
      if (val.name !== undefined) {
        this.user.username = val.username;
        this.user.name = val.name;
        this.user.email = val.email;
        console.log("copy : ", this.user);
        $("#modalSaveUser").modal("show");
      }
    },
    doDelete(val) {
      console.log("doDelete", val);
      // userService
      //       .deleteUser({ id: row.id })
      //       .then(res => {
      //         var index = self.tableUser.data.findIndex(x => x.id == row.id);
      //         var index2 = self.allUsersTmp.findIndex(x => x.id == row.id);
      //         self.tableUser.data.splice(index, 1);
      //         self.allUsersTmp.splice(index2, 1);
      //         const maxpage = Math.ceil(
      //           self.tableUser.data.length / self.tableUser.perPage
      //         );
      //         if (self.tableUser.current > maxpage) {
      //           self.tableUser.current = maxpage;
      //         }
      //         console.log(res);
      //       })
      //       .catch(err => {
      //         self.$alertify.error(err.message, {
      //           duration: 4000
      //         });
      //         console.log(err);
      //       });
    },
    doHelp() {
      console.log("doHelp");
    },
    rowClicked(val) {
      console.log("rowClicked", val);
    },
    doResetPassword(val) {
      console.log(val);
      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) {
          // userService
          //   .resetPasswordUser(val.id)
          //   .then(res => {
          //     this.$alertify.success(res.message, {
          //       duration: 4000
          //     });
          //     console.log(res);
          //   })
          //   .catch(err => {
          //     self.$alertify.error(err.message, {
          //       duration: 4000
          //     });
          //     console.log(err);
          //   });
        }
      });
    }
  }
};
</script>
<style lang="scss">
#user {
  .modal-body {
    padding: 10px;
  }
  .modal-header {
    padding: 15px 10px 0px;
  }
  .modal-footer {
    padding: 0px 10px 15px;
  }
}
</style>
