<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-md-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-md-5 text-right">
            <a
              @click="$router.go(-1)"
              class="btn btn-sm btn-info btn-round btn-icon"
            >
              <span class="btn-inner--icon text-white"
                ><i class="ni ni-bold-left"></i
              ></span>
              <span class="text-white">ກັບຄືນ</span>
            </a>
          
          </div>
        </div>
      </div>
    </div>
    <div class="row" v-if="isLoggedIn"> 
      <div class="col-lg-8"> 
        <div class="card">
          <!-- Card header -->
          <div class="card-header border-0">
            <div class="row d-flex justify-content-between px-3">
              <div class="">
                <h3 class="mb-0">ໃບສະເໜີລາຄາ ເລກທີ່: <span class="text-danger"> {{ QuoNumId }}<div v-if="!QuoNumId" class="spinner-grow" style="width: 22px; height: 22px;" role="status"> <span class="sr-only">Loading...</span>  </div> </span> </h3> 
              </div>
              <div class=" text-right"><span :class="CheckCashBT"></span>
                <a aria-current="page" v-if="ListBilldata[0].ListItemBill.length==0"  @click="CancelQuo" href="javascript:void(0)" class=" router-link-active router-link-exact-active btn btn-sm btn-warning btn-round btn-icon " ><span class="btn-inner--icon" > <i class="fas fa-times-circle"></i>  ຍົກເລີກ ໃບສະເໜີລາຄາ</span ></a >
                <!-- <a aria-current="page" @click="Print" href="javascript:void(0)" :class="chbtprint" 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> ພິມ Mini</span ></a > -->
                <a aria-current="page" v-if="ListBilldata[0].ListItemBill.length>0"  :class="CheckForm_sent_to_bill" @click="SentToBill()" 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-file-invoice"></i> ສົ່ງໄປໃບບິນ </span ></a >
                <a aria-current="page" v-if="ListBilldata[0].ListItemBill.length>0"  :class="CheckForm" @click="SavePrint('true')" href="javascript:void(0)" class=" router-link-active router-link-exact-active btn btn-sm btn-success btn-round btn-icon " ><span class="btn-inner--icon" ><i class="fas fa-file-export"></i> ບັນທຶກ ແລະ ພິມ</span ></a >
                <a aria-current="page" v-if="ListBilldata[0].ListItemBill.length>0"  :class="CheckForm" @click="SavePrint" href="javascript:void(0)" class=" router-link-active router-link-exact-active btn btn-sm btn-warning btn-round btn-icon " ><span class="btn-inner--icon" ><i class="fas fa-save"></i> ບັນທຶກ</span ></a
                >
              </div>
            </div>
          </div>

         
          <div class="card-bordy p-2 mt--4">
             <bailllist
                :ListBilldata="ListBilldata"
                ></bailllist>
          </div>

        </div>


      </div>

      <div class="col-lg-4">
        <div class="card">
          <!-- Card header -->
          <div class="card-header border-0">
            <div class="row">
              <div class="col-12">
                <h3 class="mb-0"><i class="fas fa-user"></i> ຂໍ້ມູນລູກຄ້າ</h3>
              </div>

            </div>
          </div>

          <!-- Light table -->
          <div class="card-body">
              
                    <getcustomer :CustomerData="CustomerData" />

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

<script>
import html2pdf from "html2pdf.js";

