<template>
<div class="container-fluid">
  <section class="content">
    <div class="header pb-2">
      <div class="header-body">
        <div class="row align-items-center py-4">
          <div class="col-lg-6 col-7">
            <nav
              aria-label="breadcrumb"
              class="d-none d-md-inline-block ml-md-4"
            >
              <ol class="breadcrumb breadcrumb-links">
                <li class="breadcrumb-item">
                  <a href="#"><i class="fas fa-home"></i></a>
                </li>
                <li class="breadcrumb-item">
                  <a href="#">Dashboards</a>
                </li>
                <li class="breadcrumb-item active" aria-current="page">
                  ຂໍ້ມູນລູກຄ້າ
                </li>
              </ol>
            </nav>
          </div>
          <div class="col-lg-6 col-5 text-right">


          </div>
        </div>
      </div>
    </div>
    <div class="row" v-if="isLoggedIn">
      <div class="col-lg-7">
        <div class="card">
          <!-- Card header -->
          <div class="card-header border-0">
            <div class="row">
              <div class="col-6">
                <h3 class="mb-0">ລາຍການລູກຄ້າ</h3>
              </div>
              <div class="col-6 text-right" v-if="$store.getters['getroles'].includes('customer_add')">
                 <router-link to="/customer/add" class="btn btn-sm btn-primary btn-round btn-icon" >
              <span class="btn-inner--icon"><i class="fas fa-plus"></i></span>
              <span class="btn-inner--text">ເພີ່ມຂໍ້ມູນລູກຄ້າ</span>
            </router-link>
              </div>
            </div>
          </div>
          <div class="px-2 pb-2">
            <div class="form-group" style="margin-bottom: 0">
                  <div class="input-group input-group-merge">
                    <input
                      class="form-control"
                      type="text"
                      placeholder="ຄົ້ນຫາຂໍ້ມູນ..."
                      v-model="search"
                      v-on:keyup="this.searchCustomer($event)"
                    />
                    <div class="input-group-append">
                      <span class="input-group-text"
                        ><i class="fas fa-search"></i
                      ></span>
                    </div>
                  </div>
                </div>
          </div>
          <!-- Light table -->
          <div class="table-responsive">
            <table class="table align-items-center table-flush">
              <thead class="thead-light">
                <tr>
                  <th width="30">ID</th>
                  <th>ຊື່ລູກຄ້າ</th>
                  <th>ສຳນັກງານ</th>
                  <th>ທີ່ຢູ່/ຕິດຕໍ່</th>
                  <th width="80" v-if="$store.getters['getroles'].includes('customer_edit') || $store.getters['getroles'].includes('customer_remove')">ຈັດການ</th>
                </tr>
              </thead>
              <tbody>
                <tr v-if="loadingC">
                  <td colspan="6" class="text-center">
                    <content-loader viewBox="-10 10 450 110" >
                            <rect x="0" y="0" rx="3" ry="3" width="350" height="5" />
                            <rect x="10" y="20" rx="3" ry="3" width="320" height="5" />
                            <rect x="0" y="40" rx="3" ry="3" width="370" height="5" />
                            <rect x="10" y="60" rx="3" ry="3" width="350" height="5" />
                            <rect x="0" y="80" rx="3" ry="3" width="300" height="5" />
                            <rect x="10" y="100" rx="3" ry="3" width="380" height="5" />
                      </content-loader>
                  </td>
                </tr>
                <tr v-for="customer in customers.data" :key="customer.id">
                  <th>{{ customer.id }}</th>
                  <td class="table-user">
                    <img v-bind:src="'images/avatars/'+customer.images"
                                        class="avatar rounded-circle mr-3"
                                     v-if="customer.images"/>
                                     <img v-bind:src="'images/add_img_bt.png'"
                                        class="avatar rounded-circle mr-3"
                                     v-if="!customer.images"/>

                    <b>{{ customer.name }} {{ customer.last_name }}</b>
                  </td>
                  <td>
                    <span class="text-muted">{{ customer.office_name }}</span>
                  </td>
                 
                  <td>
                    <span class="text-muted">{{ customer.address }}</span><br>
                    <span class="text-muted"
                      >ເບີໂທ: {{ customer.tel }} <br />
                      ອີເມວລ໌: {{ customer.email }}</span
                    >
                  </td>
                  <td class="table-actions" v-if="$store.getters['getroles'].includes('customer_edit') || $store.getters['getroles'].includes('customer_remove')">
                    <button type="button" class="btn btn-sm btn-neutral mr-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" >
                      <i class="fas fa-ellipsis-h"></i>
                    </button>
                    <div class="dropdown-menu dropdown-menu-right" style="">
                      <router-link v-if="$store.getters['getroles'].includes('customer_edit')" :to="{ name: 'editcustomer', params: { id: customer.id }, }" class="dropdown-item" > <i class="fas fa-user-edit text-info"></i >ແກ້ໄຂຂໍ້ມູນ</router-link >
                      <a class="dropdown-item" v-if="$store.getters['getroles'].includes('customer_remove')" href="javascript:void(0)" @click="deleteCustomer(customer.id)" ><i class="fas fa-trash text-red"></i>ລຶບຂໍ້ມູນ</a >
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>

            <vuePagination
              :pagination="customers"
              @paginate="getCustomers()"
              :offset="4"
            ></vuePagination>
          </div>
        </div>
      </div>

      <div class="col-lg-5">
        <div class="card">
          <!-- Card header -->
          <div class="card-header border-0">
            <div class="row">
              <div class="col-6">
                <h3 class="mb-0">ສຳນັກງານລູກຄ້າ</h3>
              </div>
              <div class="col-6 text-right" v-if="$store.getters['getroles'].includes('customer_office_add')">
                <a href="javascript:void(0)" class="btn btn-sm btn-primary btn-round btn-icon" > <span class="btn-inner--icon"><i class="fas fa-plus"></i></span> <span class="btn-inner--text" @click="addFormOF"> ເພີ່ມຂໍ້ມູນສຳນັກງານ</span > </a>
              </div>
            </div>
          </div>
          <!-- form office -->
          <div class="p-4" v-if="formoff">
            <form @submit.prevent="formOfficeSave">
              <div class="form-group">
                <div class="input-group input-group-merge">
                  <div class="input-group-prepend">
                    <span class="input-group-text"
                      ><i class="fa fa-building"></i
                    ></span>
                  </div>
                  <input
                    class="form-control"
                    placeholder="ຊື່ຫ້ອງການ"
                    type="text"
                    v-model="office.office_name"
                    v-on:keyup="checkFormOf"
                    ref="inputoff"
                  />
                </div>
              </div>
              <div class="form-group">
                <div class="input-group input-group-merge">
                  <div class="input-group-prepend">
                    <span class="input-group-text"
                      ><i class="fa fa-phone-square"></i
                    ></span>
                  </div>
                  <input
                    class="form-control"
                    placeholder="ເບີໂທ"
                    type="text"
                    v-model="office.office_tel"
                    v-on:keyup="checkFormOf"
                  />
                </div>
              </div>
              <div>
                <label class="form-control-label">ທີ່ຢູ່:</label
                ><textarea
                  class="form-control mb-4"
                  rows="3"
                  v-model="office.office_address"
                ></textarea>
              </div>
              <div class="row justify-content-end pr-4">
                <button type="submit" class="btn btn-info" :disabled="btOffice">
                  ບັນທຶກຂໍ້ມູນ
                </button>
                <button
                  type="button"
                  class="btn btn-secondary"
                  @click="cancelFormOF"
                >
                  ຍົກເລີກ
                </button>
              </div>
            </form>
          </div>

          <!-- Light table -->
          <div class="table-responsive" v-if="!formoff">
            <table class="table align-items-center table-flush">
              <thead class="thead-light">
                <tr>
                  <th>ຊື່ສຳນັກງານ</th>
                  <th>ຕິດຕໍ່</th>
                  <th v-if="$store.getters['getroles'].includes('customer_office_edit') || $store.getters['getroles'].includes('customer_office_remove')">ຈັດການ</th>
                </tr>
              </thead>
              <tbody>
                <tr v-if="loadingO">
                  <td colspan="3" class="text-center">
                    <content-loader viewBox="-10 10 450 110" >
                            <rect x="0" y="0" rx="3" ry="3" width="350" height="5" />
                            <rect x="10" y="20" rx="3" ry="3" width="320" height="5" />
                            <rect x="0" y="40" rx="3" ry="3" width="370" height="5" />
                            <rect x="10" y="60" rx="3" ry="3" width="350" height="5" />
                            <rect x="0" y="80" rx="3" ry="3" width="300" height="5" />
                            <rect x="10" y="100" rx="3" ry="3" width="380" height="5" />
                      </content-loader>
                  </td>
                </tr>
                <tr v-for="office in officeList.data" :key="office.id">
                  <td>
                    <b>{{ office.office_name }} </b>
                  </td>
                  <td>
                    <span class="text-muted">
                      ເບີໂທ: {{ office.office_tel }}
                    </span>
                  </td>
                  <td class="table-actions" v-if="$store.getters['getroles'].includes('customer_office_edit') || $store.getters['getroles'].includes('customer_office_remove')">
                    <button
                      type="button"
                      class="btn btn-sm btn-neutral mr-0"
                      data-toggle="dropdown"
                      aria-haspopup="true"
                      aria-expanded="false"
                    >
                      <i class="fas fa-ellipsis-h"></i>
                    </button>
                    <div class="dropdown-menu dropdown-menu-right" style="">
                      <a v-if="$store.getters['getroles'].includes('customer_office_edit')" href="javascript:void(0)" @click="editOffice(office.id)" class="dropdown-item" > <i class="fas fa-user-edit text-info"></i>ແກ້ໄຂຂໍ້ມູນ</a >
                      <a v-if="$store.getters['getroles'].includes('customer_office_remove')" class="dropdown-item" href="javascript:void(0)" @click="deleteoffice(office.id)" ><i class="fas fa-trash text-red"></i>ລຶບຂໍ້ມູນ</a >
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>

            <vuePagination
              :pagination="officeList"
              @paginate="getOffice()"
              :offset="4"
            ></vuePagination>

            <!-- <vuePaginationf
              :pagination="officeList"
              :url="urlOffice"
              :offset="4"
            ></vuePaginationf> -->
          </div>
        </div>
      </div>
    </div>
  </section>
