<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 " aria-current="page">
                  ລາຍການສ້ອມແປງ
                </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>
           <!-- <a @click="CancelRepaire" class="btn btn-sm btn-danger btn-round btn-icon" > <span class="btn-inner--icon text-white" ><i class="fas fa-trash"></i ></span> </a> -->
          </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">ຟອມຮັບເຄື່ອງນຳລູກຄ້າ ({{ RepaireID }}<div v-if="!RepaireID" class="spinner-grow" style="width: 22px; height: 22px;" role="status"> <span class="sr-only">Loading...</span> </div>)</h3>
              </div>
              <div class="col-md-6 text-right">
                <a aria-current="page" href="javascript:void(0)" :class="chbtprint" @click="Print($event,RepaireID)" 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> ພິມ</span ></a >
                <a
                  aria-current="page"
                  href="javascript:void(0)"
                  :class="CheckForm"
                  @click="SaveRepaire('true')"
                  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"
                  @click="SaveRepaire()"
                  :class="CheckForm"
                  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>

          <!-- Light table -->
          <div class="card-body">
            <div class="row">
              <div class="col-lg-4 col-md-6">
                <div class="d-flex justify-content-between">
                        <label class="form-control-label" >ຮູບພາບອຸປະກອນ</label>
                        <a v-if="Customer.Images" class="btn btn-sm btn-danger btn-round btn-icon" @click="delImage" ><span class="btn-inner--icon text-white"><i class="fas fa-trash"></i> ລຶບຮູບ</span></a>
                    </div>
                <br />
                <div class="image mb-4">
                  <div class="row justify-content-center">
            
                          <a href="javascript:void(0)">
                            <img v-bind:src="imagePreview"
                              class=""
                              onclick="$('#simg').click()"
                              style="width: 220px; height: auto;"
                            />
                          </a>
                          <input type="file" id="simg" name="file" style="display:none;" @change="onSelected" accept="image/*">
                
                    
                    </div>
                    
                    <div class="text-center">
                      <div class="progress-wrapper" v-if="images.shupload">
                <div class="progress-info">
                  <div class="progress-label">
                    <span>ກຳລັງອັບໂຫຼດ</span>
                  </div>
                  <div class="progress-percentage">
                    <span>{{images.percenUp}}%</span>
                  </div>
                </div>
                <div class="progress">
                  <div class="progress-bar bg-primary" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" v-bind:style="{ width: images.percenUp + '%' }"></div>
                </div>
              </div>
                      <span class="text-red" v-if="images.upmax">ໄຟລ໌ທີ່ທ່ານອັບໂຫຼດມີຂະໜາດເກີນ 6 Mb</span>
                    </div>
                </div>
               
              </div>
              <div class="col-lg-4 col-md-6">
                <getcustomer :CustomerData="CustomerData" />
              
                
                <!-- <div class="row">
                  <div class="col-md-6">
                    <div class="custom-control custom-radio mb-3">
                      <input
                        name="customer-bills"
                        class="custom-control-input"
                        id="customRadio5"
                        value="true"
                        type="radio"
                        v-model="CustomerSe"
                      />
                      <label class="custom-control-label" for="customRadio5"
                        >ບຸກຄົນ</label
                      >
                    </div>
                    <div class="form-group">
                      <select
                        class="form-control"
                        v-on:change="onChangeCustomer($event)"
                        :disabled="CustomerSe === 'false'"
                      >
                        <option value="0">ລູກຄ້າທົ່ວໄປ</option>
                        <option
                          v-bind:value="customer.id"
                          :key="customer.id"
                          v-for="customer in CustomerList"
                        >
                          {{ customer.sex }} {{ customer.name }}
                          {{ customer.last_name }}
                        </option>
                      </select>
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="custom-control custom-radio mb-3">
                      <input
                        name="customer-bills"
                        class="custom-control-input"
                        id="customRadio6"
                        value="false"
                        type="radio"
                        v-model="CustomerSe"
                      />
                      <label class="custom-control-label" for="customRadio6"
                        >ລູກຄ້າສຳນັກງານ</label
                      >
                    </div>
                    <div class="form-group">
                      <select
                        class="form-control"
                        :disabled="CustomerSe === 'true'"
                        v-model="office_select"
                      >
                        <option value="0">ສຳນັກງານທົ່ວໄປ</option>
                        <option
                          v-bind:value="office.id"
                          :key="office.id"
                          v-for="office in OfficeList"
                        >
                          {{ office.office_name }}
                        </option>
                      </select>
                    </div>
                  </div>
                </div> -->
                <!-- <div class="other-customer" v-if="shform">
                  <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-user"></i
                        ></span>
                      </div>
                      <input
                        class="form-control"
                        placeholder="ຊື່ຂອງລູກຄ້າ/ຊື່ສຳນັກງານ"
                        type="text"
                        v-model="Customer.Name"
                      />
                    </div>
                  </div>
                  <div class="form-group">
                    <div class="input-group input-group-merge">
                      <div class="input-group-prepend">
                        <span class="input-group-text"
                          ><i class="ni ni-mobile-button"></i
                        ></span>
                      </div>
                      <input
                        class="form-control"
                        placeholder="ເບີໂທລະສັບ 020 XXXXXXXX"
                        type="text"
                        v-model="Customer.Tel"
                      />
                    </div>
                  </div>
                  <div class="input-group input-group-merge">
                    <div class="input-group-prepend">
                      <span class="input-group-text"
                        ><i class="ni ni-pin-3"></i
                      ></span>
                    </div>
                    <input
                      class="form-control"
                      placeholder="ທີ່ຢູ່ລູກຄ້າ..."
                      type="text"
                      v-model="Customer.Address"
                    />
                  </div>
                </div> -->

                <!-- <div v-else>
                  <span class="customer" v-if="CustomerSe === 'true'">
                    ເບີໂທ <i class="ni ni-mobile-button"></i>:
                    {{ Customer_data.tel }} <br />
                    ທີ່ຢູ່ <i class="ni ni-pin-3"></i>:
                    {{ Customer_data.address }} <br />
                  </span>
                  <span class="office" v-if="CustomerSe === 'false'">
                    <span v-for="off in OfficeList" :key="off.id">
                      <span v-if="off.id == office_select">
                        ເບີໂທ <i class="ni ni-mobile-button"></i>:
                        {{ off.office_tel }}<br />
                        ທີ່ຢູ່ <i class="ni ni-pin-3"></i>:
                        {{ off.office_address }}
                      </span>
                    </span>
                  </span>
                </div> -->
              </div>
              <div class="col-lg-4 col-md-12">
                <div class="form-group">
                  <label class="form-control-label">ປະເພດອຸປະກອນ</label>
                  <select class="form-control">
                    <option>ລູກຄ້າທົ່ວໄປ</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                  </select>
                </div>
                <label class="form-control-label"
                  >ລາຍລະອຽດຂອງ ອຸປະກອນເພີ່ມເຕີມ:</label
                >
                <QuillEditor
                  theme="snow"
                  style="height: 50px"
                  class="mb-5"
                  v-model:content="Customer.Detail"
                  contentType="html"
                />

                <label class="form-control-label">ອາການເປ່ເພເບື້ອງຕົ້ນ:</label>
                <QuillEditor
                  theme="snow"
                  style="height: 50px"
                  class="mb-5"
                  v-model:content="Customer.CauseDetail"
                  contentType="html"
                />
              </div>
            </div>
          </div>
        </div>
        <!-- Light table -->
      </div>
      <div class="col-xl-4">
        <div class="card">
          <div class="card-header border-0">
            <div class="row align-items-center">
              <div class="col">
                <h3 class="mb-0">ສະຖານະ ການສ້ອມແປງ</h3>
              </div>
              <div class="col text-right">
                <a
                  href="javascript:void(0)"
                  data-toggle="modal"
                  data-target="#mg_status"
                  class="btn btn-sm btn-primary"
                >
                  <i class="fas fa-edit"></i>
                </a>
              </div>
            </div>
          </div>
          <div class="table-responsive">
            <!-- Projects table -->
            <div class="card-body">
              <timeline :timeline="status" />
            </div>
          </div>
        </div>
      </div>

      <div class="col-xl-8">
        <div class="card">
          <div class="card-header d-flex justify-content-between">
            <span> ລາຍການສ້ອມແປງ/ສິນຄ້າ</span>
            <span>
                 <a aria-current="page" @click="cpBill()" :class="CheckListSer" 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 >
            </span>
           
          </div>
          <bailllist
                :ListBilldata="ListBilldata"
                ></bailllist>
        </div>
        
      </div>
    </div>

    
  </section>
  <div
      class="modal fade"
      id="mg_status"
      tabindex="-1"
      role="dialog"
      aria-labelledby="addNew"
      aria-hidden="true"
    >
      <div class="modal-dialog" 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">
            <div class="form-group">
              <label class="form-control-label">ລາຍການສະຖານະ</label>
              <select class="form-control" v-on:change="onChangeStatus($event)">
                <option value="">== ເລືອກສະຖານະ ==</option>
                <option
                  v-bind:value="item.id"
                  v-for="item in ListStatus"
                  :key="item.id"
                >
                  {{ item.data }}
                </option>
              </select>
            </div>

            <table class="table align-items-center table-flush table-striped">
              <thead class="thead-light">
                <tr>
                  <th>ສະຖານະ</th>
                  <th width="90">ລຶບອອກ</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="it in status" :key="it.index">
                  <td class="table-user">
                    <b v-for="nit in ListStatus" :key="nit.id">
                      <span v-if="it == nit.id">
                        {{ nit.data }}
                      </span>
                    </b>
                  </td>
                  <td class="table-actions">
                    <a
                      href="javascript:void(0)"
                      @click="removeStatus(it)"
                      class="table-action table-action-delete"
                      data-toggle="tooltip"
                      data-original-title="Delete product"
                    >
                      <i class="fas fa-trash"></i>
                    </a>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-dismiss="modal"
            >
              ປິດ
            </button>
          </div>
        </div>
      </div>
    </div>
