var VPRekapAbsensi = (function () {
    let gridConf = {
        ready: false,
        data: [],
        id: "absensi-table",
        ref: "absensi-table",
        columns: [{ id: 'fullname', name: 'fullname' },
        {
            id: 'cam', name: 'Dibuat Pada', formatter: (_, row) => {
                if (!row.cells[1].data.isValid()) return '';
                if (row.cells[1].data.format("YYYY-MM-DD") == mm().format("YYYY-MM-DD")) {
                    return row.cells[1].data.format("HH:mm")
                } else if (row.cells[1].data.format("YYYY") == mm().format("YYYY")) {
                    return row.cells[1].data.format("DD MMMM HH:mm")
                }
                return row.cells[1].data.format("YYYY-MM-DD HH:mm")
            }
        },
        {
            name: 'Waktu',
            formatter: (_, row) => {
                let btn = `<div class="${row.cells[11].data ? 'd-flex' : ''}">`;
                if (row.cells[11].data) {
                    btn += `
                    <div class="input-style-1">
                        <label>Masuk</label>
                        <input style="min-width: 90px;" id="attendanceTimeIn" data-date="${row.cells[1].data.format("YYYY-MM-DD")}" data-ni="${row.cells[0].data}" data-nama="${row.cells[1].data}" data-id="${row.cells[3].data}" value="${row.cells[7].data ? row.cells[7].data.format("HH:mm") : ''}" placeholder="07:00">
                    </div>
                    `;
                } else btn += `<div>Masuk : ${row.cells[7].data ? row.cells[7].data.format("HH:mm") : '-'}</div>`;
                btn += "&nbsp;";
                if (row.cells[11].data) {
                    btn += `
                <div class="input-style-1">
                    <label>Keluar</label>
                    <input style="min-width: 90px;" id="attendanceTimeOut" data-date="${row.cells[1].data.format("YYYY-MM-DD")}" data-ni="${row.cells[0].data}" data-nama="${row.cells[1].data}" data-id="${row.cells[3].data}" value="${row.cells[8].data ? row.cells[8].data.format("HH:mm") : ''}" placeholder="17:00">
                </div>
                `;
                } else btn += `<div>Keluar : ${row.cells[8].data ? row.cells[8].data.format("HH:mm") : '-'}</div>`;
                btn += "</div>";
                btn += `<div class="d-flex">`;
                if (row.cells[9].data) {
                    btn += `<div class="text-center" style="min-width: 90px;"><small>${row.cells[9].data}°C</small></div>`;
                }
                if (row.cells[10].data) {
                    btn += `<div class="text-center" style="min-width: 90px;"><small>${row.cells[10].data}°C</small></div>`;
                }
                btn += `</div>`;
                return gridjs.html(btn);
            }
        },
        {
            id: 'id',
            name: 'Aksi',
            formatter: (_, row) => {
                let btn = `<div class="d-flex">`;
                btn += `
                <div class="select-style-1 m-0">
                    <div class="select-position">
                        <select id="status-absen" style="width: 90px;" data-ni="${row.cells[0].data}" data-nama="${row.cells[1].data}" data-id="${row.cells[3].data}" value="${row.cells[4].data}">
                            <option ${row.cells[4].data == '1' ? 'selected' : ''} value="1">Hadir</option>
                            <option ${row.cells[4].data == '2' ? 'selected' : ''} value="2">Alpa</option>
                            <option ${row.cells[4].data == '3' ? 'selected' : ''} value="3">Sakit</option>
                            <option ${row.cells[4].data == '4' ? 'selected' : ''} value="4">Izin</option>
                        </select>
                    </div>
                </div>`;
                if (row.cells[5].data && row.cells[4].data == 1) {
                    btn += `&nbsp;<button class="btn btn-primary location-presence" title="Lokasi Masuk" data-link="${row.cells[5].data}"><i class="fas fa-globe-asia"></i></button>`;
                }
                if (row.cells[6].data && row.cells[4].data == 1) {
                    btn += `&nbsp;<button class="btn btn-success location-presence" title="Lokasi Keluar" data-link="${row.cells[6].data}"><i class="fas fa-globe-asia"></i></button>`;
                }
                btn += "</div>";
                return gridjs.html(btn);
            }
        },
        { id: 'status_presence', hidden: true },
        { id: 'google_map_in', hidden: true },
        { id: 'google_map_out', hidden: true },
        { id: 'tim', hidden: true },
        { id: 'tom', hidden: true },
        { id: 'suhuIn', hidden: true },
        { id: 'suhuOut', hidden: true },
        { id: 'allow_edit', hidden: true },
        ]
    };
    let vp_template = `
    <div class="card-style">
        <div class="row">
            <div class="col-md-6 text-center">
                <label for="filter-status">Status</label>
                <select class="form-control text-center my-2" id="filter-status" v-model="filter.status">
                    <option value="all">Semua</option>
                    <option value="1">Hadir</option>
                    <option value="2">Alpa</option>
                    <option value="3">Sakit</option>
                    <option value="4">Izin</option>
                </select>
            </div>
            <div class="col-md-6 text-center">
                <label for="filter-karyawan" class="mb-2">Karyawan</label>
                <tomselect id="filter-karyawan" :options="karyawan.data" :value="karyawan_id" @changed="karyawan_id=$event" placeholder="Pilih Karyawan" :multiple="true" eltype="select" style="width: 100%;">
                </tomselect>
            </div>
            <div class="col-12 text-center">
                <label for="daterange">Waktu</label>
                <input type="text" class="form-control text-center my-2" id="filter-date" ref="filter-date" name="filter-date"  />
            </div>
        </div> 
        <div style="text-align:right">
        
            &nbsp;
            <a class="main-btn btn-sm success-btn rounded-md btn-hover" :href="filteredUrl.replace('all','export')" >
                <i class="fas fa-file-excel"></i>
            </a>
            &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="filteredUrl" :ref="grid.ref" :columns="grid.columns"
                :ondataload="ondataload"></grid>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" ref="modalLocation" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-fullscreen modal-dialog-centered">
          <div class="modal-content card-style">
            <div class="modal-header px-0 border-0">
              <h5 class="text-bold">Lokasi</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 h-100 w-100">
                <iframe id="iframe-map" src="" title="Lokasi Presensi" class="w-100 h-100"></iframe>
              </div>
            </div>
          </div>
        </div>
    </div>
    `;
    return {
        template: vp_template,
        name: "rekap-absensi",
        data() {
            return {
                grid: gridConf,
                year: (new Date()).getFullYear(),
                month: (new Date()).getMonth() + 1,
                today: true,
                filter: {
                    status: 'all',
                    startDate: moment().format('YYYY-MM-DD'),
                    endDate: moment().format('YYYY-MM-DD')
                },
                karyawan: {
                    value: [],
                    data: []
                },
            }
        },
        mounted() {
            this.eventListener();
            this.loadKaryawan();
        },
        watch: {
            today(v) {
                if (v) {
                    this.year = (new Date()).getFullYear();
                    this.month = (new Date()).getMonth() + 1;
                }
            },
            month(v) {
                if (v != (new Date()).getMonth() + 1) this.today = false;
            },
            year(v) {
                if (v != (new Date()).getFullYear()) this.today = false;
            }
        },
        computed: {
            filterDate() {
                return `${this.filter.startDate}-${this.filter.endDate}`
            },
            filteredUrl() {
                let url = `${window.location.href}/all?`;
                url += `&startDate=${this.filter.startDate}`;
                url += `&endDate=${this.filter.endDate}`;
                url += `&status=${this.filter.status}`;
                url += `&karyawan=${this.karyawan_id}`;
                return url;
            },
            karyawan_id: {
                get() {
                    return this.karyawan.value.join(',');
                }, set(v) {
                    this.karyawan.value = v.map(v => v);
                }
            }
        },
        methods: {
            eventListener() {
                $('input[name="filter-date"]').daterangepicker({
                    startDate: moment(this.filter.startDate).format('DD/MM/YYYY'),
                    endDate: moment(this.filter.endDate).format('DD/MM/YYYY'),
                    locale: {
                        format: 'DD/MM/YYYY'
                    },
                    ranges: {
                        'Today': [moment(), moment()],
                        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                        'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                        'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                        'This Month': [moment().startOf('month'), moment().endOf('month')],
                        'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                    },
                    opens: 'left'
                }, (start, end, label) => {
                    this.filter.startDate = start.format('YYYY-MM-DD');
                    this.filter.endDate = end.format('YYYY-MM-DD');
                });
                document.addEventListener('click', (e) => {
                    if (e.target.classList.contains('location-presence')) {
                        this.showLocation(e.target.dataset.link);
                    }
                });
                document.addEventListener('change', (e) => {
                    if (e.target.id == "status-absen") {
                        this.save(e.target.dataset.id, {
                            status: e.target.value,
                            nama: e.target.dataset.nama,
                            nomor_induk: e.target.dataset.ni
                        })
                    }
                    if (e.target.id == "attendanceTimeIn" || e.target.id == "attendanceTimeOut") {
                        let data = {
                            status: document.querySelector(`[id='status-absen'][data-id='${e.target.dataset.id}']`).value,
                            nama: e.target.dataset.nama,
                            nomor_induk: e.target.dataset.ni
                        }
                        if (e.target.id == "attendanceTimeIn") data.timeIn = e.target.value ? moment(`${e.target.dataset.date} ${e.target.value}`).unix() : 'null';
                        if (e.target.id == "attendanceTimeOut") data.timeOut = e.target.value ? moment(`${e.target.dataset.date} ${e.target.value}`).unix() : 'null';
                        this.save(e.target.dataset.id, data)
                    }
                })
            },
            showLocation(link) {
                console.log(link)
                document.getElementById('iframe-map').src = link;
                this.modalLocation();
            },
            loadKaryawan() {
                axios({
                    method: 'get',
                    url: this.$store.state.config.base_url + `/panel/users/staff/all?role=karyawan`
                }).then((response) => {
                    if (!isObject(response.data)) return Swal.fire('Error', gaem({ response }, response.data), 'error');
                    this.karyawan.data = response.data.data.map((v, i) => {
                        return { value: v.id, text: v.fullname };
                    });

                }, (error) => {
                    Swal.fire('Gagal', gaem(error, 'Gagal Mengambil Data Karyawan'), 'error')
                });
            },
            save(id, datas) {
                let data = {
                    [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value,
                    status: datas.status,
                }
                if (typeof datas.timeIn != 'undefined') data.timeIn = datas.timeIn;
                if (typeof datas.timeOut != 'undefined') data.timeOut = datas.timeOut;

                axios({
                    method: 'post',
                    data,
                    url: `${window.location.href}/` + id
                }).then((response) => {
                }, (error) => {
                    let text = `Gagal Mengubah Data ${datas.nama} \n` + gaem(error, '');
                    Swal.fire('Gagal', text, 'error')
                });
            },
            ondataload(data) {
                this.grid.data = data.absensi.map(v => {
                    v.allow_edit = data.allow_edit;
                    v.cam = mm({ unix: v.created_at });
                    v.tim = v.timeIn ? mm({ unix: v.timeIn }) : null;
                    v.tom = v.timeOut ? mm({ unix: v.timeOut }) : null;
                    return v;
                });
                this.grid.ready = true;
                return data.absensi;
            },
            modalLocation(e = 'show') {
                if (!this.locationModal) {
                    this.locationModal = new bootstrap.Modal(this.$refs.modalLocation);
                }
                switch (e) {
                    case "hide":
                        this.locationModal.hide();
                        break;
                    case "show":
                        this.locationModal.show();
                        break;
                    case "toggle":
                        this.locationModal.toggle();
                        break;
                    case "dispose":
                        this.locationModal.dispose();
                        break;
                }
            },
        },
    }
})();
