<template>
  <Filters
    @reset-form="data = []"
    @run-search="() => filterData(filters)"
    @run-report="() => exportToPDF(reportMeta, data, true)"
    :report-button="true"
    class="mb-4"
  >
    <Type9 @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"
      v-if="loadingData == false"
      :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"
    >
      <DxSelection mode="single" />
      <DxPaging :enabled="false" />
      <DxScrolling column-rendering-mode="virtual" mode="virtual" />
      <!--  -->

      <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="50"
        alignment="center"
        :calculate-display-value="(item: any) => data.findIndex((i) => i == item) + 1"
        data-type="number"
        caption="No"
        cell-template="formatNumber"
      />
      <DxColumn
        v-if="grouping.length > 0"
        v-for="(group, index) in grouping"
        :width="150"
        alignment="center"
        :data-field="group.data"
        :caption="group.caption"
        css-class="custom-table-column"
        cell-template="formatText"
        :group-index="index"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="tanggal"
        caption="Tanggal Lapor"
        css-class="custom-table-column"
      />
      <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="formatNumberLaporanTotal"
        />
        <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="formatNumberLaporanJmlSelesai"
          />
          <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="formatNumberLaporanJmlBelumSelesai"
          />
          <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
            :visible="false"
            :width="120"
            alignment="center"
            data-field="count_durasi_response"
            data-type="number"
            caption="Jumlah Response"
            css-class="custom-table-column"
            cell-template="formatNumber"
            :calculate-cell-value="
              (rowData: any) => rowData.total_durasi_response * rowData.avg_durasi_response
            "
          />
          <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
            :visible="false"
            :width="120"
            alignment="center"
            data-field="count_durasi_recovery"
            data-type="number"
            caption="Jumlah Response"
            css-class="custom-table-column"
            cell-template="formatNumber"
            :calculate-cell-value="
              (rowData: any) => rowData.total_durasi_recovery * rowData.avg_durasi_recovery
            "
          />
          <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" @click="setDialogStatus(false, 0)">
          {{ data.text }}
        </p>
      </template>

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

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

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

      <template #formatNumberLaporanJmlBelumSelesai="{ data }">
        <p class="text-right cursor-pointer" @click="setDialogStatus(true, 2)">
          {{
            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" @click="setDialogStatus(false, 0)">
          {{ parseInt(data.text) ? formatWaktu(data.text) : '-' }}
        </p>
      </template>

      <DxSummary :calculate-custom-summary="calculateCustomSummary">
        <DxTotalItem
          display-format="TOTAL"
          show-in-column="tanggal"
          css-class="text-white !text-left"
        />
        <DxTotalItem
          column="total"
          name="total"
          summary-type="custom"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="total_selesai"
          name="total_selesai"
          summary-type="custom"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="persen_selesai"
          name="persen_selesai"
          summary-type="custom"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />

        <DxTotalItem
          column="total_inproses"
          name="total_inproses"
          summary-type="custom"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="persen_inproses"
          name="persen_inproses"
          summary-type="custom"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />

        <DxTotalItem
          column="total_durasi_response"
          name="total_durasi_response"
          summary-type="custom"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="count_durasi_response"
          name="count_durasi_response"
          summary-type="custom"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="avg_durasi_response"
          name="avg_durasi_response"
          summary-type="custom"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="max_durasi_response"
          summary-type="max"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatWaktu(e.value)"
        />
        <DxTotalItem
          column="min_durasi_response"
          summary-type="min"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatWaktu(e.value)"
        />

        <DxTotalItem
          column="total_diatas_sla_response"
          summary-type="sum"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="total_dibawah_sla_response"
          summary-type="sum"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />

        <DxTotalItem
          column="total_durasi_recovery"
          name="total_durasi_recovery"
          summary-type="custom"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="count_durasi_recovery"
          name="count_durasi_recovery"
          summary-type="custom"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="avg_durasi_recovery"
          name="avg_durasi_recovery"
          summary-type="custom"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="max_durasi_recovery"
          summary-type="max"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatWaktu(e.value)"
        />
        <DxTotalItem
          column="min_durasi_recovery"
          summary-type="min"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatWaktu(e.value)"
        />

        <DxTotalItem
          column="total_diatas_sla_recovery"
          summary-type="sum"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="total_dibawah_sla_recovery"
          summary-type="sum"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
      </DxSummary>
    </DxDataGrid>
  </div>

  <DetailDialog
    :open="dialogDetail"
    title="Detail Rekapitulasi Gangguan/Tanggal"
    @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="onExportingDetail"
          :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"
          />
          <!--  -->
          <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"
            :calculate-display-value="(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>

  <BufferDialog v-if="loadingData || loadingSubData" />
</template>

<script setup lang="ts">
import Filters from '@/components/Form/Filters.vue'
import Type9 from '@/components/Form/FiltersType/Type9.vue'
import { formatWaktu } from '@/components/Form/FiltersType/reference'
import { onMounted, ref } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxPager,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection,
  DxSummary,
  DxTotalItem
} from 'devextreme-vue/data-grid'
import { queries, requestGraphQl } from '@/utils/api/api.graphql'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'
import { apolloClient } from '@/utils/api/api.graphql'
import { provideApolloClient } from '@vue/apollo-composable'
import DetailDialog from '@/components/Dialogs/DetailDialog.vue'
import InputText from '@/components/InputText.vue'
import {
  exportToPDF,
  exportDetailToPDF,
  exportToXLSX,
  exportDetailToXLSX,
  exportToDOCX,
  exportDetailToDOCX
} from '@/report/Gangguan/Rekap/RGangguan_PerTanggal'
import BufferDialog from '@/components/Dialogs/BufferDialog.vue'
import { reformatDate } from '@/utils/texts'

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>()
const dataSubSelected = ref<any>()
const dialogDetail = ref(false)
const loadingData = ref(false)
const loadingSubData = ref(false)
const filters = ref<any>({ groupBy: false })
const reportMeta = ref({
  uid: { id: 0, name: 'Semua Unit Induk Distribusi/Wilayah' },
  up3: { id: 0, name: 'Semua Unit Pelaksanaan Pelayanan Pelanggan' },
  posko: { id: 0, name: 'Semua Posko' },
  periode: '',
  groupBy: false
})
const grouping = ref<any[]>([
  {
    data: '',
    caption: 'Seluruh Unit'
  }
])
const isDialogEnabled = ref(false)
const progressSelected = ref(0)
const isGroupBy = ref(false)

const setDialogStatus = (status: boolean, progress: number) => {
  isDialogEnabled.value = status
  progressSelected.value = progress
}

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

  var query = {
    dateFrom: ref?.tanggal ? reformatDate(ref?.tanggal, 'yyyy/MM/dd', 'yyyy-MM-dd') : '',
    dateTo: ref?.tanggal ? reformatDate(ref?.tanggal, 'yyyy/MM/dd', 'yyyy-MM-dd') : '',
    posko: 0,
    idUid: 0,
    idUp3: 0,
    idUlp: 0,
    idRegu: 0,
    namaRegional: ref?.nama_regional ? ref?.nama_regional : '',
    media: ref?.media ? ref?.media : '',
    isSelesai: progressSelected.value,
    tanggal: ref?.tanggal ? reformatDate(ref?.tanggal, 'yyyy/MM/dd', 'yyyy-MM-dd') : ''
  }

  if (isGroupBy.value) {
    query = {
      ...query,
      idUid: ref?.id_uid
    }
    if (uid.id != 0) {
      query = {
        ...query,
        idUp3: ref?.id_up3
      }

      if (up3.id != 0) {
        query = {
          ...query,
          posko: ref?.id_posko
        }

        if (posko.id != 0) {
          query = {
            ...query,
            idUlp: ref?.id_ulp
          }
        }
      }
    }
  } else {
    if (uid.id != 0) {
      query = {
        ...query,
        idUid: uid.id
      }
      if (up3.id != 0) {
        query = {
          ...query,
          idUp3: up3.id
        }
        if (posko.id != 0) {
          query = {
            ...query,
            posko: posko.id
          }
        }
      }
    }
  }

  loadingSubData.value = true
  await requestGraphQl(queries.gangguan.rekap.gangguanAllDetail, query)
    .then((result) => {
      if (result.data.data != undefined) {
        dataSub.value = result.data.data.detailGangguan
      } else {
        dataSub.value = []
      }
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingSubData.value = false
      dialogDetail.value = true
    })
}

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

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