</div>
</template>

<script>
//import timeline from './../../components/Timeline.vue'

import timeline from "../../components/Timeline.vue";

export default {
  name: "RepaireAdd",

  components: {
    timeline,
  },

  directives: {},

  data() {
    return {
      RepaireID: "",
      Customer: {
        EqTypeID: "1",
        Name: "",
        Tel: "",
        Address: "",
        Detail: "",
        CauseDetail: "",
        ListStatus: "",
        StatusNow: "",
        Images: "",
      },
      OfficeList: [],
      CustomerList: [],
      Customer_data: [],
      ItemRepaire: [],
      SeclectCustomer: "0",
      CustomerSe: "true",
      office_select: "0",
      status_created: true,
      status: ["a1"],
      ListStatus: [
        {
          id: "a1",
          data: "ຮັບເຄື່ອງແລ້ວ",
          icon: '<span class="badge badge-dot mr-1"><i class="bg-success"></i></span>',
        },
        {
          id: "a2",
          data: "ກຳລັງກວດເຊັກ",
          icon: '<span class="badge badge-dot mr-1"><i class="bg-info"></i></span>',
        },
        {
          id: "a3",
          data: "ແຈ້ງລາຄາສ້ອມແປງໃຫ້ລູກຄ້າ",
          icon: '<span class="badge badge-dot mr-1"><i class="bg-primary"></i></span>',
        },
        {
          id: "a4",
          data: "ລູກຄ້າຍືນຍັງສ້ອມແປງ",
          icon: '<span class="badge badge-dot mr-1"><i class="bg-success"></i></span>',
        },
        {
          id: "a5",
          data: "ກຳລັງສັ່ງອາໄຫລ໋ ສ້ອມແປງ",
          icon: '<span class="badge badge-dot mr-1"><i class="bg-warning"></i></span>',
        },
        {
          id: "a6",
          data: "ກຳລັງສັ້ອມແປງ",
          icon: '<span class="badge badge-dot mr-1"><i class="bg-warning"></i></span>',
        },
        {
          id: "a7",
          data: "ສ້ອມແປງສຳເລັດ",
          icon: '<span class="badge badge-dot mr-1"><i class="bg-success"></i></span>',
        },
        {
          id: "a8",
          data: "ສົ່ງຄືນບໍ່ສ້ອມແປງ",
          icon: '<span class="badge badge-dot mr-1"><i class="bg-warning"></i></span>',
        },
        {
          id: "a9",
          data: "ບໍ່ສາມາດສ້ອມແປງໄດ້",
          icon: '<span class="badge badge-dot mr-1"><i class="bg-warning"></i></span>',
        },
      ],
      Litem: {
        name: "",
        count: 1,
        credit: "",
        bill_type:"product",
        product_id:''
      },
      polling: null,
      ModalAdd: true,
      listUpdateId: "",
      cname: "",
      csex: "",
      ctel: "",
      caddress: "",
      btprint:false,
      images:{
        file:null,
        max_size: 6000*1204,
        upmax:false,
        percenUp:0,
        shupload:false
      },
      daSave:true,
      daBQ:false,
      isLoggedIn: false,
      // new update
      ListBilldata:[{
        QuoNumId:'',
        BillsId:'',
        ListItemBill:[],
        db_product:[],
        PayStatus:false,
        Sign:false,
        discount:0,
        tax:0,
        tax_set:10,
        tax_amount:null,
        AlltotalAmount:0,
        totalCount:0
        }],
        CustomerData:{
          Size:'S',
          Type:'',
          CustomerSe:'',
          Customer_id:'',
          Customer_name:'',
          Customer_tel:'',
          Customer_address:''
        }
    };
    
  },

  mounted() {
    //this.CustomerBill=true
  },
  computed: {
    CheckListSer(){
      if(this.ListBilldata[0].ListItemBill.length > 0){
          return ''
      } else {
          return 'disabled'
      }
    },
    imagePreview(){
      if(this.Customer.Images)
      {
        return window.location.origin+'/images/repaire/'+this.Customer.Images
      }
       else 
       { 
        return window.location.origin+'/images/add_img_bt.png'
        }
    },
    lastStatus() {
      // var item = this.ListStatus.find(i => i.id === this.status.slice(-1)[0]);
      // return item.data
      return this.status.slice(-1)[0];
    },
    totalAmount() {
      return this.ItemRepaire.reduce(
        (num, item) => num + item.credit * item.count,
        0
      );
    },
    totalCount() {
      return this.ItemRepaire.reduce((num, item) => num + item.count, 0);
    },

    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;
        }
      }
    },
    chbtprint(){
      if(this.btprint){ return '' } else { return "disabled" }
    },
    CheckForm() {
      if (this.CustomerSe == "true") {
        if (this.SeclectCustomer == "0") {
          if (this.Customer.EqTypeID != "") {
           // if (this.Customer.Name != "") {
              //if (this.Customer.Tel != "") {
               // if (
              //    this.Customer.Address != "" &&
              //    this.Customer.Address != "<p><br></p>"
              //  ) {
                  // if (
                  //   this.Customer.Detail != "" &&
                  //   this.Customer.Detail != "<p><br></p>"
                  // ) {
                    // if (
                    //   this.Customer.CauseDetail != "" &&
                    //   this.Customer.CauseDetail != "<p><br></p>"
                    // ) {
                      if(this.daSave){
                        return "";
                      } else {
                        return "disabled";
                      }
                      
                    // } else {
                    //   return "disabled";
                    // }
                  // } else {
                  //   return "disabled";
                  // }
                // } else {
                //   return "disabled";
                // }
             // } else {
             //   return "disabled";
            //  }
           // } else {
           //   return "disabled";
           // }
          } else {
            return "disabled";
          }
        } else {
          // if (
          //   this.Customer.Detail != "" &&
          //   this.Customer.Detail != "<p><br></p>"
          // ) {
          //   if (
          //     this.Customer.CauseDetail != "" &&
          //     this.Customer.CauseDetail != "<p><br></p>"
          //   ) {
              return "";
          //   } else {
          //     return "disabled";
          //   }
          // } else {
          //   return "disabled";
          // }
        }
      } else {
        if (this.office_select == "0") {
          if (this.Customer.EqTypeID != "") {
            // if (this.Customer.Name != "") {
              // if (this.Customer.Tel != "") {
                // if (
                //   this.Customer.Address != "" &&
                //   this.Customer.Address != "<p><br></p>"
                // ) {
                  // if (
                  //   this.Customer.Detail != "" &&
                  //   this.Customer.Detail != "<p><br></p>"
                  // ) {
                    // if (
                    //   this.Customer.CauseDetail != "" &&
                    //   this.Customer.CauseDetail != "<p><br></p>"
                    // ) {
                      if(this.daSave){
                        return "";
                      } else {
                        return "disabled";
                      }
                    // } else {
                    //   return "disabled";
                    // }
                  // } else {
                  //   return "disabled";
                  // }
                // } else {
                //   return "disabled";
                // }
              // } else {
              //   return "disabled";
              // }
            // } else {
            //   return "disabled";
            // }
          } else {
            return "disabled";
          }
        } else {
          // if (
          //   this.Customer.Detail != "" &&
          //   this.Customer.Detail != "<p><br></p>"
          // ) {
            // if (
            //   this.Customer.CauseDetail != "" &&
            //   this.Customer.CauseDetail != "<p><br></p>"
            // ) {
              return "";
            // } else {
            //   return "disabled";
            // }
          // } else {
          //   return "disabled";
          // }
        }
      }
    },
    printBQ(){
        if(this.daBQ){
          return '';
        } else {
          return 'disabled';
        }
    }
  },
  methods: {
    delImage(){
        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.post(`/api/repaire/deleteImage/${this.RepaireID}`,{
                    image: this.Customer.Images
                    })
                        .then(response => {
                            this.$Progress.finish()
                            this.Customer.Images = null
                           // this.$router.back();
                        })
                        .catch((error)=> {
                          this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
                           // console.error(error)
                            this.$Progress.fail()
                        });
                })
            }
            })
    },
     cpQuo(){
        if(this.QuotationID == null){
         /// console.log('Quo Null!')

       
            if(this.CustomerSe =='true'){
              if(this.customer_id == '0'){
                this.cname = this.Customer.Name
                this.ctel = this.Customer.Tel
                this.caddress = this.Customer.Address
              } else {
                this.cname = this.Customer_data.name +' '+ this.Customer_data.last_name
                this.csex = this.Customer_data.sex
                this.ctel = this.Customer_data.tel
                this.caddress = this.Customer_data.address
              }
            } else {
              if(this.customer_id == '0'){
                this.cname = this.Customer.Name
                this.ctel = this.Customer.Tel
                this.caddress = this.Customer.Address
              } else {
                var item = this.OfficeList.find(i => i.id === this.office_select);
                this.cname = item.office_name
                this.ctel = item.office_tel
                this.caddress = item.office_address
              }
            }

            this.$Progress.start();
          this.$axios.get("/sanctum/csrf-cookie").then((response) => {
            axios
              .post("/api/quotation/addQuo",{
              renum_id: this.RepaireID,
              customer_id: this.customer_id,
              office_id: this.office_select,
              customer_name: this.cname,
              customer_tel: this.ctel,
              customer_address: this.caddress,
              customer_detail: this.Customer_more_detail,
              user_id: window.Laravel.user.id,
              customer_type: this.CustomerSe,
              totalAmount: this.totalAmount,
              totalCount: this.totalCount,
            }).then((response) => {
                if (response.data.success) {
                  this.$Progress.finish();
                  this.$notify({ group: "sucess", title: "ສຳເລັດ!", text: " ຂໍ້ມູນໄດ້ຖຶກລຶບອອກແລ້ວ! " }, 2000)
                  // console.log(response.data.billnum_id)
                  this.QuotationID = response.data.quonum_id;
                  if(this.QuotationID){
                    window.open(window.location.origin+'/api/printquotation/'+this.QuotationID, "_blank");
                  }

                } else {
                  this.error = response.data.message;
                  console.error(error);
                  this.$Progress.fail();
                }
              })
              .catch( (error)=> {
                this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
                //console.error(error);
              });
          });
        }else {
          window.open(window.location.origin+'/api/printquotation/'+this.QuotationID, "_blank");
        }
    },
    cpBill(){
        if(this.BillID == null){
          console.log('Bill Null!')

           if(this.CustomerSe =='true'){
            if(this.customer_id == '0'){
              this.cname = this.Customer.Name
              this.ctel = this.Customer.Tel
              this.caddress = this.Customer.Address
            } else {
              this.cname = this.Customer_data.name +' '+ this.Customer_data.last_name
              this.csex = this.Customer_data.sex
              this.ctel = this.Customer_data.tel
              this.caddress = this.Customer_data.address
            }
          } else {
            if(this.customer_id == '0'){
              this.cname = this.Customer.Name
              this.ctel = this.Customer.Tel
              this.caddress = this.Customer.Address
            } else {
              var item = this.OfficeList.find(i => i.id === this.office_select);
              this.cname = item.office_name
              this.ctel = item.office_tel
              this.caddress = item.office_address
            }
          }

           this.$Progress.start();
        this.$axios.get("/sanctum/csrf-cookie").then((response) => {
          axios
            .post("/api/bills/addbillRe",{
            renum_id: this.RepaireID,
            customer_id: this.customer_id,
            office_id: this.office_select,
            customer_name: this.cname,
            customer_tel: this.ctel,
            customer_address: this.caddress,
            customer_detail: this.Customer_more_detail,
            user_id: window.Laravel.user.id,
            customer_type: this.CustomerSe,
            totalAmount:this.ListBilldata[0].AlltotalAmount,
            totalCount:this.ListBilldata[0].totalCount,
            status: this.ListBilldata[0].PayStatus,
            signed: 'true',
            trn_type:'cincome',
            discount: this.ListBilldata[0].discount,
            list_bill:this.ListBilldata[0].ListItemBill,
            ListBilldata:this.ListBilldata,
            tax:this.ListBilldata[0].tax,
            tax_amount: this.ListBilldata[0].tax_amount,
          }).then((response) => {
              if (response.data.success) {
                this.$Progress.finish();
                // console.log(response.data.billnum_id)
                this.BillID = response.data.billnum_id;
                if(this.BillID){
                  window.open(window.location.origin+'/api/printbill/'+this.BillID, "_blank");
                }
                this.$notify({ group: "sucess", title: "ສຳເລັດ!", text: " ຂໍ້ມູນໄດ້ຖຶກລຶບອອກແລ້ວ! " }, 2000)


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

        } else {
           /// update bill 
          if(this.CustomerSe =='true'){
            if(this.customer_id == '0'){
              this.cname = this.Customer.Name
              this.ctel = this.Customer.Tel
              this.caddress = this.Customer.Address
            } else {
              this.cname = this.Customer_data.name +' '+ this.Customer_data.last_name
              this.csex = this.Customer_data.sex
              this.ctel = this.Customer_data.tel
              this.caddress = this.Customer_data.address
            }
          } else {
            if(this.customer_id == '0'){
              this.cname = this.Customer.Name
              this.ctel = this.Customer.Tel
              this.caddress = this.Customer.Address
            } else {
              var item = this.OfficeList.find(i => i.id === this.office_select);
              this.cname = item.office_name
              this.ctel = item.office_tel
              this.caddress = item.office_address
            }
          }

           this.$Progress.start();
        this.$axios.get("/sanctum/csrf-cookie").then((response) => {
          axios
            .post("/api/bills/addbillRe",{
            renum_id: this.RepaireID,
            customer_id: this.customer_id,
            office_id: this.office_select,
            customer_name: this.cname,
            customer_tel: this.ctel,
            customer_address: this.caddress,
            customer_detail: this.Customer_more_detail,
            user_id: window.Laravel.user.id,
            customer_type: this.CustomerSe,
            totalAmount:this.ListBilldata[0].AlltotalAmount,
            totalCount:this.ListBilldata[0].totalCount,
            status: this.ListBilldata[0].PayStatus,
            signed:'true',
            billUpdate: 'true',
            billID: this.BillID,
            discount: this.ListBilldata[0].discount,
            list_bill:this.ListBilldata[0].ListItemBill,
            ListBilldata:this.ListBilldata,
            tax:this.ListBilldata[0].tax,
            tax_amount: this.ListBilldata[0].tax_amount,
          }).then((response) => {
              if (response.data.success) {
                this.$Progress.finish();
                // console.log(response.data.billnum_id)
                this.BillID = response.data.billnum_id;
                if(this.BillID){
                  window.open(window.location.origin+'/api/printbill/'+this.BillID, "_blank");
                }

            //      this.$swal.fire({
            //   position: "top-end",
            //   icon: "success",
            //   title: "ບັນທຶກຂໍ້ມູນສຳເລັດ!",
            //   showConfirmButton: false,
            //   timer: 1500,
            // });

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

        });
         // window.open(window.location.origin+'/api/printbill/'+this.BillID, "_blank");
        }
    },
     onSelected(event){
      this.images.file = event.target.files[0]
        let reader  = new FileReader();
              reader.addEventListener("load", function () {
                  this.imagePreview = reader.result;
                }.bind(this), false);
                if( this.images.file ){
                  if ( /\.(jpe?g|png|gif)$/i.test( this.images.file.name ) ) {
                   // console.log(this.images.file.size+' | '+this.images.max_size)
                    if(this.images.file.size>this.images.max_size){
                      this.images.upmax = true
                    } else {
                      this.UploadImg()
                      this.images.upmax = false
                      reader.readAsDataURL( this.images.file );
                    }
                  } 
                }
    },
    UploadImg(){
      this.images.shupload = true
      let formData = new FormData();
      formData.append("file", this.images.file);
       // console.log(formData)
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
          axios.post("/api/img/upload_img_repaire", formData, {
            headers: {"Content-Type": "multipart/form-data"},
            onUploadProgress: progressEvent => {
              this.images.percenUp = Math.round(progressEvent.loaded / progressEvent.total * 100)
              if(this.images.percenUp==100){ this.images.shupload = false; this.images.percenUp=0 }
             // console.log('Upload Progress:' + Math.round(progressEvent.loaded / progressEvent.total * 100) + '%')
            }
          }).then((response)=> {
              //console.log(response.data.images)
              this.Customer.Images = response.data.images

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

         });

    },
    Print(e,id){
      window.open(window.location.origin+'/api/rece/'+id, "_blank");
    },
    CancelRepaire() {
      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/repaire/delete/${this.RepaireID}`)
                .then((response) => {
                  this.$Progress.finish();
                  this.$router.back();
                })
                .catch( (error)=> {
                this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
                  //console.error(error);
                  this.$Progress.fail();
                });
            });
          }
        });
    },
    fnFocus() {
      this.Litem.name = "";
      this.Litem.count = 1;
      this.Litem.credit = "";
      this.polling = setInterval(() => {
        this.$refs.foc_name.focus();
        clearInterval(this.polling);
      }, 900);
    },
    onChangeStatus(e) {
      var id = e.target.value;
      if (!this.status.includes(id)) {
        this.status.push(id);
      }
    },
    removeStatus(e) {
      // console.log(e)
      this.status.splice(this.status.indexOf(e), 1);
    },
    onChangeCustomer(e) {
      var id = e.target.value;
      //this.customers.office = id;
      if (id != "0") {
        this.GetOneCustomer(id);
      } else {
        this.Customer_data = [];
      }

      this.SeclectCustomer = id;
    },
    GetListCustomer() {
      this.$Progress.start();
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
        axios
          .get(`/api/customer/billlist`)
          .then((response) => {
            this.$Progress.finish();
            this.CustomerList = response.data;
            //console.log(response.data)
          })
          .catch((error) => {
            this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
       //console.error(error);
            this.$Progress.fail();
          });
      });
    },
    GetListOffice() {
      this.$Progress.start();
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
        axios
          .get(`/api/customeroffice`)
          .then((response) => {
            this.OfficeList = response.data;
            // console.log(response.data)
          })
          .catch((error) => {
            this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
            //console.error(error);
            this.$Progress.fail();
          });
      });
    },
    GetOneCustomer(id) {
      this.$Progress.start();
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
        this.$axios
          .get(`/api/customer/edit/${id}`)
          .then((response) => {
            this.Customer_data = response.data;

            //console.log(response.data)
            this.$Progress.finish();
          })
          .catch((error)=> {
            this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
           // console.error(error);
            this.$Progress.fail();
          });
      });
    },
    CreatedRepaire() {
      // console.log(this.status_created)
      if (this.status_created) {
        this.$Progress.start();
        this.$axios.get("/sanctum/csrf-cookie").then((response) => {
          axios
            .post("/api/repaire/add")
            .then((response) => {
              if (response.data.success) {
                this.$Progress.finish();

                this.RepaireID = response.data.renum_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)
             // console.error(error);
            });
        });
      }
    },
    SaveRepaire(print) {
      this.daSave = false


      this.$Progress.start();
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
        axios
          .post(`/api/repaire/update/${this.RepaireID}`, {
            customer_id: this.CustomerData.Customer_id,  //ok
            user_id: window.Laravel.user.id, //ok
            equiment_type_id: "1",
            detail: this.Customer.Detail,
            images: this.Customer.Images,
            cause_detail: this.Customer.CauseDetail,
            customer_name: this.CustomerData.Customer_name,                //ok
           // customer_sex: this.csex,
            customer_tel: this.CustomerData.Customer_tel,                  //ok
            customer_address: this.CustomerData.Customer_address,          //ok
            customer_type: this.CustomerData.CustomerSe,           //ok
            other_customer: "",
            all_price: this.ListBilldata[0].AlltotalAmount,
            list_status: this.status,
            status_now: this.lastStatus,
            ListBilldata:this.ListBilldata,
            list_repaire:this.ListBilldata[0].ListItemBill,
          }).then((response) => {
            if (response.data.success) {
              this.daSave = true
              this.daBQ = true
              this.$Progress.finish();
              this.btprint = true
              if(print){
                window.open(window.location.origin+'/api/rece/'+this.RepaireID, "_blank");
              }

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

              
            } 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)
        //console.error(error);
          });
      });
    },

   
    formatPrice(value) {
      let val = (value / 1).toFixed(0).replace(".", ",");
      return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
  },
  created() {
    this.$axios.get(`/api/users/checkauth`).then((response) => {
      if (!response.data.isLogin) {
        window.location.href = "/";
      }
    });

    this.CreatedRepaire();
    this.GetListCustomer();
    this.GetListOffice();
    if(window.Laravel.isLoggedin){
           this.isLoggedIn = true
        }

  },

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

<style lang="scss" scoped>
.table td, .table th {
    padding: 8px;
}
</style>
