<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-12">

        <div class="card">
          <!-- Card header -->
          <div class="card-header border-0">
            <div class="row">
              <div class="col-md-6">
                <h3 class="mb-0">ໃບສະເໜີລາຄາ</h3>
              </div>
              <div class="col-md-6 text-right">
                   <router-link v-if="$store.getters['getroles'].includes('quo_add')" to="/bills/add_quotation" class="btn btn-sm btn-info 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="card-body">

         
          <div class=" pb-2 row">
            <div class="col-md-6"></div>
            <div class="col-md-6"><div class="form-group" style="margin-bottom: 0">
                  <div class="input-group input-group-merge">
                    <input
                      class="form-control"
                      type="text"
                      placeholder="ຄົ້ນຫາຂໍ້ມູນ..."
                      v-model="searchQuo"
                      v-on:keyup="this.searchQuoUP($event)"
                    />
                    <div class="input-group-append">
                      <span class="input-group-text"
                        ><i class="fas fa-search"></i
                      ></span>
                    </div>
                  </div>
                </div></div>
            
          </div>
          <!-- Light table -->
          <div class="table-responsive border">
            <table class="table align-items-center table-flush">
              <thead class="thead-light">
                <tr>
                 <!-- <th width="30">ID</th> -->
                  <th class="text-center" width="80">ເລກທີ່</th>
                  <th class="text-left table-user-info" >ຂໍ້ມູນລູກຄ້າ</th>
                  <th class="text-right">ຈຳນວນເງິນ</th>
                  <th class="text-center">ສະຖານະ</th>
                  <th width="80" class="text-right">ຈັດການ</th>
                </tr>
              </thead>
              <tbody>
                <tr v-if="loadingQ">
                    <td colspan="5" 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="quo in quotation.data" :key="quo.id">
                 <!--  <td>
                   <b>{{ quo.id }} </b>
                  </td>-->
                  <td class="text-center">
                    <span class="text-muted">
                      <b> {{ quo.quonum_id }} </b>
                    </span>
                  </td>
                  <td class="text-left tabble-user">
                    <span  v-if="quo.customer_id =='0' && quo.office_id =='0' && quo.customer_name ==null" >
                      <b>ລູກຄ້າທົ່ວໄປ ເຂົ້າມາໜ້າຮ້ານ</b>
                    </span>
                    <span v-else>
                    <b>{{quo.customer_name}}</b>
                    
                    <br>
                      <small><i class="ni ni-pin-3"></i>: {{quo.customer_address}}</small><br> 
                      <span v-if="quo.customer_type=='true'"><small><i class="ni ni-mobile-button"></i>: 020 {{quo.customer_tel}}</small></span>
                      <span v-if="quo.customer_type=='false'"><small><i class="ni ni-mobile-button"></i>: {{quo.customer_tel}}</small></span>
                      </span>
                      <br><small> ວັນທີ່: {{date(quo.created_at)}}</small>
                  </td>
                  <td class="text-right">
                    <span class="text-muted">
                       {{ formatPrice(quo.all_credit) }}
                    </span>
                  </td>
                  <td class="text-center">


                        <span class="badge badge-dot mr-4" v-if="quo.status == 'pending'">
                          <i class="bg-warning"></i>
                          <span class="status">ລໍດຳເນີນການ</span>
                        </span>

                        <span class="badge badge-dot mr-4" v-if="quo.status == 'payed'">
                          <i class="bg-success"></i>
                          <span class="status">ສຳເລັດ</span>
                        </span>


                  </td>
                  <td class="table-actions">
                    <div class="col-auto">
                    <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 href="javascript:void(0)" @click="PrintQ($event, quo.quonum_id)" class="dropdown-item" > <i class="fas fa-print"></i> ພິມບິນ</a >
                      <router-link v-if="$store.getters['getroles'].includes('quo_edit')" :to="{ name: 'editquotation', params: { id: quo.quonum_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('quo_remove')" href="javascript:void(0)" @click="deleteQuotation($event,quo.quonum_id)" ><i class="fas fa-trash text-red"></i>ລຶບຂໍ້ມູນ</a >
                    </div></div>
                  </td>
                </tr>
              </tbody>
            </table>

            <vuePagination
              :pagination="quotation"
              @paginate="getQuotation()"
              :offset="4"
            ></vuePagination>
          </div>
           </div>
        </div>
      </div>
    </div>

  </section>
</div>
</template>

