var VPWADevice = (function () {
    let vp_template = `
    <div class="card-style">
          <div style="text-align:right">
            <button title="Filter" class="main-btn btn-sm primary-btn rounded-md btn-hover" data-bs-toggle="modal" data-bs-target="#modal-filter">
                <i class="fas fa-filter"></i>
            </button>
            &nbsp;
            <button  class="main-btn btn-sm primary-btn rounded-md btn-hover" data-bs-toggle="modal" data-bs-target="#modal-common">
                <i class="lni lni-plus"></i>
            </button>
            &nbsp;
            <button class="main-btn btn-sm success-btn rounded-md btn-hover" @click="$refs[grid.ref].reload()" >
                <i class="lni lni-reload"></i>
            </button>
          </div>
  
          <div class="table-responsive">
           <grid :id="grid.id" :limits="true" :url="parsedURL" :ref="grid.ref" :columns="grid.columns" :ondataload="ondataload"></grid>
          </div>
      </div>



      <div class="modal fade" id="modal-filter" :ref="mdl.filter.ref" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-lg modal-dialog-centered">
          <div class="modal-content card-style">
              <div class="modal-header px-0 border-0">
                  <h5 class="text-bold">Filter</h5>
                  <button class="border-0 bg-transparent h1" data-bs-dismiss="modal">
                      <i class="lni lni-cross-circle"></i>
                  </button>
              </div>
              <div class="modal-body px-0">
                  <div class="content">

                    <div class="select-style-1">
                        <label>Status</label>
                        <div class="select-position">
                        <select required v-model="mdl.filter.status">
                            <option value="all">Semua</option>
                            <option value="1">Aktif</option>
                            <option value="0">Tidak Aktif</option>
                        </select>
                        </div>
                    </div>
                    <div class="select-style-1">
                        <label>Koneksi</label>
                        <div class="select-position">
                        <select required v-model="mdl.filter.is_connected">
                            <option value="all">Semua</option>
                            <option value="1">Terkoneksi</option>
                            <option value="0">Terputus</option>
                        </select>
                        </div>
                    </div>
                    <div class="select-style-1">
                        <label>Utama</label>
                        <div class="select-position">
                        <select required v-model="mdl.filter.is_default">
                            <option value="all">Semua</option>
                            <option value="1">Utama</option>
                            <option value="0">Bukan Utama</option>
                        </select>
                        </div>
                    </div>

                  </div>
              </div>
          </div>
      </div>
  </div>

  <div class="modal fade" id="modal-common" :ref="mdl.common.ref" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content card-style">
                <div class="modal-header px-0 border-0">
                    <h5 class="text-bold">{{mdl.common.id?'Ubah':'Tambah'}}</h5>
                    <button class="border-0 bg-transparent h1" data-bs-dismiss="modal">
                        <i class="lni lni-cross-circle"></i>
                    </button>
                </div>
                <div class="modal-body px-0">
                    <div class="content">
                        <form @submit.prevent="mdl.common.id?ubah():tambah()">
                            <div class="input-style-1">
                                <label>ID Perangkat</label>
                                <input required :disabled="mdl.common.id" v-model="mdl.common.device_id" type="text" class="form-control" placeholder="ID Perangkat">
                            </div>
                            <div class="input-style-1">
                                <label>Nama Perangkat</label>
                                <input v-model="mdl.common.nama" type="text" class="form-control" placeholder="Nama Perangkat">
                            </div>
                            <div class="row">
                                <div class="col-6">
                                    <div class="select-style-1">
                                        <label>Status</label>
                                        <div class="select-position">
                                        <select required v-model="mdl.common.status">
                                            <option value="1">Aktif</option>
                                            <option value="0">Tidak Aktif</option>
                                        </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="py-5 px-4">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" v-model="mdl.common.is_default" type="checkbox" >
                                            <label @click="mdl.common.is_default=!mdl.common.is_default" class="form-check-label">Nomor Utama</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer px-0">
                                <button type="submit" class="main-btn btn-sm success-btn btn-hover">
                                    <template v-if="mdl.common.id"> 
                                        Simpan
                                    </template>
                                    <template v-else>
                                        Tambah
                                    </template>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
  
`
    let gridConf = {
        ready: false,
        data: [],
        id: "device-table",
        ref: "device-table",
        columns: [

            {
                id: 'device_id',
                name: "ID Perangkat"
            }, {
                id: 'nama',
                name: "Nama Perangkat"
            }, {
                id: 'nomor',
                name: "Nomor Whatsapp"
            },
            {
                id: 'status',
                name: 'Status',
                formatter: (_, row) => {
                    let state = row.cells[3].data == '1';
                    let is_default = row.cells[5].data == '1';
                    let is_connected = row.cells[6].data == '1';
                    let k = "<div class='d-flex'>";
                    k += `&nbsp;<span class="badge bg-${state ? 'success' : 'danger'}">${state ? 'Aktif' : 'Tidak Aktif'}</span>`;
                    k += `&nbsp;<span class="badge bg-${is_default ? 'success' : 'danger'}">${is_default ? 'Utama' : 'Bukan Utama'}</span>`;
                    k += `&nbsp;<span class="badge bg-${is_connected ? 'success' : 'danger'}">${is_connected ? 'Terkoneksi' : 'Terputus'}</span>`;
                    k += '</div>';
                    return gridjs.html(k);
                }
            },
            {
                id: 'id',
                name: 'Aksi',
                formatter: (_, row) => {
                    let btn = "";
                    btn += "<div class='d-flex'>";
                    btn += `<button class="btn btn-primary rounded-md" id="trigger-edit" data-id="${row.cells[4].data}"><i id="trigger-edit" data-id="${row.cells[4].data}" class='lni lni-pencil-alt'></i></button>`;
                    btn += `&nbsp;<button class="btn btn-danger rounded-md" id="trigger-delete" data-id="${row.cells[4].data}"><i id="trigger-delete" data-id="${row.cells[4].data}" class='lni lni-trash-can'></i></button>`;
                    btn += "</div>";
                    return gridjs.html(btn);
                }
            },
            {
                id: "is_default",
                hidden: true
            },
            {
                id: "is_connected",
                hidden: true
            },
        ]
    };

    return {
        name: "wadevice",
        template: vp_template,

        data() {
            return {
                grid: gridConf,
                mdl: {
                    filter: {
                        ref: "filter-modal",
                        status: 'all',
                        is_default: 'all',
                        is_connected: 'all',
                    },
                    common: {
                        id: null,
                        device_id: '',
                        ref: "common-modal",
                        is_default: false,
                        nama: '',
                        status: '1',
                    }
                }
            }
        },
        mounted() {
            this.eventListener();
        },
        methods: {
            eventListener() {
                document.addEventListener('click', (e) => {
                    if (e.target && e.target.id == 'trigger-edit') {
                        this.rincian(e.target.dataset.id)
                    }
                    if (e.target && e.target.id == 'trigger-delete') {
                        this.hapus(e.target.dataset.id)
                    }
                });
                this.$refs[this.mdl.common.ref].addEventListener('hide.bs.modal', (e) => {
                    this.mdl.common.id = null
                })
            },
            ubah() {
                let data = {
                    [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                    is_default: this.mdl.common.is_default ? '1' : '0',
                    nama: this.mdl.common.nama,
                    status: this.mdl.common.status,
                };
                showDismisableLoading();
                axios({
                    method: 'PUT',
                    data: data,
                    url: this.$store.state.config.base_url + "/panel/whatsapp/devices/" + this.mdl.common.id,
                }).then((response) => {
                    Swal.close()
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    Swal.fire('Berhasil', response.data.message, 'success');
                    this.$refs[this.grid.ref].reload()
                    this.CommonModal('hide');
                }, (error) => {
                    Swal.close()
                    if (typeof error.response == 'undefined') return;
                    let errMsg = gaem(error);
                    return Swal.fire('Gagal', errMsg, 'error')
                });
            },
            rincian(id) {
                showDismisableLoading();
                axios({
                    method: 'GET',
                    url: this.$store.state.config.base_url + "/panel/whatsapp/devices/" + id,
                }).then((response) => {
                    Swal.close()
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.mdl.common.id = id;
                    this.mdl.common.device_id = response.data.device_id;
                    this.mdl.common.nama = response.data.nama;
                    this.mdl.common.is_default = response.data.is_default;
                    this.mdl.common.status = response.data.status;
                    this.CommonModal('show');
                }, (error) => {
                    this.mdl.common.id = null;
                    Swal.close()
                    if (typeof error.response == 'undefined') return;
                    let errMsg = gaem(error);
                    return Swal.fire('Gagal', errMsg, 'error')
                });
            },
            hapus(id) {
                showDismisableLoading();
                axios({
                    method: 'DELETE',
                    data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, },
                    url: this.$store.state.config.base_url + "/panel/whatsapp/devices/" + id,
                }).then((response) => {
                    Swal.close()
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.$refs[this.grid.ref].reload()
                    return Swal.fire('Success', response.data.message, 'success');
                }, (error) => {
                    Swal.close()
                    if (typeof error.response == 'undefined') return;
                    let errMsg = gaem(error);
                    return Swal.fire('Gagal', errMsg, 'error')
                });
            },
            tambah() {
                let data = {
                    [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                    device_id: this.mdl.common.device_id,
                    is_default: this.mdl.common.is_default ? '1' : '0',
                    nama: this.mdl.common.nama,
                    status: this.mdl.common.status,
                };
                showDismisableLoading();
                axios({
                    method: 'POST',
                    data: data,
                    url: this.$store.state.config.base_url + "/panel/whatsapp/devices",
                }).then((response) => {
                    Swal.close()
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    Swal.fire('Berhasil', response.data.message, 'success');
                    this.$refs[this.grid.ref].reload()
                    this.CommonModal('hide');
                }, (error) => {
                    Swal.close()
                    if (typeof error.response == 'undefined') return;
                    let errMsg = gaem(error);
                    return Swal.fire('Gagal', errMsg, 'error')
                });
            },
            ondataload(data) {
                this.grid.data = data.data;
                this.grid.ready = true;
                return data.data;
            },
            FilterModal(e = 'show') {
                if (!this.mdl.filter.instance) {
                    this.mdl.filter.instance = new bootstrap.Modal(this.$refs[this.mdl.filter.ref]);
                }
                switch (e) {
                    case "hide":
                        this.mdl.filter.instance.hide();
                        break;
                    case "show":
                        this.mdl.filter.instance.show();
                        break;
                    case "toggle":
                        this.mdl.filter.instance.toggle();
                        break;
                    case "dispose":
                        this.mdl.filter.instance.dispose();
                        break;
                }
            },
            CommonModal(e = 'show') {
                if (!this.mdl.common.instance) {
                    this.mdl.common.instance = new bootstrap.Modal(this.$refs[this.mdl.common.ref]);
                }
                switch (e) {
                    case "hide":
                        this.mdl.common.instance.hide();
                        break;
                    case "show":
                        this.mdl.common.instance.show();
                        break;
                    case "toggle":
                        this.mdl.common.instance.toggle();
                        break;
                    case "dispose":
                        this.mdl.common.instance.dispose();
                        break;
                }
            }
        },
        computed: {
            parsedURL() {
                let url = window.location.href + '/all?';
                url += `&status=${this.mdl.filter.status}`;
                url += `&is_connected=${this.mdl.filter.is_connected}`;
                url += `&is_default=${this.mdl.filter.is_default}`;
                return url;
            },
        }
    }
})();