const onExporting = (e: any) => {
  if (e.format === 'pdf') {
    exportToPDF(reportMeta.value, data.value)
  } else if (e.format === 'xlsx') {
    exportToXLSX(reportMeta.value, e)
  } else {
    exportToDOCX(reportMeta.value, data.value)
  }
}

const onExportingDetail = (e: any) => {
  if (e.format === 'pdf') {
    exportDetailToPDF(reportMeta.value, dataSub.value)
  } else if (e.format === 'xlsx') {
    exportDetailToXLSX(reportMeta.value, e)
  } else {
    exportDetailToDOCX(reportMeta.value, dataSub.value)
  }
}

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 resetData = () => {
  data.value = []
  dataSub.value = []
}

const filterData = async (params: any) => {
  resetData()
  const dateValue = params.periode.split(' s/d ')
  const { posko, uid, up3 } = params
  isGroupBy.value = params.groupBy
  if (isGroupBy.value) {
    if (uid.id != 0) {
      grouping.value = [
        {
          data: 'nama_up3',
          caption: 'UP3'
        }
      ]

      if (up3.id != 0 || posko.id != 0) {
        grouping.value = [
          {
            data: 'nama_posko',
            caption: 'Posko'
          }
        ]
      }
    } else {
      grouping.value = [
        {
          data: 'nama_uid',
          caption: 'UID'
        }
      ]
    }
  } else {
    if (uid.id != 0) {
      grouping.value = [
        {
          data: 'nama_uid',
          caption: 'UID'
        }
      ]

      if (up3.id != 0) {
        grouping.value = [
          {
            data: 'nama_up3',
            caption: 'UP3'
          }
        ]

        if (posko.id != 0) {
          grouping.value = [
            {
              data: 'nama_posko',
              caption: 'Posko'
            }
          ]
        }
      }
    } else {
      grouping.value = [
        {
          data: '',
          caption: 'Seluruh Unit'
        }
      ]
    }
  }

  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
  }

  loadingData.value = true
  await requestGraphQl(
    isGroupBy.value
      ? grouping.value[0].data == 'nama_uid'
        ? queries.gangguan.rekap.gangguanPerTanggalUID
        : grouping.value[0].data == 'nama_up3'
          ? queries.gangguan.rekap.gangguanPerTanggalUP3
          : queries.gangguan.rekap.gangguanPerTanggalPosko
      : queries.gangguan.rekap.gangguanPerTanggal,
    query
  )
    .then((result) => {
      if (result.data.data != undefined) {
        if (grouping.value.length > 0 && grouping.value[0].data != '') {
          data.value = [
            ...(isGroupBy.value
              ? grouping.value[0].data == 'nama_uid'
                ? result.data.data.rekapitulasiGangguanPerTanggalUid
                : grouping.value[0].data == 'nama_up3'
                  ? result.data.data.rekapitulasiGangguanPerTanggalUp3
                  : result.data.data.rekapitulasiGangguanPerTanggalPosko
              : result.data.data.rekapitulasiGangguanPerTanggal)
          ].sort((a, b) => a[grouping.value[0].data].localeCompare(b[grouping.value[0].data]))
        } else {
          data.value = isGroupBy.value
            ? grouping.value[0].data == 'nama_uid'
              ? result.data.data.rekapitulasiGangguanPerTanggalUid
              : grouping.value[0].data == 'nama_up3'
                ? result.data.data.rekapitulasiGangguanPerTanggalUp3
                : result.data.data.rekapitulasiGangguanPerTanggalPosko
            : result.data.data.rekapitulasiGangguanPerTanggal
        }
      } else {
        data.value = []
      }
      reportMeta.value = {
        uid: { id: uid ? uid.id : 0, name: uid ? uid.name : 'Semua Unit Induk Distribusi/Wilayah' },
        up3: {
          id: up3 ? up3.id : 0,
          name: up3 ? up3.name : 'Semua Unit Pelaksanaan Pelayanan Pelanggan'
        },
        posko: { id: posko ? posko.id : 0, name: posko ? posko.name : 'Semua Posko' },
        periode: params.periode,
        groupBy: params.groupBy
      }
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingData.value = false
    })
}