<script>
import moment from 'moment';
export default {
  name: "Bills",

  components: {},

  directives: {},

  data() {
    return {
      bills: [],
      quotation: [],
      searchBill: "",
      searchQuo:"",
      loadingB:false,
      loadingQ:false,
      isLoggedIn: false,
    };
  },

  mounted() {},

  methods: {
    date(value) {
      return moment(value).format("DD/MM/YYYY");
    },
     Print(e,id){
      window.open(window.location.origin+'/api/printbill/'+id, "_blank");
    },
    PrintQ(e,id){
      window.open(window.location.origin+'/api/printquotation/'+id, "_blank");
    },
    formatPrice(value) {
        let val = (value/1).toFixed(0).replace('.', ',')
        return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    },
    getBills(bpage){
      this.loadingB = true
      this.$Progress.start();
          if (typeof bpage == "undefined") {
            this.$axios.get("/sanctum/csrf-cookie").then((response) => {
              axios
                .get(`/api/bills?page=${this.bills.current_page}`)
                .then((response) => {
                  if(response.data.message){
                    this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+response.data.message }, 4000)
                   this.$Progress.fail();
                  } else {
                    this.loadingB = false
                    if (response.data.data.length < 1) {
                      const bp = this.bills.current_page - 1;
                      if (bp >= 1) {
                        this.getBills(bp);
                      } else {
                        this.bills = response.data;
                      }
                    } else {

                      this.bills = 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/bills?page=${bpage}`)
                .then((response) => {
                  if(response.data.message){
                    this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+response.data.message }, 4000)
                     this.$Progress.fail();
                  } else {
                  this.bills = response.data;
                  this.$Progress.finish();
                  }
                })
                .catch((error) => {
                   this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
                  //console.error(error);
                  this.$Progress.fail();
                });
            });
          }
    },
    getQuotation(bpage){
      this.loadingQ = true
      this.$Progress.start();
          if (typeof bpage == "undefined") {
            this.$axios.get("/sanctum/csrf-cookie").then((response) => {
              axios
                .get(`/api/quotation?page=${this.quotation.current_page}`)
                .then((response) => {
                    this.loadingQ = false
                  if (response.data.data.length < 1) {

                    const bp = this.quotation.current_page - 1;
                    if (bp >= 1) {
                      this.getQuotation(bp);
                    } else {
                       this.quotation = response.data
                    }
                  } else {

                    this.quotation = 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/getQuotation?page=${bpage}`)
                .then((response) => {
                  this.quotation = response.data
                  this.$Progress.finish();
                })
                .catch((error) => {
                   this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
                  //console.error(error);
                  this.$Progress.fail();
                });
            });
          }
    },
  searchBillUp(e){
           if(!this.searchBill){
                this.doSearch()
           }
         if (e.which === 13) {
            this.doSearch()
            }

        },
    doSearch(){
      this.loadingB = true
            this.$axios.get("/sanctum/csrf-cookie").then((response) => {
                axios.get(`/api/bills?page=1&s=${this.searchBill}`)
                    .then((response) => {
                            this.bills = response.data;
                            this.$Progress.finish()
                            this.loadingB = false
                    })
                    .catch(() => {
                        console.error(error)
                        this.$Progress.fail()
                    })
                })
        },
      searchQuoUP(e){
           if(!this.searchQuo){
                this.doSearchQ()
           }
         if (e.which === 13) {
            this.doSearchQ()
            }

        },
    doSearchQ(){
      this.loadingQ = true
            this.$axios.get("/sanctum/csrf-cookie").then((response) => {
                axios.get(`/api/quotation?page=1&s=${this.searchQuo}`)
                    .then((response) => {
                            this.quotation = response.data;
                            this.$Progress.finish()
                            this.loadingQ = false
                    })
                    .catch((error) => {
                       this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
                       // console.error(error)
                        this.$Progress.fail()
                    })
                })
        },
      deleteBill(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/bills/delete/${id}`)
                        .then(response => {
                             this.getBills()
                            if (response.data.success) {
                              this.$Progress.finish()
                              this.$notify({ group: "sucess", title: "ສຳເລັດ!", text: " ຂໍ້ມູນໄດ້ຖຶກລຶບອອກແລ້ວ! " }, 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()
                        });
                })
            }
            })
        },
        deleteQuotation(e,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/quotation/delete/${id}`)
                        .then(response => {
                             this.getQuotation()
                            if (response.data.success) {
                              this.$Progress.finish()
                              this.$notify({ group: "sucess", title: "ສຳເລັດ!", text: " ຂໍ້ມູນໄດ້ຖຶກລຶບອອກແລ້ວ! " }, 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.$axios.get(`/api/users/checkauth`).then((response) => {
      if (!response.data.isLogin) {
        window.location.href = "/";
      }
    })

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

    this.getBills()
    this.getQuotation()

    // set display
    this.$store.dispatch({
          type:"setCustomerBill",
          listbill: [],
          customer: [{'customerSelect':'0','listCustomer':this.ListCustomer,'CustomerSe':this.CustomerSe,'staff':window.Laravel.user.sex+' '+window.Laravel.user.name+' '+window.Laravel.user.last_name}],
          option: [{'discount':'0','tax':'0','alltatal':'0'}]
        })
  },
  beforeRouteEnter(to, from, next) {
        if (!window.Laravel.isLoggedin) {
            window.location.href = "/";
        }
        next();
    }
};
</script>

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