<!-- Rekapitulasi Gangguan/Jenis Gangguan SE 004 -->

<template>
  <Filters
    @reset-form="data = []"
    :report-button="true"
    @run-search="() => filterData(filters)"
    class="mb-4"
  >
    <Type1 @update:filters="(value) => (filters = value)" />
  </Filters>

  <div id="data">
    <DxDataGrid
      ref="dataGridRef"
      :allow-column-reordering="true"
      class="max-h-[calc(100vh-140px)] mb-10"
      :data-source="data"
      :show-column-lines="true"
      :show-row-lines="false"
      :show-borders="true"
      :row-alternation-enabled="true"
      :hover-state-enabled="true"
      @selection-changed="onDataSelectionChanged"
      :column-width="100"
      @exporting="onExporting"
      :allow-column-resizing="true"
      column-resizing-mode="widget"
      :word-wrap-enabled="true"
    >
      <DxGrouping expand-mode="rowClick" />
      <DxSelection mode="single" />
      <DxPaging :enabled="false" />
      <DxScrolling column-rendering-mode="virtual" mode="virtual" />
      <DxLoadPanel
        shading-color="rgba(0,0,0,0.4)"
        :position="position"
        :show-indicator="showIndicator"
        :show-pane="showPane"
        :shading="shading"
        v-model:visible="loadingData"
        :enabled="true"
      />
      <DxSearchPanel :visible="true" :highlight-case-sensitive="true" />
      <DxExport
        :enabled="true"
        :formats="['pdf', 'xlsx', 'document']"
        :allow-export-selected-data="false"
      />
      <DxColumnFixing :enabled="true" />

      <!-- <DxColumn
        css-class="custom-table-column"
        :width="60"
        alignment="center"
        :calculateCellValue="(item: any) => data.findIndex((i) => i == item) + 1"
        caption="No"
      /> -->
      <DxColumn
        :width="120"
        alignment="center"
        data-field="kode"
        caption="Kode"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="120"
        alignment="center"
        data-field="id_fasilitas"
        caption=""
        css-class="custom-table-column"
        cell-template="formatText"
        name="idFasilitasGroup"
        :group-index="0"
      />
      <DxColumn
        :width="150"
        alignment="center"
        data-field="sub_kelompok"
        caption="Sub Kelompok (Equipment)"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn alignment="center" caption="Laporan" css-class="custom-table-column">
        <DxColumn
          :width="120"
          alignment="center"
          data-field="total"
          data-type="number"
          caption="Total"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
        <DxColumn alignment="center" caption="Sudah Selesai" css-class="custom-table-column">
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_selesai"
            data-type="number"
            caption="Jml"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="70"
            alignment="center"
            data-field="persen_selesai"
            data-type="number"
            caption="%"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
        <DxColumn alignment="center" caption="Belum Selesai" css-class="custom-table-column">
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_inproses"
            data-type="number"
            caption="Jml"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="70"
            alignment="center"
            data-field="persen_inproses"
            data-type="number"
            caption="%"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
      </DxColumn>
      <DxColumn alignment="center" caption="Response Time" css-class="custom-table-column">
        <DxColumn alignment="center" caption="Menit" css-class="custom-table-column">
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_durasi_response"
            data-type="number"
            caption="Total"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="avg_durasi_response"
            data-type="number"
            caption="Rata-Rata"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="max_durasi_response"
            data-type="number"
            caption="Max"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="min_durasi_response"
            data-type="number"
            caption="Min"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
        </DxColumn>
        <DxColumn alignment="center" caption="Laporan" css-class="custom-table-column">
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_diatas_sla_response"
            data-type="number"
            caption=">SLA"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_dibawah_sla_response"
            data-type="number"
            caption="≤SLA"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
      </DxColumn>
      <DxColumn alignment="center" caption="Recovery Time" css-class="custom-table-column">
        <DxColumn alignment="center" caption="Menit" css-class="custom-table-column">
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_durasi_recovery"
            data-type="number"
            caption="Total"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="avg_durasi_recovery"
            data-type="number"
            caption="Rata-Rata"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="max_durasi_recovery"
            data-type="number"
            caption="Max"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="min_durasi_recovery"
            data-type="number"
            caption="Min"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
        </DxColumn>
        <DxColumn alignment="center" caption="Laporan" css-class="custom-table-column">
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_diatas_sla_recovery"
            data-type="number"
            caption=">SLA"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_dibawah_sla_recovery"
            data-type="number"
            caption="≤SLA"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
      </DxColumn>

      <template #formatText="{ data }">
        <p class="text-left cursor-pointer">
          {{ data.text }}
        </p>
      </template>

      <template #formatNumber="{ data }">
        <p class="text-right cursor-pointer">
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatTime="{ data }">
        <p class="!text-right cursor-pointer">
          {{ parseInt(data.text) ? formatWaktu(data.text) : '-' }}
        </p>
      </template>

      <DxSummary>
        <DxGroupItem
          :show-in-group-footer="true"
          column="Kode"
          display-format="Total"
          css-class="!text-left"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_selesai"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="persen_selesai"
          summary-type="avg"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_inproses"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="persen_inproses"
          summary-type="avg"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_durasi_response"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="avg_durasi_response"
          summary-type="avg"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="max_durasi_response"
          summary-type="max"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="min_durasi_response"
          summary-type="min"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_diatas_sla_response"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_dibawah_sla_response"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_durasi_recovery"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="avg_durasi_recovery"
          summary-type="avg"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="max_durasi_recovery"
          summary-type="max"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="min_durasi_recovery"
          summary-type="min"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_diatas_sla_recovery"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_dibawah_sla_recovery"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
      </DxSummary>
    </DxDataGrid>
  </div>

  <DetailDialog
    :open="dialogDetail"
    title="Detail Rekapitulasi Gangguan/Jenis Gangguan SE 004"
    @on-close="closeDialog"
    :full-width="true"
  >
    <div class="w-full mb-4 lg:w-[70%] lg:float-left">
      <div class="p-4 bg-white rounded-xl lg:mr-4">
        <DxDataGrid
          :allow-column-reordering="true"
          class="max-h-[calc(100vh-140px)]"
          :data-source="dataSub"
          :show-column-lines="true"
          :show-row-lines="false"
          :show-borders="true"
          :row-alternation-enabled="true"
          :hover-state-enabled="true"
          @selection-changed="onDataSubSelectionChanged"
          :column-width="100"
          @exporting="onExporting"
          :allow-column-resizing="true"
          column-resizing-mode="widget"
        >
          <DxSelection mode="single" />
          <DxPaging :page-size="20" :enabled="true" />
          <DxPager
            :visible="true"
            :allowed-page-sizes="[20, 50, 100]"
            display-mode="full"
            :show-page-size-selector="true"
            :show-info="true"
            :show-navigation-buttons="true"
          />
          <DxLoadPanel
            shading-color="rgba(0,0,0,0.4)"
            :position="position"
            :show-indicator="showIndicator"
            :show-pane="showPane"
            :shading="shading"
            v-model:visible="loadingSubData"
            :enabled="true"
          />
          <DxSearchPanel :visible="true" :highlight-case-sensitive="true" />
          <DxExport
            :enabled="true"
            :formats="['pdf', 'xlsx', 'document']"
            :allow-export-selected-data="false"
          />

          <DxColumn
            css-class="custom-table-column"
            :width="50"
            alignment="center"
            :calculateCellValue="(item: any) => dataSub.findIndex((i) => i == item) + 1"
            data-type="number"
            caption="No"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="no_laporan"
            caption="No Laporan"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_lapor"
            caption="Tgl Lapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_response"
            caption="Tgl Datang"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_recovery"
            caption="Tgl Nyala"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="durasi_response_time"
            caption="Durasi Response Time"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="durasi_recovery_time"
            caption="Durasi Recovery Time"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="status_akhir"
            caption="Status"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="referensi_marking"
            caption="Referensi Marking"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="id_pelnomormeter"
            caption="IDPEL/NO METER"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_pelapor"
            caption="Nama Pelapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="alamat_pelapor"
            caption="Alamat Pelapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="no_telp_pelapor"
            caption="No Telp Pelapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="200"
            alignment="center"
            data-field="keterangan_pelapor"
            caption="Keterangan Pelapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_posko"
            caption="Posko"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="tindakan"
            caption="Tidakan"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="penyebab"
            caption="Penyebab"
            css-class="custom-table-column"
            cell-template="formatText"
          />

          <template #formatText="{ data }">
            <p class="text-left cursor-pointer">
              {{ data.text }}
            </p>
          </template>

          <template #formatNumber="{ data }">
            <p class="text-right cursor-pointer">
              {{ data.text }}
            </p>
          </template>

          <template #formatTime="{ data }">
            <p>
              {{ parseInt(data.text) ? formatWaktu(data.text) : '-' }}
            </p>
          </template>
        </DxDataGrid>
      </div>
    </div>
    <div class="w-full mb-4 lg:w-[30%] lg:float-right">
      <div class="p-4 space-y-2 bg-white rounded-xl">
        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">No Laporan:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.no_laporan" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Tgl Lapor:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.waktu_lapor" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Tgl Datang:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.waktu_response"
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Tgl Nyala:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.waktu_recovery"
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Durasi Response Time:</h3>
          <InputText
            :readonly="true"
            :value="
              parseInt(dataSubSelected?.durasi_response_time)
                ? formatWaktu(dataSubSelected?.durasi_response_time)
                : '-'
            "
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Durasi Recovery Time:</h3>
          <InputText
            :readonly="true"
            :value="
              parseInt(dataSubSelected?.durasi_recovery_time)
                ? formatWaktu(dataSubSelected?.durasi_recovery_time)
                : '-'
            "
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Status:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.status_akhir" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Referensi Marking:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.referensi_marking"
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">IDPEL/NO METER:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.id_pelnomormeter"
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Nama Pelapor:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.nama_pelapor" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Alamat Pelapor:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.alamat_pelapor"
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">No Telp Pelapor:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.no_telp_pelapor"
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Keterangan Pelapor:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.keterangan_pelapor"
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Posko:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.nama_posko" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Tindakan:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.tindakan" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Penyebab:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.penyebab" class-name="flex-1" />
        </div>
      </div>
    </div>
  </DetailDialog>
