<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">
              <a @click="$router.go(-1)" aria-current="page" href="javascript:void(0)" class=" router-link-active router-link-exact-active btn btn-sm btn-info btn-round btn-icon mb-2 " ><span class="btn-inner--icon" ><i class="fas fa-chevron-left"></i> ກັບຄືນ</span></a>
            </div>
          </div>
        </div>
      </div>
      <div class="row" v-if="isLoggedIn">
        <div class="col-md-12">
          <div class="card">
            <div class="card-header d-flex justify-content-between">
              <div>ໃບສັ່ງຊື້ ເລກທີ່: {{ PreOrderID }} </div>
              <div>
                <a @click="AddImport()" :class="CheckImportBT" aria-current="page" href="javascript:void(0)" class=" router-link-active router-link-exact-active btn btn-sm btn-success btn-round btn-icon mb-2 " v-if="transport_status!='imported'" ><span class="btn-inner--icon" ><i class="fas fa-download"></i> ບັນທຶກນຳເຂົ້າ</span></a>
                <a @click="ImportToBill()" :class="CheckImportBT" aria-current="page" href="javascript:void(0)" class=" router-link-active router-link-exact-active btn btn-sm btn-warning btn-round btn-icon mb-2 " v-if="transport_status=='imported'" ><span class="btn-inner--icon" ><i class="fas fa-file-invoice"></i> ສ້າງໃບບິນ</span></a>
                
              </div>
            </div>
            <div class="row container mt-2">
              <div class="col-md-4 mb-4">
                
                <h3 class=" text-info">ຜູ້ສະໜອງສິນຄ້າ</h3>
                <list-loader v-if="loading_check"></list-loader>
                <div v-if="!loading_check"> 
                        <div class="col flex justify-center mb-2">
                        <span class="avatar avatar-xl rounded-circle">
                
                          <img
                            alt="Image placeholder"
                            :src="SupplierData.images"
                          />
                        </span>
                      </div>
                      <div class="ml-3">
                        <i class="fas fa-warehouse"></i>: {{SupplierData.name}}<br />
                        <i class="fas fa-mobile-alt"></i>: {{SupplierData.tel}}<br />
                        <i class="fas fa-map-marked-alt"></i>: {{SupplierData.address}}
                      
                      </div>
                      </div>
              </div>
              <div class="col-md-4 mb-4">
                <h3 class=" text-info">ຜູ້ສັ່ງຊື້ສິນຄ້າ</h3>
                <list-loader v-if="loading_check"></list-loader>
                <div v-if="!loading_check"> 
                      <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>
                        <i class="fas fa-mobile-alt" ></i>: {{CustomerData.Customer_tel}} <br>
                        <i class="fas fa-map-marked-alt" ></i>: {{CustomerData.Customer_address}}
                      </span>
                      </div>
              </div>
              <div class="col-md-4 mb-4">
                <h3 class=" text-info">ການຂົນສົ່ງ</h3>
                <list-loader v-if="loading_check"></list-loader>
                <div v-if="!loading_check"> 
                      ສັ່ງຊື້ເມື່ອ: {{ date(DayOrder) }}<br>
                      ວັນທີ່ຂົນສົ່ງ: {{ dayto(TranDay)}}
                  
                </div>
              </div>
            </div>

          </div>

          <div class="row">
           

          
          </div>
          <div class="row">
            <div class="col-md-8">
              <div class="card">
                <div class="card-header border-0 ">
             ລາຍກນສິນຄ້າ
                </div>

                <div class="">
                  <list-loader v-if="loading_check" class="p-4"></list-loader>

                  <div class="table-responsive " v-if="!loading_check">
                    <vue-easy-lightbox
                            scrollDisabled
                            escDisabled
                            moveDisabled
                            :visible="visible"
                            :imgs="images_show"
                            :index="index"
                            @hide="handleHide"
                          >
                          </vue-easy-lightbox>
                    <table class="table align-items-center table-flush">
                      <thead class="thead-light">
                        <tr>
                          <!-- <th width="30">ID</th> -->
                          <th class="text-center" width="120">ຮູບ</th>
                          <th class="text-left">ຊື່ລາຍການ</th>
                          <th class="text-center" width="110">ລາຄາຊື້</th>
                          <th class="text-center" width="90">ຈຳນວນ</th>
                          <th class="text-right" width="140">ລວມ</th>
                          <th width="80" class="text-center" >ນຳເຂົ້າ</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr v-for="list in ListPreorder" :key="list.id">
                          <td>
                            <span class="avatar avatar-xl border-radius-lg cursor-pointer">
                              <img v-if="list.images" alt="Image placeholder" @click="imgbox(localtionURL + '/images/product/' + list.images)" :src=" localtionURL + '/images/product/' + list.images " />
                              <img v-else alt="Image placeholder" :src="localtionURL + '/images/add_img_bt.png'" />
                            </span>
                          </td>
                          <td>
                            {{ list.name }}<br />
                            <small>{{ list.detail }}</small>
                          </td>
                          <td class="text-right">
                            {{ formatPrice(list.price_buy) }} ກີບ
                          </td> 
                     
                          <td class="text-center" >
                         
                            {{ list.amount }}
                           
                          </td>
                          <td class="text-right">
                            {{ formatPrice(list.amount * list.price_buy) }} ກີບ
                          </td>
                          <td class="table-action text-center" >
                                <span  class=" "  v-if="list.product_id && PayStatus" >  
                                  <i class="fas fa-check-circle text-success fa-2x" v-if="list.item_tran_status == 'imported'"></i>
                                  <i class="fas fa-download text-warning fa-2x cursor-pointer" @click="AddImport(list.id)" v-if="list.item_tran_status == 'pending'"></i>
                                </span>
                                <Popper content="ທ່ານຍັງບໍ່ຊຳລ່ະເງິນເທື່ອ!">
                                <i class="fas fa-exclamation-triangle fa-2x text-danger" v-if="!PayStatus"></i>
                                </Popper>
                          </td>
                        </tr>
                      </tbody>
                      <thead class="thead-light">
                        <tr>
                          <th class="text-center" width="120"></th>
                          <th class="text-left"></th>
                          <th class="text-center" width="110">ລວມທັງໝົດ</th>
                          <th class="text-center" width="90"></th>
                          <th class="text-right" width="110">
                            {{ formatPrice(AmountPreorder) }} ກີບ
                          </th>
                          <th></th>
                        </tr>
                      </thead>
                    </table>
                  </div>
                </div>
                <div class="card-footer"></div>
              </div>
            </div>

            <div class="col-md-4">
              <div class="card">
                <div class="card-header border-0">
                        <i class="fas fa-donate"></i> ຄ່າຂົນສົ່ງ
                </div>
               <list-loader v-if="loading_check" class="p-4"></list-loader>
                 <div class="table-responsive" v-if="!loading_check">
                    <table class="table align-items-center table-flush">
                    <thead class="thead-light">
                      <tr>
                        <th class="text-left">ລາຍນລະອຽດຂົນສົ່ງ</th>
                        <th class="text-right" width="120">ລາຄາຂົນສົ່ງ</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="list in tranData.ListTran" :key="list.id">
                        <td>{{ list.detail }}</td>
                        <td class="text-right">{{ formatPrice(list.price) }} ກີບ</td>
                        
                      </tr>
                    </tbody>
                    <thead class="thead-light">
                      <tr>
                        <th class=" text-right"> ລວມທັງໝົດ:</th>
                        <th class=" text-right"> {{formatPrice(AmountTran)}} ກີບ</th>
                      </tr>
                    </thead>
                  </table>
                  </div>
                 
                    <div class="card-footer"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
    <div
      class="modal fade"
      id="add_list_preorder"
      tabindex="-1"
      role="dialog"
      aria-labelledby="add_custom"
      data-keyboard="false"
      data-backdrop="static"
      aria-hidden="true"
    >
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLongTitle">
              <i class="fas fa-list-ul"></i> ເພີ່ມລາຍການສິນຄ້າ
            </h5>
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <div class="row">
              <div class="col-md-12">
                <uploadimgoneproduct :imagesBack="FormPreData" />
              </div>

              <div class="col-md-6">
                <div class="form-group">
                  <div class="input-group input-group-merge">
                    <div class="input-group-prepend">
                      <span class="input-group-text"
                        ><i class="fas fa-stream"></i
                      ></span>
                    </div>

                    <input
                      type="text"
                      class="form-control"
                      name="name"
                      placeholder="ຊື່ສິນຄ້າ"
                      v-model="FormPreData.name"
                      ref="namepre"
                    />
                  </div>
                </div>
              </div>
              <div class="col-md-6">
                <div class="form-group">
                  <div class="input-group input-group-merge">
                    <cleave
                      :options="option"
                      class="form-control"
                      placeholder="ລາຄາຊື້"
                      v-model="FormPreData.price"
                    />
                    <div class="input-group-append">
                      <span class="input-group-text"
                        ><i class="fas fa-donate"></i
                      ></span>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-md-6">
                <div class="form-group">
                  <div class="input-group input-group-merge">
                    <div class="input-group-prepend">
                      <span class="input-group-text"
                        ><i class="ni ni-fat-add"></i
                      ></span>
                    </div>
                    <input
                      class="form-control"
                      placeholder="ຈຳນວນ"
                      type="number"
                      pattern="[1-99]"
                      style="width: 80px"
                      v-model="FormPreData.amount"
                    />
                  </div>
                </div>
              </div>

              <div class="col-md-12">
                <label class="form-control-label">ລາຍລະອຽດ:</label>
                <textarea
                  class="form-control mb-4"
                  rows="3"
                  v-model="FormPreData.detail"
                ></textarea>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-primary"
              :disabled="check"
              @click="SavePre"
            >
              ບັນທຶກ
            </button>
            <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: "order",
  components: {},
  data() {
    return {
      visible: false,
      index:0,
      images_show:'',
      PreOrderID: "",
      isLoggedIn: false,
      Repaires: [],
      searchOrder: null,
      loading: false,
      CustomerData: {
        Size: "S",
        CustomerSe: "",
        Customer_id: "",
        Customer_name: "",
        Customer_tel: "",
        Customer_address: "",
      },
      SupplierData: {
            name: "",
            tel: "",
            address: "",
            images: "",
          },
      tranData: {
        ListTran: [],
      },
      FormPreType: true,
      FormPreShow: false,
      FormPreID: "",
      FormPreData: {
        product_id: "",
        name: "",
        amount: 1,
        price: "",
        detail: "",
        images: "",
      },
      ListPreorder: [],
      ListBilldata:[{
        QuoNumId:'',
        BillsId:'',
        ListItemBill:[],
        db_product:[],
        PayStatus:false,
        Sign:true,
        discount:0,
        tax:0,
        tax_set:10,
        tax_amount:null,
        AlltotalAmount:0,
        totalCount:0
        }],
      option: {
        // prefix: '$ ',
        numeral: true,
        numeralPositiveOnly: true,
        noImmediatePrefix: true,
        rawValueTrimPrefix: true,
        numeralIntegerScale: 10,
        numeralDecimalScale: 2,
        numeralDecimalMark: ".",
        delimiter: ",",
      },
      localtionURL: window.location.origin,
      config: {
        mode: "range",
        wrap: true, // set wrap to true only when using 'input-group'
        altFormat: "d/m/Y",
        altInput: true,
        dateFormat: "Y-m-d",
        allowInput: true,
      },

      TranDay: "",
      TranDaycom: "",
      barcode: "",
      CashType_pre: true,
      CashAmount: 0,
      PayStatus: false,
      EditForm_pre:false,
      DayOrder:'',
      loading_check: false,
      transport_status:'',
    };
  },
  watch:{
    // ListPreorder(){
    //   this.EditForm_pre = true
    // }
    CashType_pre(){
      if(this.CashType_pre=='false'){ this.CashAmount = this.AmountPreorder } else { this.CashAmount = 0 }
    },
  },
  computed: {
    CheckImportBT(){
      if(this.PayStatus) { return '' } else { return 'disabled' }
    },
    CheckCashBT(){
      if(parseInt(this.CashAmount) == 0){
        return true
      } else {
        if(parseInt(this.CashAmount) < parseInt(this.AmountPreorder)) {
          return true
          } else {
            return false
            }
        }
    },
    check() {
      if (this.FormPreData.name == "" || this.FormPreData.price == "") {
        return true;
      } else {
        return false;
      }
    },
    AmountPreorder() {
      return this.ListPreorder.reduce(
        (price_buy, item) => parseInt(price_buy) + parseInt(item.price_buy * item.amount),
        0
      );
    },
    AmountTran() {
      return this.tranData.ListTran.reduce(
        (price, item) => parseInt(price) + parseInt(item.price),
        0
      );
    },
    // AlltotalListAmount(){
    //   return this.ListPreorder.reduce(
    //     (price, item) => parseInt(price) + parseInt(item.amount*item.price),
    //     0
    //   );
    // },
  },

  methods: {
    imgbox(img){
       // alert(img);
        this.images_show = img;
        this.show()
    },
    show() {
        this.visible = true
      },
      handleHide() {
        this.visible = false
      },
    ImportToBill(){
     // alert('import to bill')
      this.$Progress.start();
                this.$axios.get("/sanctum/csrf-cookie").then((response) => {
                  axios.post(`/api/preorder/import_to_bill`,{
                    customer_data:this.CustomerData,
                    preorder_import:this.ListPreorder,
                    preorder_id:this.PreOrderID,
                    user_id: window.Laravel.user.id, 
                  }).then((response) => {
                      if (response.data.success) {
                        if(response.data.billnum_id!=null){
                          this.$router.push('/bills/edit/'+response.data.billnum_id);
                        }
                       // this.GetPreOrder();
                        this.$Progress.finish();
                      } 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 );
                    });
                });
    },
    AddImport(id){
      if(id!=null){
        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) => {
                  axios.post(`/api/preorder_item/add_import`,{
                    item_id:id,
                    preorder_import:this.ListPreorder,
                    preorder_id:this.PreOrderID,
                    user_id: window.Laravel.user.id, 
                  }).then((response) => {
                      if (response.data.success) {
                        this.GetPreOrder();
                        this.$Progress.finish();
                      } 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 );
                    });
                });
            }
            });
      } else {
      this.$Progress.start();
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
        axios.post(`/api/preorder_item/add_import`,{
          item_id:id,
          preorder_import:this.ListPreorder,
          preorder_id:this.PreOrderID,
          user_id: window.Laravel.user.id, 
        }).then((response) => {
            if (response.data.success) {
              this.GetPreOrder();
              this.$Progress.finish();
            } 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 );
          });
      });
      }
    },
    add_import(id){
      //if(this.ProductImportID.includes(id)){let findex = this.ProductImportID.findIndex((i) => i == id); this.ProductImportID.splice(findex,1)} else {this.ProductImportID.push(id);}
      let getfind = this.ListPreorder.find((i)=>i.id==id);
      //console.log(getfind)
      if(getfind){
        if(getfind.item_tran_status=='pending'){
          getfind.item_tran_status='imported';
        } else if(getfind.item_tran_status='imported'){
          getfind.item_tran_status='pending';
        }
      }
    },
    date(value) {
      return moment(value).format("DD/MM/YYYY");
    },
    dayto(day){
        if(day!=''){
          let day_start = day.split(' ');
         return this.date(day_start[0])+' - '+this.date(day_start[2])
        }
        
      },
    CashPayBT(){
      this.PayStatus = true
      this.SavePreorder()
    },
    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;
      }
    },
    RemoveNumPro(id) {
      if (this.ListPreorder.find((i) => i.product_id == id)) {
        this.ListPreorder.find((i) => i.product_id == id).amount =
          this.ListPreorder.find((i) => i.product_id == id).amount - 1;
        if (this.ListPreorder.find((i) => i.product_id == id).amount < 1) {
          this.$notify(
            {
              group: "sucess",
              title: "ສຳເລັດ!",
              text: " ຂໍ້ມູນໄດ້ຖຶກລຶບແລ້ວ! ",
            },
            2000
          );
          this.ListPreorder.splice(
            this.ListPreorder.map((i) => i.product_id).indexOf(id),
            1
          );
        }
      }
      this.EditForm_pre = true
    },
    AddNumPro(id) {
      if (this.ListPreorder.find((i) => i.product_id == id)) {
        this.ListPreorder.find((i) => i.product_id == id).amount =
          this.ListPreorder.find((i) => i.product_id == id).amount + 1;
      }
      this.EditForm_pre = true
    },
    RemovePro(id) {
      this.$notify(
        { group: "sucess", title: "ສຳເລັດ!", text: " ຂໍ້ມູນໄດ້ຖຶກລຶບແລ້ວ! " },
        2000
      );
      this.ListPreorder.splice(
        this.ListPreorder.map((i) => i.product_id).indexOf(id),
        1
      );
      this.EditForm_pre = true
    },
    getDate(e) {
      this.TranDay = e;
    },
    GetProduct() {
      // console.log(this.barcode)
      this.$Progress.start();
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
        axios
          .get(`/api/store/product/sbarcode/${this.barcode}`)
          .then((response) => {
            if (response.data.success) {
              let db_product = response.data.product;
              let product_options = response.data.product_options;
              let product_prices = response.data.product_prices;

              //console.log(db_product[0]);

              //this.BarcodeAdd(this.barcode, db_product, product_options, product_prices)

              if (
                this.ListPreorder.find(
                  (i) => i.product_id == db_product[0].product_id
                )
              ) {
                this.ListPreorder.find(
                  (i) => i.product_id == db_product[0].product_id
                ).amount =
                  this.ListPreorder.find(
                    (i) => i.product_id == db_product[0].product_id
                  ).amount + 1;
                //console.log(this.ListPreorder.find((i)=>i.product_id==db_product[0].product_id).amount+1)
              } else {
                let product_img = "";
                if (
                  db_product[0].product_images != null ||
                  db_product[0].product_images != ""
                ) {
                  product_img = JSON.parse(db_product[0].product_images)[0];
                }
                //console.log(product_img.img);
                this.ListPreorder.push({
                  id: Math.floor(Math.random() * 10000),
                  product_id: db_product[0].product_id,
                  name: db_product[0].product_name,
                  amount: 1,
                  price: db_product[0].product_price_buy,
                  detail: db_product[0].product_detail,
                  images: product_img.img,
                });
              }

              this.$Progress.finish();
              this.barcode = null;
              this.EditForm_pre = true
            } else {
              this.$Progress.fail();
              this.barcode = null;
              this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: response.data.message, }, 4000 );
            }
          })
          .catch((error) => {
            this.$Progress.fail();
            this.dable_add = false;
            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, ",");
    },
    searchOrder_up(e) {},
    AddPre() {
      $("#add_list_preorder").modal("show");
      this.FormPreData.product_id = "";
      this.FormPreData.name = "";
      this.FormPreData.amount = 1;
      this.FormPreData.detail = "";
      this.FormPreData.price = "";
      this.FormPreData.images = "";

      this.polling = setInterval(() => {
        this.$refs.namepre.focus();
        clearInterval(this.polling);
      }, 500);
    },
    SavePre() {
      if (this.FormPreType) {
        this.ListPreorder.push({
          id: Math.floor(Math.random() * 10000),
          product_id: this.FormPreData.product_id,
          name: this.FormPreData.name,
          amount: this.FormPreData.amount,
          price: this.FormPreData.price,
          detail: this.FormPreData.detail,
          images: this.FormPreData.images,
        });
      } else {
        this.ListPreorder.find((i) => i.id == this.FormPreID).name =
          this.FormPreData.name;
        this.ListPreorder.find((i) => i.id == this.FormPreID).amount =
          this.FormPreData.amount;
        this.ListPreorder.find((i) => i.id == this.FormPreID).product_id =
          this.FormPreData.product_id;
        this.ListPreorder.find((i) => i.id == this.FormPreID).price =
          this.FormPreData.price;
        this.ListPreorder.find((i) => i.id == this.FormPreID).detail =
          this.FormPreData.detail;
        this.ListPreorder.find((i) => i.id == this.FormPreID).images =
          this.FormPreData.images;
      }
      $("#add_list_preorder").modal("hide");
      this.FormPreType = true;
      this.FormPreData.product_id = "";
      this.FormPreData.name = "";
      this.FormPreData.amount = 1;
      this.FormPreData.detail = "";
      this.FormPreData.price = "";
      this.FormPreData.images = "";
      this.FormPreID = "";

      this.EditForm_pre = true
    },
    EditPre(id) {
      let item = this.ListPreorder.find((i) => i.id == id);
      $("#add_list_preorder").modal("show");
      this.FormPreID = id;
      this.FormPreType = false;
      this.FormPreData.product_id = item.product_id;
      this.FormPreData.name = item.name;
      this.FormPreData.amount = item.amount;
      this.FormPreData.detail = item.detail;
      this.FormPreData.price = item.price;
      this.FormPreData.images = item.images;
    },
    DelPre(id) {
      this.$swal
        .fire({
          title: "ທ່ານແນ່ໃຈບໍ່?",
          text: "ທີ່ຈະລຶບຂໍ້ມູນນີ້!",
          icon: "warning",
          showCancelButton: true,
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "ລຶບເລີຍ!",
          cancelButtonText: "ຍົກເລີກ",
        })
        .then((result) => {
          if (result.isConfirmed) {
            let item = this.ListPreorder.find((i) => i.id == id);
            if (item.product_id) {
              this.$notify( { group: "sucess", title: "ສຳເລັດ!", text: " ຂໍ້ມູນໄດ້ຖຶກລຶບແລ້ວ! ", }, 2000 );
              this.ListPreorder.splice(
                this.ListPreorder.map((i) => i.id).indexOf(id),
                1
              );
            } else {
              if (item.images) {
                this.$Progress.start();
                this.$axios.get("/sanctum/csrf-cookie").then((response) => {
                  axios
                    .post("/api/img/del_img_product", {
                      image_del: item.images,
                    })
                    .then((response) => {
                      if (response.data.success) {
                        this.$Progress.finish();
                        this.$notify( { group: "sucess", title: "ສຳເລັດ!", text: " ຮູບໄດ້ຖຶກລຶບແລ້ວ! ", }, 2000 );
                        this.ListPreorder.splice(
                          this.ListPreorder.map((i) => i.id).indexOf(id),
                          1
                        );
                      } else {
                        this.error = response.data.message;
                        this.$Progress.fail();
                      }
                    })
                    .catch((error) => {
                      this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: "ຜິດຜາດ: " + error.message, }, 4000 );
                    });
                });
              } else {
                this.$notify( { group: "sucess", title: "ສຳເລັດ!", text: " ຂໍ້ມູນໄດ້ຖຶກລຶບແລ້ວ! ", }, 2000 );
                this.ListPreorder.splice(
                  this.ListPreorder.map((i) => i.id).indexOf(id),
                  1
                );
              }
            }
          }
        });
    },
    SavePreorder() {
      this.$Progress.start();
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
        axios
          .post(`/api/preorder/update/${this.PreOrderID}`, {
            supplier_id: this.SupplierData.SupplierID,
            customer_id: this.CustomerData.Customer_id,
            customer_type: this.CustomerData.CustomerSe,
            customer_name: this.CustomerData.Customer_name,
            customer_tel: this.CustomerData.Customer_tel,
            customer_address: this.CustomerData.Customer_address,
            tran_price: this.tranData.ListTran,
            preoder_item: this.ListPreorder,
            amount: this.AmountPreorder,
            amountTran: this.AmountTran,
            transport_day: this.TranDay,
            transport_status:'pending',
            transport_day_come: "",
            user_id: window.Laravel.user.id,
            CashType_pre: this.CashType_pre,
            PayStatus: this.PayStatus,
            EditForm_pre:this.EditForm_pre,
          })
          .then((response) => {
            if (response.data.success) {
              this.$Progress.finish();
              this.$notify( { group: "sucess", title: "ສຳເລັດ!", text: response.data.message, }, 2000 );
              //this.$router.push('/service/preorder')
              this.EditForm_pre = false
            } else {
              this.daSave = true;
              this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: "ຜິດຜາດ: " + response.data.message, }, 4000 );
              this.$Progress.fail();
            }
          })
          .catch((error) => {
            this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: "ຜິດຜາດ: " + error.message, }, 4000 );
          });
      });
    },
    GetPreOrder() {
      this.loading_check = true;
      this.$Progress.start();
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
        axios.get(`/api/preorder/edit/${this.PreOrderID}`)
          .then((response) => {
            if (response.data.success) {
              this.ListPreorder = response.data.pre_list_data;
              this.tranData.ListTran = JSON.parse( response.data.preorder_data[0].tran_price );

              this.transport_status = response.data.preorder_data[0].transport_status;
              this.TranDay = response.data.preorder_data[0].transport_day;
              this.supplierBack = response.data.preorder_data[0].supplier_id;
              this.DayOrder = response.data.preorder_data[0].created_at; 
              this.supplierBack = response.data.preorder_data[0].supplier_id;
              this.SupplierData.name = response.data.preorder_data[0].sup_name;
              this.SupplierData.tel = response.data.preorder_data[0].sup_tel;
              this.SupplierData.address = response.data.preorder_data[0].sup_address;
              this.SupplierData.images = window.location.origin+'/images/avatars/'+response.data.preorder_data[0].sup_images;


              this.CustomerData.CustomerSe =
                response.data.preorder_data[0].customer_type;
              this.CustomerData.Customer_id =
                response.data.preorder_data[0].customer_id;
              this.CustomerData.Customer_name =
                response.data.preorder_data[0].customer_name;
              this.CustomerData.Customer_tel =
                response.data.preorder_data[0].customer_tel;
              this.CustomerData.Customer_address =
                response.data.preorder_data[0].customer_address;
              if (response.data.preorder_data[0].pay_status == "payed") {
                this.PayStatus = true;
              } else {
                this.PayStatus = false;
              }
              //console.log(response.data.preorder_data[0]);
              this.loading_check = false;
              this.$Progress.finish();
            } else {
              this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: "ຜິດຜາດ: " + response.data.message, }, 4000 );
            }
          })
          .catch((error) => {
            this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: "ຜິດຜາດ: " + error.message, }, 4000 );
            this.$Progress.fail();
          });
      });
    },
  },
  created() {
    this.PreOrderID = this.$route.params.id;
    this.GetPreOrder();
    this.$axios.get(`/api/users/checkauth`).then((response) => {
      if (!response.data.isLogin) {
        window.location.href = "/";
      }
    });

    if (window.Laravel.isLoggedin) {
      this.isLoggedIn = true;
    }
  },
};
</script>

<style>
 
</style>