let total = 0
let total_selesai = 0
let total_inproses = 0
let count_durasi_response = 0
let total_durasi_response = 0
let total_durasi_recovery = 0
let count_durasi_recovery = 0
const calculateCustomSummary = (options: any) => {
  if (options.name === 'total') {
    if (options.summaryProcess === 'calculate') {
      total += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = total
    }
  }

  if (options.name === 'total_selesai') {
    if (options.summaryProcess === 'calculate') {
      total_selesai += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = total_selesai
    }
  }

  if (options.name === 'total_inproses') {
    if (options.summaryProcess === 'calculate') {
      total_inproses += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = total_inproses
    }
  }

  if (options.name === 'persen_selesai') {
    if (options.summaryProcess === 'start') {
      total = 0
      total_selesai = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = !isFinite(total_selesai / total)
        ? 0
        : total_selesai == 0
          ? 0
          : (total_selesai / total) * 100
    }
  }

  if (options.name === 'persen_inproses') {
    if (options.summaryProcess === 'start') {
      total = 0
      total_inproses = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = !isFinite(total_inproses / total)
        ? 0
        : total_inproses == 0
          ? 0
          : (total_inproses / total) * 100
    }
  }

  if (options.name === 'total_durasi_response') {
    if (options.summaryProcess === 'calculate') {
      total_durasi_response += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = total_durasi_response
    }
  }

  if (options.name === 'count_durasi_response') {
    if (options.summaryProcess === 'calculate') {
      count_durasi_response += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = count_durasi_response
    }
  }

  if (options.name === 'avg_durasi_response') {
    if (options.summaryProcess === 'start') {
      total_durasi_response = 0
      count_durasi_response = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = !isFinite(count_durasi_response / total_durasi_response)
        ? 0
        : count_durasi_response == 0
          ? 0
          : count_durasi_response / total_durasi_response
    }
  }

  if (options.name === 'count_durasi_recovery') {
    if (options.summaryProcess === 'calculate') {
      count_durasi_recovery += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = count_durasi_recovery
    }
  }

  if (options.name === 'total_durasi_recovery') {
    if (options.summaryProcess === 'calculate') {
      total_durasi_recovery += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = total_durasi_recovery
    }
  }

  if (options.name === 'avg_durasi_recovery') {
    if (options.summaryProcess === 'start') {
      count_durasi_recovery = 0
      total_durasi_recovery = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = !isFinite(count_durasi_recovery / total_durasi_recovery)
        ? 0
        : count_durasi_recovery == 0
          ? 0
          : count_durasi_recovery / total_durasi_recovery
    }
  }
}

