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

  <div>
    <DxDataGrid
      @cell-click="onCellClicked"
      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"
      @exporting="onExporting"
      :allow-column-resizing="true"
      column-resizing-mode="widget"
    >
      <DxPaging :enabled="false" />
      <DxGrouping :auto-expand-all="false" :context-menu-enabled="true" expand-mode="" />
      <DxSelection mode="single" />

      <DxSearchPanel :visible="true" :highlight-case-sensitive="true" />
      <DxExport
        :enabled="true"
        :formats="['pdf', 'xlsx', 'document']"
        :allow-export-selected-data="false"
      />

      <DxColumn
        alignment="center"
        :width="200"
        data-field="nama_ulp"
        caption="Nama Unit"
        css-class="custom-table-column"
        cell-template="formatText"
      />

      <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 alignment="center" caption="Response Time" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total"
          data-type="number"
          caption="Total"
          css-class="custom-table-column"
          cell-template="formatNumberTotal"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_selesai"
          data-type="number"
          caption="Selesai"
          css-class="custom-table-column"
          cell-template="formatNumberSelesai"
        />
        <DxColumn
          :width="70"
          alignment="center"
          data-field="persen_selesai"
          data-type="number"
          caption="%"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_inproses"
          data-type="number"
          caption="InProgress"
          css-class="custom-table-column"
          cell-template="formatNumberProgress"
        />
        <DxColumn
          :width="70"
          alignment="center"
          data-field="persen_inproses"
          data-type="number"
          caption="%"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="avg_durasi_response"
          data-type="number"
          caption="Rata-Rata"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
        <DxColumn
          :visible="false"
          :width="150"
          alignment="center"
          data-field="total_durasi_response"
          data-type="number"
          caption="Total Durasi"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
        <DxColumn
          :visible="false"
          :width="150"
          alignment="center"
          data-field="count_durasi_response"
          data-type="number"
          caption="Jumlah Durasi"
          css-class="custom-table-column"
          cell-template="formatNumber"
          :calculate-cell-value="
            (rowData: any) => rowData.avg_durasi_response * rowData.total_durasi_response
          "
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="max_durasi_response"
          data-type="number"
          caption="Max"
          css-class="custom-table-column"
          cell-template="formatTime"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="min_durasi_response"
          data-type="number"
          caption="Min"
          css-class="custom-table-column"
          cell-template="formatTime"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_diatas_sla_response"
          data-type="number"
          caption="> SLA"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_dibawah_sla_response"
          data-type="number"
          caption="≤ SLA"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
      </DxColumn>
      <DxColumn alignment="center" caption="Penyelesaian" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="avg_durasi_recovery"
          data-type="number"
          caption="Rata-Rata"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
        <DxColumn
          :visible="false"
          :width="150"
          alignment="center"
          data-field="total_durasi_recovery"
          data-type="number"
          caption="Total Durasi"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
        <DxColumn
          :visible="false"
          :width="150"
          alignment="center"
          data-field="count_durasi_recovery"
          data-type="number"
          caption="Jumlah Durasi"
          css-class="custom-table-column"
          cell-template="formatNumber"
          :calculate-cell-value="
            (rowData: any) => rowData.avg_durasi_recovery * rowData.total_durasi_recovery
          "
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="max_durasi_recovery"
          data-type="number"
          caption="Max"
          css-class="custom-table-column"
          cell-template="formatTime"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="min_durasi_recovery"
          data-type="number"
          caption="Min"
          css-class="custom-table-column"
          cell-template="formatTime"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_diatas_sla_recovery"
          data-type="number"
          caption="> SLA"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_dibawah_sla_recovery"
          data-type="number"
          caption="≤ SLA"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
      </DxColumn>

      <DxSummary :calculate-custom-summary="calculateCustomSummary">
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="total"
          name="total"
          summary-type="custom"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="total_selesai"
          name="total_selesai"
          summary-type="custom"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="persen_selesai"
          name="persen_selesai"
          summary-type="custom"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="total_inproses"
          name="total_inproses"
          summary-type="custom"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="persen_inproses"
          name="persen_inproses"
          summary-type="custom"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="avg_durasi_response"
          name="avg_durasi_response"
          summary-type="custom"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="total_durasi_response"
          name="total_durasi_response"
          summary-type="custom"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="count_durasi_response"
          name="count_durasi_response"
          summary-type="custom"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />

        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="max_durasi_response"
          summary-type="max"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="min_durasi_response"
          summary-type="min"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="total_diatas_sla_response"
          summary-type="sum"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="total_dibawah_sla_response"
          summary-type="sum"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="avg_durasi_recovery"
          name="avg_durasi_recovery"
          summary-type="custom"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="total_durasi_recovery"
          name="total_durasi_recovery"
          summary-type="custom"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="count_durasi_recovery"
          name="count_durasi_recovery"
          summary-type="custom"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="max_durasi_recovery"
          summary-type="max"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="min_durasi_recovery"
          summary-type="min"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="total_diatas_sla_recovery"
          summary-type="sum"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          column="total_dibawah_sla_recovery"
          summary-type="sum"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
      </DxSummary>

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

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

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

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

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

      <template #formatText="{ data }">
        <p class="!text-left">
          {{ data.text }}
        </p>
      </template>
    </DxDataGrid>
  </div>

  <DetailDialog
    :open="dialogDetail"
    title="Detail Rekapitulasi Keluhan All"
    @on-close="closedialogDetail"
    :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="Dalam Proses Bidang"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_recovery"
            caption="Selesai Bidang Unit"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="durasi_response_time"
            caption="Durasi Response Time"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="durasi_recovery_time"
            caption="Durasi Recovery Time"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="status_akhir"
            caption="Status"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="idpel_nometer"
            caption="IDPEL/NO METER"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_pelapor"
            caption="Nama Pelapor"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="200"
            alignment="center"
            data-field="alamat_pelapor"
            caption="Alamat Pelapor"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="no_telp_pelapor"
            caption="No Tlp Pelapor"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="200"
            alignment="center"
            data-field="keterangan_pelapor"
            caption="Keterangan Pelapor"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_ulp"
            caption="Rayon"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="uraian"
            caption="Uraian"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="respon_pelanggan"
            caption="Respon Pelanggan"
            :allow-resizing="false"
            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 class="text-right cursor-pointer">
              {{ 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">Dalam Proses Bidang:</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">Selesai Bidang Unit:</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">IDPEL/NO METER:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.idpel_nometer" 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"
            type="textarea"
            :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">Rayon:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.nama_ulp" 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">Uraian:</h3>
          <InputText
            :readonly="true"
            type="textarea"
            :value="dataSubSelected?.uraian"
            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">Response Pelanggan:</h3>
          <InputText
            :readonly="true"
            type="textarea"
            :value="dataSubSelected?.respon_pelanggan"
            class-name="flex-1"
          />
        </div>
      </div>
    </div>
  </DetailDialog>

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

<script setup lang="ts">
import DetailDialog from '@/components/Dialogs/DetailDialog.vue'
import InputText from '@/components/InputText.vue'
import Filters from '@/components/Form/Filters.vue'
import Type3 from '@/components/Form/FiltersType/Type3.vue'
import { ref, onMounted } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxExport,
  DxPaging,
  DxPager,
  DxSearchPanel,
  DxSelection,
  DxSummary,
  DxGroupItem,
  DxGrouping
} from 'devextreme-vue/data-grid'
import { formatWaktu } from '@/components/Form/FiltersType/reference'
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 {
  exportToPDF,
  exportDetailToPDF,
  exportToXLSX,
  exportDetailToXLSX,
  exportToDOCX,
  exportDetailToDOCX
} from '@/report/Keluhan/Rekap/RKeluhan_ALL'
import BufferDialog from '@/components/Dialogs/BufferDialog.vue'
import { getDataRowGroup } from '@/utils/helper'

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 closedialogDetail = () => (dialogDetail.value = false)
const loadingData = ref(false)
const loadingSubData = ref(false)
const isDialogEnabled = ref(false)
const progressSelected = ref(0)
const groupIndex = ref(0)
const groupDialog = ref(false)
const groupData = ref<any>(null)
const reportMeta = ref({
  uid: { id: 0, name: 'Semua Unit Induk Distribusi/Wilayah' },
  up3: { id: 0, name: 'Semua Unit Pelaksanaan Pelayanan Pelanggan' },
  ulp: { id: 0, name: 'Semua Unit Layanan Pelanggan' },
  periode: ''
})
const grouping = ref<any[]>([
  {
    data: '',
    caption: 'Semua Unit'
  },
  {
    data: 'nama_regional',
    caption: 'Regional'
  },
  {
    data: 'nama_uid',
    caption: 'UID'
  },
  {
    data: 'nama_up3',
    caption: 'UP3'
  }
])

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
    }
  }
}