</template>

<script setup lang="ts">
import Filters from '@/components/Form/Filters.vue'
import Type1 from '@/components/Form/FiltersType/Type1.vue'
import { onMounted, ref, watch } from 'vue'
import { formatWaktu } from '@/components/Form/FiltersType/reference'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxLoadPanel,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection,
  DxSummary,
  DxGroupItem,
  DxPager,
  DxGrouping
} from 'devextreme-vue/data-grid'
import { jsPDF } from 'jspdf'
import { exportDataGrid as exportToPdf } from 'devextreme/pdf_exporter'
import { exportDataGrid as exportToExcel } from 'devextreme/excel_exporter'
import { saveAs } from 'file-saver'
import { Workbook } from 'exceljs'
import { useQuery } from '@vue/apollo-composable'
import { queries } from '@/utils/api/api.graphql'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'
import InputText from '@/components/InputText.vue'
import DetailDialog from '@/components/Dialogs/DetailDialog.vue'
import { apolloClient } from '@/utils/api/api.graphql'
import { provideApolloClient } from '@vue/apollo-composable'

const client = apolloClient()
provideApolloClient(client)
const position = { of: '#data' }
const showIndicator = ref(true)
const shading = ref(true)
const showPane = ref(true)
const data = ref<any[]>([])
const dataSub = ref<any[]>([])
const dataSelected = ref<any>(null)
const dataSubSelected = ref<any>(null)
const dialogDetail = ref(false)
const loadingData = ref(false)
const loadingSubData = ref(false)

