<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-6">
                <h3 class="mb-0">ໃບບິນ </h3>
              </div>
              <div class="col-6 text-right" v-if="$store.getters['getroles'].includes('bill_add')">
                <router-link to="/bills/add" 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>
          <!-- Light table -->
          <div class="card-body">
          <div class=" row pb-2">
            <div class="col-md-6 pb-2"> 
              <div class="custom-control custom-radio custom-control-inline">
                  <input type="radio" id="filterall" name="filterbill" class="custom-control-input" value="all" v-model="FilterBill" @click="setAll()">
                  <label class="custom-control-label" for="filterall">ທັງໝົດ</label>
                </div>
                <div class="custom-control custom-radio custom-control-inline">
                  <input type="radio" id="filterpay" name="filterbill" class="custom-control-input" value="pay" v-model="FilterBill" @click="setPay()">
                  <label class="custom-control-label" for="filterpay">ສຳເລັດ</label>
                </div>
                <div class="custom-control custom-radio custom-control-inline">
                  <input type="radio" id="filteruppay" name="filterbill" class="custom-control-input" value="unpay" v-model="FilterBill" @click="setUnPay()">
                  <label class="custom-control-label" for="filteruppay">ລໍດຳເນີນການ</label>
                </div>
              </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="searchBill"
                      v-on:keyup="this.searchBillUp($event)"
                    />
                    <div class="input-group-append">
                      <span class="input-group-text"
                        ><i class="fas fa-search"></i
                      ></span>
                    </div>
                  </div>
                </div></div>
            
          </div>
          <div class="table-responsive border">
            
            <table class="table align-items-center table-flush">
              <thead class="thead-light">
                <tr>
                  <!-- <th width="30" class="text-center">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-center">ຈັດການ</th>
                </tr>
              </thead>
              <tr v-if="loadingB">
                    <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>
              <tbody v-if="!loadingB">
                
                <tr v-for="bill in bills.data" :key="bill.id">
                 <!--  <th>{{ bill.id }}</th> -->
                  <td class="table-user">
                    <b>{{ bill.billnum_id }}</b>
                  </td>
                  <td class="text-left table-user">
                    <span  v-if="bill.customer_id =='0' && bill.office_id =='0' && bill.customer_name ==null" >
                      <b>ລູກຄ້າທົ່ວໄປ ເຂົ້າມາໜ້າຮ້ານ</b>
                    </span>
                    <span v-else>
                    <b>{{bill.customer_name}}</b><br>
                      <small><i class="ni ni-pin-3"></i>: {{bill.customer_address}}</small><br>
                      <span v-if="bill.customer_type=='true'"> <small><i class="ni ni-mobile-button"></i>: 020 {{bill.customer_tel}}</small> </span>
                      <span v-else> <small><i class="ni ni-mobile-button"></i>: {{bill.customer_tel}}</small> </span>
                      

                      </span>
                      <br><small> ວັນທີ່: {{date(bill.created_at)}}</small>
                  </td>
                  <td class="text-right">
                    <span class="text-muted"
                      >{{ formatPrice(bill.all_credit) }}</span
                    >
                  </td>
                  <td class="text-center">


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

                        <span class="badge badge-dot mr-4" v-if="bill.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="Bill_view($event, bill.billnum_id)" class="dropdown-item" > <i class="fas fa-file-alt"></i>ເບີ່ງບິນ </a >
                      <a href="javascript:void(0)" @click="Print($event, bill.billnum_id)" class="dropdown-item" > <i class="fas fa-print"></i>ພິມບິນ</a >
                      <router-link v-if="$store.getters['getroles'].includes('bill_edit')" :to="{ name: 'editbills', params: { id: bill.billnum_id }, }" class="dropdown-item" > <i class="fas fa-user-edit text-info"></i >ແກ້ໄຂຂໍ້ມູນ ໃບບິນ</router-link >
                      <a class="dropdown-item" href="javascript:void(0)" v-if="$store.getters['getroles'].includes('bill_remove')" @click="deleteBill(bill.billnum_id)" ><i class="fas fa-trash text-red"></i>ລຶບຂໍ້ມູນ</a >
                    </div></div>
                  </td>
                </tr>
              </tbody>
            </table>

            <vuePagination
              :pagination="bills"
              @paginate="getBills()"
              :offset="4"
            ></vuePagination>
          </div>
          </div>
        </div>
      </div>

      
    </div>

  </section>

  <div
      class="modal fade"
      id="bill_dialog"
      tabindex="-1"
      role="dialog"
      aria-labelledby="addNew"
      aria-hidden="true"
      data-keyboard="false" data-backdrop="static"
    >
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLongTitle">ເບີ່ງລາຍລະອຽດ ໃບບິນ</h5>
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
          <list-loader v-if="Loading"></list-loader>
             <div class="border-0" v-if="!Loading">
                  <div class="text-right pr-3"> 
                    <a aria-current="page"  @click="Print80($event, BillID_View)" href="javascript:void(0)" class="router-link-active router-link-exact-active btn btn-sm btn-info btn-round btn-icon"><span class="btn-inner--icon"><i class="fas fa-print"></i> ພິມບິນ 80mm</span></a>
                    <a aria-current="page"  @click="Print($event, BillID_View)" href="javascript:void(0)" class="router-link-active router-link-exact-active btn btn-sm btn-info btn-round btn-icon"><span class="btn-inner--icon"><i class="fas fa-print"></i> ພິມບິນ A4</span></a>
                    </div>
                  <div class=" container d-flex justify-content-between"> 
                    <div>
                        
                      <span v-if="CustomerData.Customer_id==0">
                        <i class="fas fa-user-alt"></i>: ລູກຄ້າທົ່ວໄປ ເຂົ້າມາໜ້າຮ້ານ
                      </span>
                      <span v-if="CustomerData.Customer_id!=0"> 
                        <i class="fas fa-user-alt" ></i>: {{CustomerData.Customer_name}} <br> 
                        <span v-if="CustomerData.CustomerSe=='true'"><i class="fas fa-mobile-alt" ></i>: 020 {{CustomerData.Customer_tel}} <br></span> 
                        <span v-if="CustomerData.CustomerSe=='false'"><i class="fas fa-mobile-alt" ></i>: {{CustomerData.Customer_tel}} <br></span> 
                        <i class="fas fa-map-marked-alt" ></i>: {{CustomerData.Customer_address}}
                      </span>
                    </div>
                    <div class="text-right">
                      <h3 class="text-primary"> ເລກທີ່ໃບບິນ: <span class="text-danger">{{ListBilldata[0].BillsId}}</span> </h3>
                    <span>ວັນທີ່: {{date(ListBilldata[0].BillDate)}}</span> <br>
                    ສະຖານະ: <span class="text-success" v-if="ListBilldata[0].PayStatus">ຊຳລະເງິນແລ້ວ</span> <span class="text-danger" v-if="!ListBilldata[0].PayStatus">ຕິດໜີ້</span>
                    <br><span>ຜູ້ສ້າງບິນ: {{user_created_bill}}</span>
                    </div>
                    
                  </div>
                <bailllist
                :ListBilldata="ListBilldata" :ViewType="true"
                ></bailllist>
              </div>
            
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-dismiss="modal"
            >
              ປິດ
            </button>
          </div>
        </div>
      </div>
    </div>