const onCellClicked = (e: any) => {
  if (e.rowType == 'group') {
    groupDialog.value = true
    groupIndex.value = e.row.groupIndex

    setDialogStatus(e.column.caption)
    groupData.value = getDataRowGroup(e.data)
    showDetail()
  } else {
    groupDialog.value = false
  }
}

const setDialogStatus = (column: string) => {
  if (column == 'Total' || column == 'Selesai' || column == 'InProgress') {
    isDialogEnabled.value = true
    if (column == 'Total') {
      progressSelected.value = 0
    } else if (column == 'Selesai') {
      progressSelected.value = 1
    } else {
      progressSelected.value = 2
    }
  } else {
    isDialogEnabled.value = false
  }
}

const resetData = () => {
  data.value = []
  dataSub.value = []
  dataSelected.value = null
  dataSubSelected.value = null
}

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

  var groupList: any[] = [
    {
      data: '',
      caption: 'Semua Unit'
    },
    {
      data: 'nama_regional',
      caption: 'Regional'
    },
    {
      data: 'nama_uid',
      caption: 'UID'
    },
    {
      data: 'nama_up3',
      caption: 'UP3'
    }
  ]

  if (uid?.id != 0) {
    groupList.forEach((item, index) => {
      if (item.caption == 'Semua Unit') {
        groupList.splice(index, 1)
      }
    })

    groupList.forEach((item, index) => {
      if (item.caption == 'Regional') {
        groupList.splice(index, 1)
      }
    })

    if (up3?.id != 0) {
      groupList.forEach((item, index) => {
        if (item.caption == 'UID') {
          groupList.splice(index, 1)
        }
      })

      if (ulp?.id != 0) {
        groupList.forEach((item, index) => {
          if (item.caption == 'UP3') {
            groupList.splice(index, 1)
          }
        })
      }
    }
  }
  grouping.value = groupList

  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),
    idUlp: ulp ? ulp.id : 0,
    idUid: uid ? uid.id : 0,
    idUp3: up3 ? up3.id : 0
  }

  loadingData.value = true
  await requestGraphQl(queries.keluhan.rekap.rekapKeluhanAll, query)
    .then((result) => {
      if (result.data.data != undefined) {
        data.value = result.data.data.rekapitulasiKeluhanAll
      } else {
        data.value = []
      }

      reportMeta.value = filters.value
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingData.value = false
    })
}