export default {
  name: "Bills",

  components: {
    html2pdf,
  },

  directives: {},
  watch: {
    CashType(){
      if(this.CashType=='false'){ this.CashAmount = String(this.ListBilldata[0].AlltotalAmount) } else { this.CashAmount = '' }
    },
    'CustomerSe'(){

          this.SeclectCustomer = 0
          if(this.CustomerSe=='true'){
              this.ListCustomer = this.CustomerList
          } else {
                this.ListCustomer = this.OfficeList
          }
      },
     
  },
  data() {
    return {
      Unit:[],
      BillsId: "",
      QuoNumId:"",
      Fbills: {
        name: "",
        detail: "",
        count: null || 1,
        credit: "",
        bill_type:"product",
        product_id:''
      },
      billslist: [],
      invoce: [],
      search: "",
      status_created: true,
      billTax_set: 7,
      billTax: "",
      billsDiscut: "",
      BillSetting: "",
      Customer_data: "",
      Customer_more_detail: "",
      CustomerBill: "true",
      office_select: "",
      PayStatus: false,
      Sign: false,
      output: null,
      polling: null,
      ModalAdd: true,
      listUpdateId: "",

      Customer: {
        Name: "",
        Tel: "",
        Address: "",
        Detail: "",
      },
      SeclectCustomer: "0",
      CustomerSe: "true",
      office_select: "0",
      caddress: "",
      btprint:false,
      formPost:true,
      CashType:true,
      CashAmount:0,
      daCashPayBT:true,
      barcode:null,
      isLoggedIn: false,
      //new List Bill
      ListBillRepaire:[],
      // new
      ListBilldata:[{
        QuoNumId:'',
        BillsId:'',
        ListItemBill:[],
        db_product:[],
        PayStatus:false,
        Sign:true,
        discount:0,
        tax:0,
        tax_set:7,
        tax_amount:null,
        AlltotalAmount:0,
        totalCount:0
        }],
        // pay status: payed
        //pay_status: 'pending',
        CustomerData:{
          Size:'S',
          Type:'',
          CustomerSe:'',
          Customer_id:'',
          Customer_name:'',
          Customer_tel:'',
          Customer_address:'',
          
        },
        CheckForm_sent_to_bill:'disabled'
    };
  },
  computed: {
    CheckCashBT(){
      this.updateCustomerDisplay()
      if(this.ListBilldata[0].ListItemBill.length==0){ this.ListBilldata[0].AlltotalAmount = 0 }
      if(parseInt(this.ListBilldata[0].AlltotalAmount) == 0){
          return true
      } else {

        if(parseInt(this.CashAmount) < parseInt(this.ListBilldata[0].AlltotalAmount)) {
          return true
          } else {
            return false
            }
      }
    },
     CheckForm(){
        if(parseInt(this.ListBilldata[0].ListItemBill.length) > 0){
                if(this.formPost){
                   return '' } 
                   else { return 'disabled' }
              } else {
                 return 'disabled'}
               
      },
    chbtprint(){
      if(this.btprint){ return '' } else { return 'disabled'}
    },
    customer_id() {
      if (this.CustomerSe == "true") {
        return this.SeclectCustomer;
      } else {
        return this.office_select;
      }
    },
    shform() {
      if (this.CustomerSe == "true") {
        if (this.SeclectCustomer == "0") {
          return true;
        } else {
          return false;
        }
      } else {
        if (this.office_select == "0") {
          return true;
        } else {
          return false;
        }
      }
    },

  },
  methods: {
    CancelQuo(){
      this.$Progress.start()
                this.$axios.get('/sanctum/csrf-cookie').then(response => {
                    this.$axios.delete(`/api/quotation/delete/${this.QuoNumId}`)
                        .then(response => {
                             //this.getBills()
                            if (response.data.success) {
                              this.$router.go(-1)
                              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()
                        });
                })
    },

    SentToBill(){
         this.$Progress.start();
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
        this.$axios
          .post(`/api/bills/import_quo_to_bill/${this.QuoNumId}`, {
            customer_id: this.CustomerData.Customer_id,
            office_id: this.CustomerData.Customer_id,
            customer_name: this.CustomerData.Customer_name,
            customer_tel: this.CustomerData.Customer_tel,
            customer_address: this.CustomerData.Customer_address,
            user_id: window.Laravel.user.id,
            status: this.ListBilldata[0].PayStatus,
            signed: this.ListBilldata[0].Sign,
            customer_type: this.CustomerData.CustomerSe,
            list_bill:this.ListBilldata[0].ListItemBill,
            db_product:this.ListBilldata[0].db_product,
            totalAmount:this.ListBilldata[0].AlltotalAmount,
            totalCount:this.ListBilldata[0].totalCount,
            trn_type:'cincome',
            PayStatus:this.ListBilldata[0].PayStatus,
            ListBilldata:this.ListBilldata,
            tax:this.ListBilldata[0].tax,
            tax_amount: this.ListBilldata[0].tax_amount,
            discount: this.ListBilldata[0].discount,
            CashType: this.CashType,
          })
          .then((response) => {
    
            if(response.data.success){
              this.btprint = true
              this.$Progress.finish();
               this.$notify({ group: "sucess", title: "ສຳເລັດ!", text: response.data.message }, 2000)
            } else {
              this.$Progress.fail();
              this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+ response.data.message }, 4000)
            }
          })
          .catch((error)=> {
            this.btprint = true
             this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
            //console.error(error);
            this.$Progress.fail();
          });
      });
    },
    CashPayBT(){
      this.daCashPayBT = false
      this.ListBilldata[0].PayStatus = true
      this.SavePrint()
    },
    AddAm(vl){
      if(vl=='-'){ //str.substring(0, str.length - 1)
        let pr = this.CashAmount.toString().slice(0, -1)
        if(pr==''){ this.CashAmount = 0} else { this.CashAmount=pr }
      } else {
        let pa = ''
        if(this.CashAmount==0){ pa = '' } else { pa = this.CashAmount.toString() }
        this.CashAmount = pa+vl
      }
    },

    GetBillSetting() {
      this.$Progress.start();
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
        axios
          .get(`/api/billsetting`)
          .then((response) => {
            this.$Progress.finish();
            this.BillSetting = response.data;
            //console.log(response.data.bill_size)
            //console.log(this.BillSetting.customer_default)
            if (this.BillSetting.customer_default) {
             /// this.GetOneCustomer(this.BillSetting.customer_default);
            }
          })
          .catch((error) => {
             this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
            ///console.error(error);
            this.$Progress.fail();
          });
      });
    },
    CreatedQuotation() {
    if(this.status_created){
      this.$Progress.start();
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
        axios
          .post("/api/quotation/add",)
          .then((response) => {
            if (response.data.success) {
              this.$Progress.finish();
               this.QuoNumId = response.data.quonum_id
               this.ListBilldata[0].QuoNumId = response.data.quonum_id
               this.status_created = false
            } else {
              this.error = response.data.message;
              console.error(error);
              this.$Progress.fail();
            }
          })
          .catch((error)=> {
             this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
          });
      });
    }
  },
    formatPrice(value) {
      let val = (value / 1).toFixed(0).replace(".", ",");
      return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
    SavePrint(print) {
      this.formPost = false
      this.$Progress.start();
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
        this.$axios
          .post(`/api/quotation/update/${this.QuoNumId}`, {
            customer_id: this.CustomerData.Customer_id,
            office_id: this.CustomerData.Customer_id,
            customer_name: this.CustomerData.Customer_name,
            customer_tel: this.CustomerData.Customer_tel,
            customer_address: this.CustomerData.Customer_address,
            user_id: window.Laravel.user.id,
            status: this.ListBilldata[0].PayStatus,
            signed: this.ListBilldata[0].Sign,
            customer_type: this.CustomerData.CustomerSe,
            list_bill:this.ListBilldata[0].ListItemBill,
            db_product:this.ListBilldata[0].db_product,
            totalAmount:this.ListBilldata[0].AlltotalAmount,
            totalCount:this.ListBilldata[0].totalCount,
            trn_type:'cincome',
            PayStatus:this.ListBilldata[0].PayStatus,
            ListBilldata:this.ListBilldata,
            tax:this.ListBilldata[0].tax,
            tax_amount: this.ListBilldata[0].tax_amount,
            discount: this.ListBilldata[0].discount,
            CashType: this.CashType,
          })
          .then((response) => {
            if(response.data.success){
              if (print === "true") {
                window.open( window.location.origin + "/api/printquotation/" + this.QuoNumId, "_blank" );
              }
              this.CheckForm_sent_to_bill = '';
              this.formPost = true
              this.btprint = true
              this.$Progress.finish();
               this.$notify({ group: "sucess", title: "ສຳເລັດ!", text: response.data.message }, 2000)
            } else {
              this.$Progress.fail();
              this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+ response.data.message }, 4000)
            }
          })
          .catch((error)=> {
            this.btprint = true
             this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
            //console.error(error);
            this.$Progress.fail();
          });
      });
    },

      getPriceSell(priceorg){
          let product_prices = JSON.parse(priceorg).product_prices
          let product_options = JSON.parse(priceorg).product_options
          let po = product_options.find((i)=> i.option_default == 'true')
          let pri = product_prices.find((i)=> i.option_id == po.option_id && i.default == 'true')
          let priPro = product_prices.find((i)=> i.option_id == po.option_id && i.default == 'true' && i.default_pro == 'true')

          if(priPro){
            return priPro.price_pro
          } else {
            if(pri){ return pri.price } else { return ''}
          }
        },

        updateCustomerDisplay(){
          this.$store.dispatch({
          type:"setCustomerBill",
          listbill: this.ListBilldata[0].ListItemBill,
          customer: [{'customerSelect':this.CustomerData.Customer_id,'listCustomer':this.CustomerData,'CustomerSe':this.CustomerData.CustomerSe,'staff':window.Laravel.user.sex+' '+window.Laravel.user.name+' '+window.Laravel.user.last_name}],
          option: [{'discount':this.ListBilldata[0].discount,'tax':this.ListBilldata[0].tax_amount,'alltatal':this.ListBilldata[0].AlltotalAmount}]
        })
      },

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

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

    this.CreatedQuotation();
    this.GetBillSetting();

 
  },

  beforeRouteEnter(to, from, next) {
    if (!window.Laravel.isLoggedin) {
      window.location.href = "/";
    }
    next();
  },
};
</script>
<style lang="scss" scoped>
.table td, .table th {
    padding: 8px;
}
</style>