</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,
      FilterBill:this.$store.state.bills.listSet||'all',
      ListBilldata:[{
        QuoNumId:'',
        BillsId:'',
        ListItemBill:[],
        db_product:[],
        PayStatus:false,
        Sign:true,
        discount:0,
        tax:0,
        tax_set:7,
        tax_amount:null,
        AlltotalAmount:0,
        totalCount:0
        }],
        BillDate:'',
        CustomerData:{
          Type:'edit',
          CustomerSe:'',
          Customer_id:'',
          Customer_name:'',
          Customer_tel:'',
          Customer_address:''
        },
        Loading:false,
        user_created_bill:'',
        BillID_View:'',
    };
  },

  watch:{
    'FilterBill'(){
      if(this.searchBill){
        this.doSearch()
      } else {
        this.getBills()
      }
    }
  },

  methods: {
   Print80(e,id){
      window.open(window.location.origin+'/api/printbill80/'+id, "_blank");
    },
    Bill_view(e,id){
      $('#bill_dialog').modal('show');
      this.Loading = true;
      this.BillID_View = id;
     // console.log(id);
      this.GetBillsOne(id)
    },
    setPay(){
      this.$store.dispatch({
          type:"setBillList",
          listSet:'pay'
        })
    },
    setUnPay(){
      this.$store.dispatch({
          type:"setBillList",
          listSet:'unpay'
        })
    },
    setAll(){
      this.$store.dispatch({
          type:"setBillList",
          listSet:'all'
        })
    },
    date(value) {
      return moment(value).format("DD/MM/YYYY");
    },
     Print(e,id){
      window.open(window.location.origin+'/api/printbill/'+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}&filter=${this.FilterBill}`)
                .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}&filter=${this.FilterBill}`)
                .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();
                });
            });
          }
    },
    
  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}&filter=${this.FilterBill}`)
                    .then((response) => {
                            this.bills = response.data;
                            this.$Progress.finish()
                            this.loadingB = false
                    })
                    .catch(() => {
                        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()
                        });
                })
            }
            })
        },

        GetBillsOne(id){
          this.$Progress.start();
          this.$axios.get("/sanctum/csrf-cookie").then((response) => {
              axios.get(`/api/bills/edit/${id}`)
                .then((response) => {
                    if(response.data.success){
                        this.BillDate = response.data.data_bills[0].created_at
                        if(response.data.data_bills[0].ListBilldata){
                          this.ListBilldata = JSON.parse(response.data.data_bills[0].ListBilldata)
                        } else {
                          let db = response.data.billslist
                          for (let i = 0; i < db.length; i++) {
                            if(db[i]!=''){
                              this.ListBilldata[0].ListItemBill.push({
                                id: db[i].bill_list_id,
                                barcode: db[i].barcode,
                                product_name: db[i].name,
                                bill_type: db[i].bill_type,
                                count:db[i].count,
                                price:db[i].credit
                              })
                            }
                          }
                        }
                        this.ListBilldata[0].db_product = response.data.db_product
                        this.CustomerData.CustomerSe = response.data.data_bills[0].customer_type;
                        this.CustomerData.Customer_id = response.data.data_bills[0].customer_id;
                        this.CustomerData.Customer_name = response.data.data_bills[0].customer_name;
                        this.CustomerData.Customer_tel = response.data.data_bills[0].customer_tel;
                        this.CustomerData.Customer_address = response.data.data_bills[0].customer_address;
                        this.user_created_bill = response.data.data_bills[0].sex+' '+response.data.data_bills[0].name+' '+response.data.data_bills[0].last_name;

                        let payStatus = false
                          let Sign = false
                          if(response.data.data_bills[0].status == 'payed') { payStatus = true }
                          if(response.data.data_bills[0].signed == 'true') { Sign = true }
                          this.ListBilldata[0].PayStatus = payStatus
                          this.ListBilldata[0].Sign = Sign

                          this.ListBilldata[0].BillsId = id;
                          this.ListBilldata[0].BillDate = response.data.data_bills[0].created_at;

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

                    this.Loading = false
                  //this.QuoData = response.data

                  //this.updateCustomerDisplay()
                })
                .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()

    // 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'}]
        })

        //console.log(this.$store.state.bills.listSet);
  },
  beforeRouteEnter(to, from, next) {
        if (!window.Laravel.isLoggedin) {
            window.location.href = "/";
        }
        next();
    }
};
</script>

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