const getDetail = async () => {
  const dateValue = filters.value.periode.split(' s/d ')
  const selected = dataSelected.value

  var 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),
    idUlp: 0,
    idUid: 0,
    idUp3: 0,
    namaRegional: '',
    isSelesai: progressSelected.value,
    media: '',
    tanggal: '',
    namaIssuetype: '',
    namaSubissuetype: ''
  }

  if (groupDialog.value) {
    if (grouping.value[groupIndex.value].data == 'nama_regional') {
      query = {
        ...query,
        namaRegional: groupData.value?.nama_regional ? groupData.value?.nama_regional : ''
      }
    } else if (grouping.value[groupIndex.value].data == 'nama_uid') {
      query = {
        ...query,
        idUid: groupData.value?.id_uid ? groupData.value?.id_uid : 0,
        namaRegional: groupData.value?.nama_regional ? groupData.value?.nama_regional : ''
      }
    } else if (grouping.value[groupIndex.value].data == 'nama_up3') {
      query = {
        ...query,
        idUid: groupData.value?.id_uid ? groupData.value?.id_uid : 0,
        idUp3: groupData.value?.id_up3 ? groupData.value?.id_up3 : 0,
        namaRegional: groupData.value?.nama_regional ? groupData.value?.nama_regional : ''
      }
    }
  } else {
    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),
      idUlp: selected?.id_ulp ? selected?.id_ulp : 0,
      idUid: selected?.id_uid ? selected?.id_uid : 0,
      idUp3: selected?.id_up3 ? selected?.id_up3 : 0,
      namaRegional: selected?.nama_regional ? selected?.nama_regional : '',
      media: selected?.media ? selected?.media : '',
      isSelesai: progressSelected.value,
      tanggal: '',
      namaIssuetype: '',
      namaSubissuetype: ''
    }
  }

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

const dataGridRef = ref<DxDataGrid | null>(null)
const clearSelection = () => {
  try {
    dataGridRef.value?.instance?.clearSelection()
  } catch (error) {
    console.log(error)
  }
}
const showDetail = () => {
  clearSelection()
  if (isDialogEnabled.value) {
    dataSub.value = []
    dataSubSelected.value = null
    getDetail()
  }
}

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) => {
  const data = selectedRowsData[0]
  dataSubSelected.value = data
}