const closeDialog = () => {
  dialogDetail.value = false
}

const onExporting = (e: any) => {
  if (e.format === 'pdf') {
    const doc = new jsPDF()

    exportToPdf({
      jsPDFDocument: doc,
      component: e.component,
      indent: 5
    }).then(() => {
      doc.save(`.pdf`)
    })
  } else {
    const workbook = new Workbook()
    const worksheet = workbook.addWorksheet('Employees')

    exportToExcel({
      component: e.component,
      worksheet,
      autoFilterEnabled: true
    }).then(() => {
      workbook.xlsx.writeBuffer().then((buffer: any) => {
        saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'DataGrid.xlsx')
      })
    })

    e.cancel = true
  }
}

const filterData = (params: any) => {
  const dateValue = params.periode.split(' s/d ')
  const { posko, uid, up3 } = params

  const { onResult, onError, loading, refetch } = useQuery(
    queries.gangguan.rekap.jenisGangguanSE004,
    {
      dateFrom: dateValue[0]
        ? dateValue[0].split('-').reverse().join('-')
        : new Date().toISOString().slice(0, 10),
      dateTo: dateValue[1]
        ? dateValue[1].split('-').reverse().join('-')
        : new Date().toISOString().slice(0, 10),
      posko: posko ? posko.id : 0,
      idUid: uid ? uid.id : 0,
      idUp3: up3 ? up3.id : 0
    }
  )

  onResult((queryResult) => {
    if (queryResult.data != undefined) {
      data.value = queryResult.data.rekapitulasiJenisGangguanSE004
    }
  })

  onError((queryError) => {
    console.log(queryError)
  })

  watch(loading, (value) => {
    loadingData.value = value
  })
}