</div>
</template>

<script>
export default {
  name: "order",

  components: {},
  directives: {},

  data() {
    return {
      editmode: false,
      customers: [],
      current: 1,
      pageSize: 4,
      office: {
        office_name: "",
        office_tel: "",
        office_address: "",
      },
      officeList: [],
      search: "",
      formoff: false,
      btOffice: true,
      formOfficeStatus: true,
      officeId: "",
      urlOffice: "customeroffice",
      polling: null,
      loadingC: false,
      loadingO: false,
      isLoggedIn: false,
    };
  },
  methods: {
    getCustomers(bpage) {
      this.loadingC = true;
      this.$Progress.start();
      if (typeof bpage == "undefined") {
        this.$axios.get("/sanctum/csrf-cookie").then((response) => {
          axios
            .get(`/api/customer?page=${this.customers.current_page}`)
            .then((response) => {
              this.loadingC = false;
              if (response.data.data.length < 1) {
                const bp = this.customers.current_page - 1;
                if (bp >= 1) {
                  this.getCustomers(bp);
                }
              } else {
                this.customers = response.data;
                this.$Progress.finish();
              }
            })
            .catch((error) => {
              this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
              //console.error(error);
              this.$Progress.fail();
            });
        });
      } else {
        this.loadingC = true;
        // console.log("bpage==" + bpage);
        this.$axios.get("/sanctum/csrf-cookie").then((response) => {
          axios
            .get(`/api/customer?page=${bpage}`)
            .then((response) => {
              this.customers = response.data;
              this.$Progress.finish();
              this.loadingC = false;
            })
            .catch((error) => {
              this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
          // console.error(error);
              this.$Progress.fail();
            });
        });
      }
    },
    deleteCustomer(id) {
      this.$swal
        .fire({
          title: "ທ່ານແນ່ໃຈບໍ່?",
          text: "ທີ່ຈະລຶບຂໍ້ມູນນີ້!",
          icon: "warning",
          showCancelButton: true,
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "ລຶບເລີຍ!",
          cancelButtonText: "ຍົກເລີກ",
        })
        .then((result) => {
          if (result.isConfirmed) {
            this.$Progress.start();
            this.$axios.get("/sanctum/csrf-cookie").then((response) => {
              this.$axios
                .delete(`/api/customer/delete/${id}`)
                .then((response) => {
                  this.getCustomers();
                  this.$Progress.finish();
             this.$notify({ group: "sucess", title: "ສຳເລັດ!", text: " ຂໍ້ມູນໄດ້ຖຶກລຶບອອກແລ້ວ! " }, 2000)
                 
                })
                .catch((error)=> {
                  this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
                  //console.error(error);
                  this.$Progress.fail();
                });
            });
          }
        });
    },
    searchCustomer(e) {
      if (!this.search) {
        this.doSearch();
      }
      if (e.which === 13) {
        this.doSearch();
      }
    },
    doSearch() {
      this.loadingC = true;
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
        axios
          .get(`/api/customer?page=1&s=${this.search}`)
          .then((response) => {
            this.customers = response.data;
            this.$Progress.finish();
            this.loadingC = false;
          })
          .catch((error) => {
            this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
           // console.error(error);
            this.$Progress.fail();
          });
      });
    },
    formOfficeSave() {
      if (this.formOfficeStatus) {
        this.$Progress.start();
        this.$axios.get("/sanctum/csrf-cookie").then((response) => {
          this.$axios
            .post("/api/customeroffice/add", this.office)
            .then((response) => {
              if (response.data.success) {
                this.formoff = false;
                this.getOffice();
                 this.$notify({ group: "sucess", title: "ສຳເລັດ!", text: response.data.message }, 2000)
              } else {
                this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+response.data.message }, 4000)
                this.$Progress.fail();
              }

              this.$Progress.finish();
            })
            .catch((error)=> {
              this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
              //console.error(error);
              this.$Progress.fail();
            });
        });
      } else {
        /// update

        this.$Progress.start();
        this.$axios.get("/sanctum/csrf-cookie").then((response) => {
          this.$axios
            .post(`/api/customeroffice/update/${this.officeId}`, this.office)
            .then((response) => {
              if(response.data.success){
                this.formoff = false;
              this.getOffice();
              this.getCustomers();
              this.$Progress.finish();
               this.$notify({ group: "sucess", title: "ສຳເລັດ!", text: response.data.success }, 2000)
              } else {
                this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+response.data.message }, 4000)
                this.$Progress.fail();
              }
              
            
            })
            .catch( (error)=> {
              this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
             // console.error(error);
              this.$Progress.fail();
            });
        });

        /// end update
      }
    },
    getOffice(bpage) {
      this.loadingO = true;
      this.$Progress.start();
      if (typeof bpage == "undefined") {
        this.$axios.get("/sanctum/csrf-cookie").then((response) => {
          axios
            .get(`/api/customeroffice?page=${this.officeList.current_page}`)
            .then((response) => {
              this.loadingO = false;
              if (response.data.data.length < 1) {
                const bp = this.officeList.current_page - 1;
                if (bp >= 1) {
                  this.getOffice(bp);
                }
              } else {
                this.officeList = response.data;
                this.$Progress.finish();
              }
            })
            .catch((error) => {
              this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
              //console.error(error);
              this.$Progress.fail();
            });
        });
      } else {
        this.$axios.get("/sanctum/csrf-cookie").then((response) => {
          axios
            .get(`/api/customeroffice?page=${bpage}`)
            .then((response) => {
              this.officeList = response.data;
              this.$Progress.finish();
            })
            .catch((error) => {
              this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
              //console.error(error);
              this.$Progress.fail();
            });
        });
      }
    },

    checkFormOf() {
      if (this.office.office_name != "" && this.office.office_tel != "") {
        this.btOffice = false;
      } else {
        this.btOffice = true;
      }
    },
    addFormOF() {
      this.office.office_name = "";
      this.office.office_tel = "";
      this.formoff = true;
      this.officeId = "";
      this.formOfficeStatus = true;

      this.polling = setInterval(() => {
        this.$refs.inputoff.focus();
        clearInterval(this.polling);
      }, 900);
    },
    cancelFormOF() {
      this.formoff = false;
    },
    editOffice(id) {
      let getOfficeUp = this.officeList.data.find((item) => item.id == id);
      this.officeId = getOfficeUp.id;
      this.office.office_name = getOfficeUp.office_name;
      this.office.office_tel = getOfficeUp.office_tel;
      this.office.office_address = getOfficeUp.office_address;
      this.formoff = true;
      this.formOfficeStatus = false;
      this.checkFormOf();

      this.polling = setInterval(() => {
        this.$refs.inputoff.focus();
        clearInterval(this.polling);
      }, 900);
    },
    deleteoffice(id) {
      this.$swal
        .fire({
          title: "ທ່ານແນ່ໃຈບໍ່?",
          text: "ທີ່ຈະລຶບຂໍ້ມູນນີ້!",
          icon: "warning",
          showCancelButton: true,
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "ລຶບເລີຍ!",
          cancelButtonText: "ຍົກເລີກ",
        })
        .then((result) => {
          if (result.isConfirmed) {
            this.$Progress.start();
            this.$axios.get("/sanctum/csrf-cookie").then((response) => {
              this.$axios
                .delete(`/api/customeroffice/delete/${id}`)
                .then((response) => {

                  if (response.data.success) {
                    this.getOffice();
                    this.$Progress.finish();
                    this.$notify({ group: "sucess", title: "ສຳເລັດ!", text: response.data.message }, 2000)

                  } else {
                    this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+ response.data.message }, 4000)
                    this.$Progress.fail();
                  }
                })
                .catch( (error)=> {
                  this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
                  //console.error(error);
                  this.$Progress.fail();
                });
            });
          }
        });
    },
  },
  created() {
    this.$Progress.start();
    this.getCustomers();
    this.getOffice();
    this.$Progress.finish();

    this.$axios.get(`/api/users/checkauth`).then((response) => {
      if (!response.data.isLogin) {
        window.location.href = "/";
      }
    })

    if(window.Laravel.isLoggedin){
           this.isLoggedIn = true
        }

  },
  beforeRouteEnter(to, from, next) {
    if (!window.Laravel.isLoggedin) {
      window.location.href = "/";
    }
    next();
  },
};
</script>

<style lang="scss" scoped></style>