onMounted(() => {
  if (import.meta.env.DEV) {
    data.value = [
      {
        id: 0,
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        tanggal: '2023/01/02',
        total: 46913,
        total_selesai: 46879,
        persen_selesai: 99.92752541939335,
        total_inproses: 34,
        persen_inproses: 0.07247458060665488,
        total_durasi_response: 58470518,
        avg_durasi_response: 1918.3870205715411,
        min_durasi_response: 45,
        max_durasi_response: 86865,
        total_dibawah_sla_response: 25337,
        total_diatas_sla_response: 5142,
        total_durasi_recovery: 85727469,
        avg_durasi_recovery: 2867.8108252768207,
        min_durasi_recovery: 86,
        max_durasi_recovery: 88362,
        total_dibawah_sla_recovery: 29840,
        total_diatas_sla_recovery: 53,
        total_response: 30479,
        total_recovery: 29893
      },
      {
        id: 1,
        id_uid: 2,
        nama_uid: 'DISTRIBUSI JAKARTA RAYA',
        tanggal: '2023/01/03',
        total: 42333,
        total_selesai: 42303,
        persen_selesai: 99.92913330026221,
        total_inproses: 30,
        persen_inproses: 0.07086669973779322,
        total_durasi_response: 53049489,
        avg_durasi_response: 1834.2895819646624,
        min_durasi_response: 37,
        max_durasi_response: 26629,
        total_dibawah_sla_response: 24425,
        total_diatas_sla_response: 4496,
        total_durasi_recovery: 80409355,
        avg_durasi_recovery: 2831.0162658874065,
        min_durasi_recovery: 106,
        max_durasi_recovery: 28031,
        total_dibawah_sla_recovery: 28332,
        total_diatas_sla_recovery: 71,
        total_response: 28921,
        total_recovery: 28403
      },
      {
        id: 2,
        id_uid: 427,
        nama_uid: 'DISTRIBUSI JAWA BARAT',
        tanggal: '2023/01/04',
        total: 41907,
        total_selesai: 41884,
        persen_selesai: 99.94511656763785,
        total_inproses: 23,
        persen_inproses: 0.05488343236213521,
        total_durasi_response: 49439197,
        avg_durasi_response: 1741.1233315724598,
        min_durasi_response: 64,
        max_durasi_response: 21945,
        total_dibawah_sla_response: 24662,
        total_diatas_sla_response: 3733,
        total_durasi_recovery: 75561041,
        avg_durasi_recovery: 2712.6562915096033,
        min_durasi_recovery: 149,
        max_durasi_recovery: 26940,
        total_dibawah_sla_recovery: 27784,
        total_diatas_sla_recovery: 71,
        total_response: 28395,
        total_recovery: 27855
      },
      {
        id: 3,
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        tanggal: '2023/01/05',
        total: 41969,
        total_selesai: 41942,
        persen_selesai: 99.93566680168696,
        total_inproses: 27,
        persen_inproses: 0.06433319831304057,
        total_durasi_response: 48194720,
        avg_durasi_response: 1705.6455266138166,
        min_durasi_response: 67,
        max_durasi_response: 17030,
        total_dibawah_sla_response: 24635,
        total_diatas_sla_response: 3621,
        total_durasi_recovery: 74421179,
        avg_durasi_recovery: 2679.044566039094,
        min_durasi_recovery: 118,
        max_durasi_recovery: 88309,
        total_dibawah_sla_recovery: 27746,
        total_diatas_sla_recovery: 33,
        total_response: 28256,
        total_recovery: 27779
      },
      {
        id: 4,
        id_uid: 101,
        nama_uid: 'DISTRIBUSI JAWA TENGAH & DIY',
        tanggal: '2023/01/06',
        total: 39159,
        total_selesai: 39137,
        persen_selesai: 99.94381879006103,
        total_inproses: 22,
        persen_inproses: 0.05618120993896678,
        total_durasi_response: 46208746,
        avg_durasi_response: 1715.81991014073,
        min_durasi_response: -6640,
        max_durasi_response: 17400,
        total_dibawah_sla_response: 23310,
        total_diatas_sla_response: 3621,
        total_durasi_recovery: 71354127,
        avg_durasi_recovery: 2691.4913432160233,
        min_durasi_recovery: -6147,
        max_durasi_recovery: 86700,
        total_dibawah_sla_recovery: 26499,
        total_diatas_sla_recovery: 12,
        total_response: 26931,
        total_recovery: 26511
      }
    ]
  }
})
</script>
