<template>
  <div>
    <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"
            :data="allUsers"
            :showControl="true"
            :help="doHelp"
            @doFind="doFind"
            @doAddNew="doAddNew"
            @doEdit="doEdit"
            @doPrint="doPrint"
            @doExport="doExport"
            @doCopyItem="doCopyItem"
            @doDelete="doDelete"
            @rowClicked="rowClicked"
            :pagination="{
              total: 300,
              perPage: 200
            }"
          >
            <template slot="columns">
              <th>Họ tên</th>
              <th>Email</th>
              <th>Số điện thoại</th>
              <th>Quyền</th>
              <th class="text-right">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-right">
                <button
                  class="btn btn-primary btn-sm"
                  data-toggle="modal"
                  @click="beginEdit(row)"
                  data-target="#add-new"
                >
                  <i class="fa fa-edit"></i>
                </button>
                <button 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 -->
    <div
      class="modal"
      id="add-new"
      tabindex="-1"
      role="dialog"
      aria-hidden="true"
    >
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content  modal-lg">
          <div class="modal-header">
            <h5 class="modal-title">Thêm mới nhân viên</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-6">
                    <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-md-6">
                    <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-6">
                    <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-6" 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">
                      <Select2
                        :required="true"
                        :options="roles"
                        v-model="user.role"
                        :settings="{
                          placeholder: 'Chọn quyền'
                        }"
                      />
                      <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">
            <button
              type="button"
              class="btn btn-secondary"
              data-dismiss="modal"
              @click="doCloseSaveUser"
            >
              Đóng
            </button>
            <button
              type="submit"
              class="btn btn-primary"
              @click.prevent="doSaveUser"
              :disabled="pending"
            >
              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: false,
      user: {
        name: "",
        avatar: "",
        phone: "",
        username: "",
        email: "",
        password: "",
        role: 0,
        isNewRecord: true
      },
      userTmp: {},
      roles: [],
      ty_password: "password"
    };
  },
  mounted() {
    this.getListUser();
    this.getListRole();
  },
  methods: {
    getListUser() {
      userService
        .adminGetAllUser({})
        .then(res => {
          this.pending = false;
          this.allUsers = res.data;
        })
        .catch(err => {
          this.pending = false;
          this.$alertify.error(err.message, {
            duration: 4000
          });
        });
    },
    getListRole() {
      var self = this;
      roleService
        .getlist({})
        .then(res => {
          self.pending = false;
          self.roles = [];
          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");
            }
          })
          .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;
      }
    },
    doFind(val) {
      console.log("doFind", val);
    },
    doAddNew(val) {
      $("#add-new").modal("show");
      console.log("doAddNew", val);
    },
    doEdit(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);
    },
    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);
    }
  },
  watch: {
    keyword: function(keyword) {
      this.doSearch(keyword);
    }
  }
};
</script>
<style></style>