const filters = ref()

onMounted(() => {
  if (import.meta.env.DEV) {
    data.value = [
      {
        id: 0,
        nama_regional: 'REGIONAL JMB',
        id_uid: 101,
        nama_uid: 'DISTRIBUSI JAWA TENGAH & DIY',
        id_up3: 52150,
        nama_up3: 'UP3 MAGELANG',
        id_ulp: 52156,
        nama_ulp: 'ULP PARAKAN',
        total: 1,
        total_selesai: 0,
        persen_selesai: 0,
        total_inproses: 1,
        persen_inproses: 100,
        total_durasi_response: 6869,
        avg_durasi_response: 6869,
        min_durasi_response: 6869,
        max_durasi_response: 6869,
        total_dibawah_sla_response: 0,
        total_diatas_sla_response: 1,
        total_durasi_recovery: 6918,
        avg_durasi_recovery: 6918,
        min_durasi_recovery: 6918,
        max_durasi_recovery: 6918,
        total_dibawah_sla_recovery: 0,
        total_diatas_sla_recovery: 1
      },
      {
        id: 1,
        nama_regional: 'REGIONAL JMB',
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 154,
        nama_up3: 'UP3 SITUBONDO',
        id_ulp: 51654,
        nama_ulp: 'ULP WONOSARI',
        total: 4,
        total_selesai: 0,
        persen_selesai: 0,
        total_inproses: 4,
        persen_inproses: 100,
        total_durasi_response: 12102,
        avg_durasi_response: 4034,
        min_durasi_response: 881,
        max_durasi_response: 9125,
        total_dibawah_sla_response: 1,
        total_diatas_sla_response: 2,
        total_durasi_recovery: 169068,
        avg_durasi_recovery: 42267,
        min_durasi_recovery: 0,
        max_durasi_recovery: 70663,
        total_dibawah_sla_recovery: 1,
        total_diatas_sla_recovery: 3
      },
      {
        id: 2,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 110,
        nama_uid: 'WILAYAH ACEH',
        id_up3: 116,
        nama_up3: 'UP3 SIGLI',
        id_ulp: 11662,
        nama_ulp: 'ULP MEUREUDU',
        total: 1,
        total_selesai: 0,
        persen_selesai: 0,
        total_inproses: 1,
        persen_inproses: 100,
        total_durasi_response: 325,
        avg_durasi_response: 325,
        min_durasi_response: 325,
        max_durasi_response: 325,
        total_dibawah_sla_response: 1,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 368,
        avg_durasi_recovery: 368,
        min_durasi_recovery: 368,
        max_durasi_recovery: 368,
        total_dibawah_sla_recovery: 1,
        total_diatas_sla_recovery: 0
      },
      {
        id: 3,
        nama_regional: 'REGIONAL JMB',
        id_uid: 287,
        nama_uid: 'DISTRIBUSI BALI',
        id_up3: 329,
        nama_up3: 'UP3 BALI UTARA',
        id_ulp: 55340,
        nama_ulp: 'ULP GILIMANUK',
        total: 5,
        total_selesai: 4,
        persen_selesai: 80,
        total_inproses: 1,
        persen_inproses: 20,
        total_durasi_response: 3548,
        avg_durasi_response: 709.6,
        min_durasi_response: 302,
        max_durasi_response: 1586,
        total_dibawah_sla_response: 4,
        total_diatas_sla_response: 1,
        total_durasi_recovery: 5705,
        avg_durasi_recovery: 1141,
        min_durasi_recovery: 775,
        max_durasi_recovery: 2078,
        total_dibawah_sla_recovery: 5,
        total_diatas_sla_recovery: 0
      },
      {
        id: 4,
        nama_regional: null,
        id_uid: 0,
        nama_uid: '',
        id_up3: 0,
        nama_up3: '',
        id_ulp: 22450,
        nama_ulp: 'ULP PANGKALAN BUN',
        total: 2,
        total_selesai: 0,
        persen_selesai: 0,
        total_inproses: 2,
        persen_inproses: 100,
        total_durasi_response: 1005,
        avg_durasi_response: 1005,
        min_durasi_response: 1005,
        max_durasi_response: 1005,
        total_dibawah_sla_response: 1,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 1815,
        avg_durasi_recovery: 907.5,
        min_durasi_recovery: 650,
        max_durasi_recovery: 1165,
        total_dibawah_sla_recovery: 2,
        total_diatas_sla_recovery: 0
      },
      {
        id: 5,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 221,
        nama_uid: 'WILAYAH KALIMANTAN SELATAN DAN TENGAH',
        id_up3: 2220,
        nama_up3: 'UP3 BARABAI',
        id_ulp: 22230,
        nama_ulp: 'ULP AMUNTAI',
        total: 3,
        total_selesai: 0,
        persen_selesai: 0,
        total_inproses: 3,
        persen_inproses: 100,
        total_durasi_response: 1178,
        avg_durasi_response: 392.6666666666667,
        min_durasi_response: 155,
        max_durasi_response: 580,
        total_dibawah_sla_response: 3,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 3042,
        avg_durasi_recovery: 1014,
        min_durasi_recovery: 295,
        max_durasi_recovery: 2051,
        total_dibawah_sla_recovery: 3,
        total_diatas_sla_recovery: 0
      },
      {
        id: 6,
        nama_regional: 'REGIONAL JMB',
        id_uid: 427,
        nama_uid: 'DISTRIBUSI JAWA BARAT',
        id_up3: 546,
        nama_up3: 'UP3 TASIKMALAYA',
        id_ulp: 53231,
        nama_ulp: 'ULP CIAMIS',
        total: 4,
        total_selesai: 1,
        persen_selesai: 25,
        total_inproses: 3,
        persen_inproses: 75,
        total_durasi_response: 6122,
        avg_durasi_response: 1530.5,
        min_durasi_response: 46,
        max_durasi_response: 3024,
        total_dibawah_sla_response: 2,
        total_diatas_sla_response: 2,
        total_durasi_recovery: 6269,
        avg_durasi_recovery: 1567.25,
        min_durasi_recovery: 73,
        max_durasi_recovery: 3076,
        total_dibawah_sla_recovery: 4,
        total_diatas_sla_recovery: 0
      },
      {
        id: 7,
        nama_regional: 'REGIONAL JMB',
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 157,
        nama_up3: 'UP3 SURABAYA UTARA',
        id_ulp: 51101,
        nama_ulp: 'ULP INDRAPURA',
        total: 7,
        total_selesai: 6,
        persen_selesai: 85.71428571428571,
        total_inproses: 1,
        persen_inproses: 14.285714285714285,
        total_durasi_response: 34744,
        avg_durasi_response: 5790.666666666667,
        min_durasi_response: 55,
        max_durasi_response: 11082,
        total_dibawah_sla_response: 2,
        total_diatas_sla_response: 4,
        total_durasi_recovery: 36971,
        avg_durasi_recovery: 5281.571428571428,
        min_durasi_recovery: 149,
        max_durasi_recovery: 11304,
        total_dibawah_sla_recovery: 3,
        total_diatas_sla_recovery: 4
      },
      {
        id: 8,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 131,
        nama_uid: 'WILAYAH SUMATERA BARAT',
        id_up3: 13100,
        nama_up3: 'UP3 PADANG',
        id_ulp: 13105,
        nama_ulp: 'ULP LUBUK ALUNG',
        total: 1,
        total_selesai: 1,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 459,
        avg_durasi_response: 459,
        min_durasi_response: 459,
        max_durasi_response: 459,
        total_dibawah_sla_response: 1,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 7494,
        avg_durasi_recovery: 7494,
        min_durasi_recovery: 7494,
        max_durasi_recovery: 7494,
        total_dibawah_sla_recovery: 0,
        total_diatas_sla_recovery: 1
      },
      {
        id: 9,
        nama_regional: 'REGIONAL JMB',
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 153,
        nama_up3: 'UP3 SIDOARJO',
        id_ulp: 51182,
        nama_ulp: 'ULP PORONG',
        total: 12,
        total_selesai: 9,
        persen_selesai: 75,
        total_inproses: 3,
        persen_inproses: 25,
        total_durasi_response: 13677,
        avg_durasi_response: 1139.75,
        min_durasi_response: 42,
        max_durasi_response: 4213,
        total_dibawah_sla_response: 8,
        total_diatas_sla_response: 4,
        total_durasi_recovery: 74952,
        avg_durasi_recovery: 6246,
        min_durasi_recovery: 358,
        max_durasi_recovery: 30185,
        total_dibawah_sla_recovery: 6,
        total_diatas_sla_recovery: 6
      },
      {
        id: 10,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 110,
        nama_uid: 'WILAYAH ACEH',
        id_up3: 111,
        nama_up3: 'UP3 BANDA ACEH',
        id_ulp: 11110,
        nama_ulp: 'ULP KOTA MERDUATI',
        total: 2,
        total_selesai: 1,
        persen_selesai: 50,
        total_inproses: 1,
        persen_inproses: 50,
        total_durasi_response: 866,
        avg_durasi_response: 433,
        min_durasi_response: 323,
        max_durasi_response: 543,
        total_dibawah_sla_response: 2,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 3186,
        avg_durasi_recovery: 1593,
        min_durasi_recovery: 917,
        max_durasi_recovery: 2269,
        total_dibawah_sla_recovery: 2,
        total_diatas_sla_recovery: 0
      },
      {
        id: 11,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 110,
        nama_uid: 'WILAYAH ACEH',
        id_up3: 112,
        nama_up3: 'UP3 LHOKSEUMAWE',
        id_ulp: 11220,
        nama_ulp: 'ULP LHOKSEUMAWE',
        total: 3,
        total_selesai: 0,
        persen_selesai: 0,
        total_inproses: 3,
        persen_inproses: 100,
        total_durasi_response: 6020,
        avg_durasi_response: 2006.6666666666667,
        min_durasi_response: 270,
        max_durasi_response: 3526,
        total_dibawah_sla_response: 1,
        total_diatas_sla_response: 2,
        total_durasi_recovery: 6125,
        avg_durasi_recovery: 2041.6666666666667,
        min_durasi_recovery: 321,
        max_durasi_recovery: 3553,
        total_dibawah_sla_recovery: 3,
        total_diatas_sla_recovery: 0
      },
      {
        id: 12,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 171,
        nama_uid: 'DISTRIBUSI LAMPUNG',
        id_up3: 17171,
        nama_up3: 'UP3 TANJUNGKARANG',
        id_ulp: 17180,
        nama_ulp: 'ULP TELUK BETUNG',
        total: 7,
        total_selesai: 2,
        persen_selesai: 28.57142857142857,
        total_inproses: 5,
        persen_inproses: 71.42857142857143,
        total_durasi_response: 2328,
        avg_durasi_response: 388,
        min_durasi_response: 92,
        max_durasi_response: 866,
        total_dibawah_sla_response: 6,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 3159,
        avg_durasi_recovery: 451.2857142857143,
        min_durasi_recovery: 169,
        max_durasi_recovery: 917,
        total_dibawah_sla_recovery: 7,
        total_diatas_sla_recovery: 0
      },
      {
        id: 13,
        nama_regional: 'REGIONAL JMB',
        id_uid: 427,
        nama_uid: 'DISTRIBUSI JAWA BARAT',
        id_up3: 540,
        nama_up3: 'UP3 GARUT',
        id_ulp: 53293,
        nama_ulp: 'ULP LELES',
        total: 2,
        total_selesai: 1,
        persen_selesai: 50,
        total_inproses: 1,
        persen_inproses: 50,
        total_durasi_response: 1870,
        avg_durasi_response: 935,
        min_durasi_response: 310,
        max_durasi_response: 1560,
        total_dibawah_sla_response: 1,
        total_diatas_sla_response: 1,
        total_durasi_recovery: 5002,
        avg_durasi_recovery: 2501,
        min_durasi_recovery: 1592,
        max_durasi_recovery: 3410,
        total_dibawah_sla_recovery: 2,
        total_diatas_sla_recovery: 0
      },
      {
        id: 14,
        nama_regional: 'REGIONAL SULMAPANA',
        id_uid: 32,
        nama_uid: 'WILAYAH SULAWESI SELATAN, TENGGARA DAN BARAT',
        id_up3: 32200,
        nama_up3: 'UP3 WATAMPONE',
        id_ulp: 32260,
        nama_ulp: 'ULP ULOE',
        total: 1,
        total_selesai: 0,
        persen_selesai: 0,
        total_inproses: 1,
        persen_inproses: 100,
        total_durasi_response: 2074,
        avg_durasi_response: 2074,
        min_durasi_response: 2074,
        max_durasi_response: 2074,
        total_dibawah_sla_response: 0,
        total_diatas_sla_response: 1,
        total_durasi_recovery: 3031,
        avg_durasi_recovery: 3031,
        min_durasi_recovery: 3031,
        max_durasi_recovery: 3031,
        total_dibawah_sla_recovery: 1,
        total_diatas_sla_recovery: 0
      }
    ]
  }
})
</script>