const getDetail = () => {
  loadingSubData.value = true
  const dateValue = filters.value.periode.split(' s/d ')
  const ref = dataSelected.value
  const { posko, uid, up3 } = filters.value

  const query = {
    dateFrom: dateValue[0]
      ? dateValue[0].split('-').reverse().join('-')
      : new Date().toISOString().slice(0, 10),
    dateTo: dateValue[1]
      ? dateValue[1].split('-').reverse().join('-')
      : new Date().toISOString().slice(0, 10),
    posko: posko ? posko.id : 0,
    idUid: uid ? uid.id : 0,
    idUp3: up3 ? up3.id : 0,
    idEquipment: ref?.kode ? parseInt(ref.kode) : 0
  }

  const { onResult, onError, loading, refetch } = useQuery(
    queries.gangguan.rekap.jenisGangguanSE004Detail,
    query
  )

  onResult((queryResult) => {
    if (queryResult.data != undefined) {
      dataSub.value = queryResult.data.detailGangguanJenisGangguanSE004
    }
  })

  onError((error) => {
    console.log(error)
  })

  watch(loading, (value) => {
    loadingSubData.value = value
  })
}

const dataGridRef = ref<DxDataGrid | null>(null)
const clearSelection = () => {
  const dataGrid = dataGridRef.value!.instance!
  dataGrid.clearSelection()
}
const showDetail = () => {
  clearSelection()
  dataSub.value = []
  dataSubSelected.value = null
  dialogDetail.value = true
  getDetail()
}

const onDataSelectionChanged = ({ selectedRowsData }: any) => {
  if (selectedRowsData[0] != undefined) {
    dataSelected.value = selectedRowsData[0]
    showDetail()
  }
}

const onDataSubSelectionChanged = ({ selectedRowsData }: any) => {
  if (selectedRowsData[0] != undefined) {
    dataSubSelected.value = selectedRowsData[0]
  }
}

const filters = ref()
onMounted(() => {
  if (import.meta.env.DEV) {
    data.value = [
      {
        id: 42,
        id_fasilitas: '111 (Gardu Induk -> Padam Tidak Terencana -> Distribusi )',
        sub_kelompok: 'MV Cell',
        kode: '11111',
        equipment_id: null,
        total: 0,
        total_selesai: 0,
        persen_selesai: 0.0,
        total_inproses: 0,
        persen_inproses: 0.0,
        total_durasi_response: null,
        avg_durasi_response: null,
        min_durasi_response: null,
        max_durasi_response: null,
        total_dibawah_sla_response: 0,
        total_diatas_sla_response: 0,
        total_durasi_recovery: null,
        avg_durasi_recovery: null,
        min_durasi_recovery: null,
        max_durasi_recovery: null,
        total_dibawah_sla_recovery: 0,
        total_diatas_sla_recovery: 0,
        total_response: 0,
        total_recovery: 0
      },
      {
        id: 40,
        id_fasilitas: '111 (Gardu Induk -> Padam Tidak Terencana -> Distribusi )',
        sub_kelompok: 'Kabel Outgoing s/d Pole Pertama',
        kode: '11112',
        equipment_id: null,
        total: 0,
        total_selesai: 0,
        persen_selesai: 0.0,
        total_inproses: 0,
        persen_inproses: 0.0,
        total_durasi_response: null,
        avg_durasi_response: null,
        min_durasi_response: null,
        max_durasi_response: null,
        total_dibawah_sla_response: 0,
        total_diatas_sla_response: 0,
        total_durasi_recovery: null,
        avg_durasi_recovery: null,
        min_durasi_recovery: null,
        max_durasi_recovery: null,
        total_dibawah_sla_recovery: 0,
        total_diatas_sla_recovery: 0,
        total_response: 0,
        total_recovery: 0
      },
      {
        id: 46,
        id_fasilitas: '111 (Gardu Induk -> Padam Tidak Terencana -> Distribusi )',
        sub_kelompok: 'Kapasitor',
        kode: '11113',
        equipment_id: null,
        total: 0,
        total_selesai: 0,
        persen_selesai: 0.0,
        total_inproses: 0,
        persen_inproses: 0.0,
        total_durasi_response: null,
        avg_durasi_response: null,
        min_durasi_response: null,
        max_durasi_response: null,
        total_dibawah_sla_response: 0,
        total_diatas_sla_response: 0,
        total_durasi_recovery: null,
        avg_durasi_recovery: null,
        min_durasi_recovery: null,
        max_durasi_recovery: null,
        total_dibawah_sla_recovery: 0,
        total_diatas_sla_recovery: 0,
        total_response: 0,
        total_recovery: 0
      },
      {
        id: 9,
        id_fasilitas: '111 (Gardu Induk -> Padam Tidak Terencana -> Distribusi )',
        sub_kelompok: 'Relay Outgoing Feeder',
        kode: '11114',
        equipment_id: null,
        total: 0,
        total_selesai: 0,
        persen_selesai: 0.0,
        total_inproses: 0,
        persen_inproses: 0.0,
        total_durasi_response: null,
        avg_durasi_response: null,
        min_durasi_response: null,
        max_durasi_response: null,
        total_dibawah_sla_response: 0,
        total_diatas_sla_response: 0,
        total_durasi_recovery: null,
        avg_durasi_recovery: null,
        min_durasi_recovery: null,
        max_durasi_recovery: null,
        total_dibawah_sla_recovery: 0,
        total_diatas_sla_recovery: 0,
        total_response: 0,
        total_recovery: 0
      },
      {
        id: 20,
        id_fasilitas: '112 (Penyulang -> Padam Tidak Terencana -> Distribusi )',
        sub_kelompok: 'Konduktor',
        kode: '11211',
        equipment_id: '11211',
        total: 571,
        total_selesai: 571,
        persen_selesai: 100.0,
        total_inproses: 0,
        persen_inproses: 0.0,
        total_durasi_response: 2317727,
        avg_durasi_response: 68.16254416961131,
        min_durasi_response: 0,
        max_durasi_response: 2277180,
        total_dibawah_sla_response: 563,
        total_diatas_sla_response: 3,
        total_durasi_recovery: 3167860,
        avg_durasi_recovery: 92.45964912280702,
        min_durasi_recovery: 0,
        max_durasi_recovery: 2277240,
        total_dibawah_sla_recovery: 555,
        total_diatas_sla_recovery: 15,
        total_response: 566,
        total_recovery: 570
      },
      {
        id: 37,
        id_fasilitas: '112 (Penyulang -> Padam Tidak Terencana -> Distribusi )',
        sub_kelompok: 'Tiang',
        kode: '11212',
        equipment_id: '11212',
        total: 5,
        total_selesai: 5,
        persen_selesai: 100.0,
        total_inproses: 0,
        persen_inproses: 0.0,
        total_durasi_response: 300,
        avg_durasi_response: 1.0,
        min_durasi_response: 60,
        max_durasi_response: 60,
        total_dibawah_sla_response: 5,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 14040,
        avg_durasi_recovery: 46.8,
        min_durasi_recovery: 120,
        max_durasi_recovery: 9300,
        total_dibawah_sla_recovery: 5,
        total_diatas_sla_recovery: 0,
        total_response: 5,
        total_recovery: 5
      },
      {
        id: 35,
        id_fasilitas: '112 (Penyulang -> Padam Tidak Terencana -> Distribusi )',
        sub_kelompok: 'DS / LBS',
        kode: '11213',
        equipment_id: '11213',
        total: 13,
        total_selesai: 13,
        persen_selesai: 100.0,
        total_inproses: 0,
        persen_inproses: 0.0,
        total_durasi_response: 1470,
        avg_durasi_response: 1.8461538461538463,
        min_durasi_response: 0,
        max_durasi_response: 300,
        total_dibawah_sla_response: 13,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 9209,
        avg_durasi_recovery: 11.692307692307692,
        min_durasi_recovery: 120,
        max_durasi_recovery: 4020,
        total_dibawah_sla_recovery: 13,
        total_diatas_sla_recovery: 0,
        total_response: 13,
        total_recovery: 13
      },
      {
        id: 45,
        id_fasilitas: '112 (Penyulang -> Padam Tidak Terencana -> Distribusi )',
        sub_kelompok: 'Recloser / PMCB',
        kode: '11214',
        equipment_id: '11214',
        total: 99,
        total_selesai: 99,
        persen_selesai: 100.0,
        total_inproses: 0,
        persen_inproses: 0.0,
        total_durasi_response: 2433074,
        avg_durasi_response: 409.5656565656566,
        min_durasi_response: 0,
        max_durasi_response: 2395440,
        total_dibawah_sla_response: 93,
        total_diatas_sla_response: 6,
        total_durasi_recovery: 2525728,
        avg_durasi_recovery: 425.1515151515151,
        min_durasi_recovery: 1,
        max_durasi_recovery: 2395500,
        total_dibawah_sla_recovery: 98,
        total_diatas_sla_recovery: 1,
        total_response: 99,
        total_recovery: 99
      },
      {
        id: 13,
        id_fasilitas: '112 (Penyulang -> Padam Tidak Terencana -> Distribusi )',
        sub_kelompok: 'AVR / Kapasitor',
        kode: '11215',
        equipment_id: null,
        total: 0,
        total_selesai: 0,
        persen_selesai: 0.0,
        total_inproses: 0,
        persen_inproses: 0.0,
        total_durasi_response: null,
        avg_durasi_response: null,
        min_durasi_response: null,
        max_durasi_response: null,
        total_dibawah_sla_response: 0,
        total_diatas_sla_response: 0,
        total_durasi_recovery: null,
        avg_durasi_recovery: null,
        min_durasi_recovery: null,
        max_durasi_recovery: null,
        total_dibawah_sla_recovery: 0,
        total_diatas_sla_recovery: 0,
        total_response: 0,
        total_recovery: 0
      },
      {
        id: 52,
        id_fasilitas: '112 (Penyulang -> Padam Tidak Terencana -> Distribusi )',
        sub_kelompok: 'CT / PT kWh Meter Exim',
        kode: '11216',
        equipment_id: '11216',
        total: 1,
        total_selesai: 1,
        persen_selesai: 100.0,
        total_inproses: 0,
        persen_inproses: 0.0,
        total_durasi_response: 35,
        avg_durasi_response: 0.0,
        min_durasi_response: 35,
        max_durasi_response: 35,
        total_dibawah_sla_response: 1,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 95,
        avg_durasi_recovery: 1.0,
        min_durasi_recovery: 95,
        max_durasi_recovery: 95,
        total_dibawah_sla_recovery: 1,
        total_diatas_sla_recovery: 0,
        total_response: 1,
        total_recovery: 1
      }
    ]
  }
})
</script>
