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

  <div id="data">
    <DxDataGrid
      ref="dataGridRef"
      :allow-column-reordering="true"
      class="max-h-[calc(100vh-140px)] mb-10"
      :data-source="data"
      :show-column-lines="true"
      :show-row-lines="false"
      :show-borders="true"
      :row-alternation-enabled="true"
      :hover-state-enabled="true"
      @selection-changed="onDataSelectionChanged"
      @exporting="onExporting"
      :allow-column-resizing="true"
      column-resizing-mode="widget"
      :word-wrap-enabled="true"
    >
      <DxGrouping expand-mode="rowClick" :auto-expand-all="false" />
      <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
        alignment="center"
        :min-width="170"
        data-type="text"
        data-field="nama_regional"
        caption="Regional"
        css-class="custom-table-column"
        :group-index="0"
        name="namaRegional"
      />
      <DxColumn
        alignment="center"
        :min-width="170"
        data-type="text"
        data-field="id_uid"
        caption="UID"
        css-class="custom-table-column"
        :group-index="1"
        name="namaUID"
        :calculate-group-value="(rowData: any) => rowData.nama_uid"
      />
      <DxColumn
        alignment="center"
        :min-width="170"
        data-type="text"
        data-field="id_up3"
        caption="UP3"
        css-class="custom-table-column"
        :group-index="1"
        name="namaUID"
        :calculate-group-value="(rowData: any) => rowData.nama_up3"
      />
      <DxColumn
        alignment="center"
        :min-width="170"
        data-type="text"
        data-field="nama_ulp"
        caption="Nama Unit"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        alignment="center"
        caption="Jumlah Dispatching Time Gangguan"
        css-class="custom-table-column"
      >
        <DxColumn alignment="center" caption="MoM" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="mom_bulan_kemarin"
            data-type="number"
            :caption="`${getMonthName(lastMonth)} ${lastYearMoM}`"
            css-class="custom-table-column"
            cell-template="formatNumberMomLastMonthLastYear"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="mom_bulan_ini"
            data-type="number"
            :caption="`${getMonthName(currentMonth)} ${currentYear}`"
            css-class="custom-table-column"
            cell-template="formatNumberMomCurrentMonthCurrentYear"
          />
          <DxColumn
            :width="70"
            alignment="center"
            data-field="persen_mom"
            data-type="number"
            caption="%"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
        <DxColumn alignment="center" caption="YoY" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="yoy_tahun_kemarin"
            data-type="number"
            :caption="`s.d ${getMonthName(currentMonth)} ${lastYear}`"
            css-class="custom-table-column"
            cell-template="formatNumberYoyCurrentMonthLastYear"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="yoy_tahun_ini"
            data-type="number"
            :caption="`s.d ${getMonthName(currentMonth)} ${currentYear}`"
            css-class="custom-table-column"
            cell-template="formatNumberYoyCurrentMonthCurrentYear"
          />
          <DxColumn
            :width="70"
            alignment="center"
            data-field="persen_yoy"
            data-type="number"
            caption="%"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
      </DxColumn>

      <DxSummary>
        <DxTotalItem
          summary-type="sum"
          display-format="Total"
          show-in-column="nama_ulp"
          css-class="text-white !text-left"
        />
        <DxTotalItem
          column="mom_bulan_kemarin"
          summary-type="sum"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="mom_bulan_ini"
          summary-type="sum"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="persen_mom"
          summary-type="avg"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
        <DxTotalItem
          column="yoy_tahun_kemarin"
          summary-type="sum"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="yoy_tahun_ini"
          summary-type="sum"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="persen_yoy"
          summary-type="avg"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />

        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="sum"
          display-format="{0}"
          show-in-column="mom_bulan_kemarin"
          column="mom_bulan_kemarin"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="sum"
          show-in-column="mom_bulan_ini"
          column="mom_bulan_ini"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="sum"
          show-in-column="persen_mom"
          column="persen_mom"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="sum"
          show-in-column="yoy_tahun_kemarin"
          column="yoy_tahun_kemarin"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="sum"
          show-in-column="yoy_tahun_ini"
          column="yoy_tahun_ini"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="sum"
          show-in-column="persen_yoy"
          column="persen_yoy"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
      </DxSummary>

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

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

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

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

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

      <template #formatText="{ data }">
        <p class="!text-left cursor-pointer" @click="setRequirements('', 0, 0)">
          {{ data.text }}
        </p>
      </template>
    </DxDataGrid>
  </div>

  <DetailDialog
    :open="dialogDetail"
    title="Detail Dispatching Time Gangguan"
    @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="nama_ulp"
            caption="ULP"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <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/Jam Lapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_response"
            caption="Tgl/Jam Datang"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_recovery"
            caption="Tgl/Jam Nyala"
            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=""
            caption="Durasi Penugasan Regu"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field=""
            caption="Durasi Perjalanan Regu"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field=""
            caption="Dispatch Oleh"
            :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="200"
            alignment="center"
            data-field=""
            caption="Sumber Lapor"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="200"
            alignment="center"
            data-field=""
            caption="Diselesaikan Oleh"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="status_akhir"
            caption="Status"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="200"
            alignment="center"
            data-field=""
            caption="Referensi Marking"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="200"
            alignment="center"
            data-field=""
            caption="Kode Gangguan"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="200"
            alignment="center"
            data-field=""
            caption="Janis Gangguan"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="200"
            alignment="center"
            data-field=""
            caption="Tindakan"
            :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">ULP:</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">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/Jam 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/Jam 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/Jam 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">Durasi Penugasan Regu:</h3>
          <InputText :readonly="true" value="" 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 Perjalanan Regu:</h3>
          <InputText :readonly="true" value="" 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">Dispatch Oleh:</h3>
          <InputText :readonly="true" value="" 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">Sumber Lapor:</h3>
          <InputText :readonly="true" value="" 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">Diselesaikan Oleh:</h3>
          <InputText :readonly="true" value="" 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="" 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">Kode Gangguan:</h3>
          <InputText :readonly="true" value="" 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">Janis Gangguan:</h3>
          <InputText :readonly="true" value="" 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="" 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 Type2 from '@/components/Form/FiltersType/Type2.vue'
import { onMounted, ref, watch } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxGroupItem,
  DxGrouping,
  DxLoadPanel,
  DxPager,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection,
  DxSummary,
  DxTotalItem
} from 'devextreme-vue/data-grid'
import { getMonthName } from '@/utils/texts'
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 { formatWaktu } from '@/components/Form/FiltersType/reference'
import InputText from '@/components/InputText.vue'
import BufferDialog from '@/components/Dialogs/BufferDialog.vue'
import {
  exportToPDF,
  exportToXLSX,
  exportDetailToPDF,
  exportDetailToXLSX
} from '@/report/Monalisa/Gangguan/Rekap/MonalisaGR_DispatchingTimeGangguan'

const client = apolloClient()
provideApolloClient(client)
const lastMonth = ref(new Date().getMonth() == 1 ? 12 : new Date().getMonth() - 1)
const lastYearMoM = ref(
  new Date().getMonth() == 1 ? new Date().getFullYear() - 1 : new Date().getFullYear()
)
const currentYear = ref(new Date().getFullYear())
const currentMonth = ref(new Date().getMonth())
const lastYear = ref(currentYear.value - 1)
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 dataType = ref('')
const dataYear = ref(new Date().getFullYear())
const dataMonth = ref(new Date().getMonth())
const reportMeta = ref({
  regional: { id: 0, name: 'Semua Regional' },
  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' },
  bulan: { id: new Date().getMonth(), name: getMonthName(new Date().getMonth()) },
  tahun: { id: new Date().getFullYear(), name: new Date().getFullYear().toString() },
  periode: '',
  lastMonth: new Date().getMonth() == 1 ? 12 : new Date().getMonth() - 1,
  lastYearMoM: new Date().getMonth() == 1 ? new Date().getFullYear() - 1 : new Date().getFullYear(),
  currentMonth: new Date().getMonth(),
  currentYear: new Date().getFullYear(),
  lastYear: new Date().getFullYear() - 1
})

const setRequirements = (type: string, month: number, year: number) => {
  dataType.value = type
  dataYear.value = year
  dataMonth.value = month
}

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

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

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

const filterData = async (params: any) => {
  resetData()
  const { regional, ulp, uid, up3, bulan, tahun } = params
  const query = {
    namaRegional: regional.name == 'Semua Regional' ? '' : regional.name,
    idUid: uid ? uid.id : 0,
    idUp3: up3 ? up3.id : 0,
    idUlp: ulp ? ulp.id : 0,
    bulan: bulan ? bulan.id : currentMonth.value,
    tahun: bulan ? tahun.id : currentYear.value
  }
  loadingData.value = true
  await requestGraphQl(queries.monalisa.gangguan.rekap.dispatchingTimeGangguan, query)
    .then((result) => {
      if (result.data.data != undefined) {
        data.value = result.data.data.monalisaDispatchingTimeGangguan
      } else {
        data.value = []
      }

      reportMeta.value = {
        regional: regional,
        uid: uid,
        up3: up3,
        ulp: ulp,
        bulan: bulan,
        tahun: tahun,
        periode: `${bulan.name} ${tahun.name}`,
        lastMonth: lastMonth.value,
        lastYearMoM: lastYearMoM.value,
        currentMonth: currentMonth.value,
        currentYear: currentYear.value,
        lastYear: lastYear.value
      }
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingData.value = false
    })
  lastMonth.value = bulan.id == 1 ? 12 : bulan.id - 1
  lastYearMoM.value = bulan.id == 1 ? tahun.id - 1 : tahun.id
  currentMonth.value = bulan.id
  currentYear.value = tahun.id
  lastYear.value = tahun.id - 1
}

const getDetail = async () => {
  const selected = dataSelected.value

  const query = {
    bulan: dataMonth.value,
    tahun: dataYear.value,
    idUlp: selected?.id_ulp ? selected?.id_ulp : 0,
    idUid: selected?.id_uid ? selected?.id_uid : 0,
    idUp3: selected?.id_up3 ? selected?.id_up3 : 0
  }

  loadingSubData.value = true
  await requestGraphQl(
    dataType.value == 'yoy'
      ? queries.monalisa.gangguan.rekap.dispatchingTimeGangguanDetailYoy
      : queries.monalisa.gangguan.rekap.dispatchingTimeGangguanDetailMom,
    query
  )
    .then((result) => {
      if (result.data.data != undefined) {
        if (dataType.value == 'yoy') {
          dataSub.value = result.data.data.detailMonalisaDispatchingTimeGangguanYoy
        } else {
          dataSub.value = result.data.data.detailMonalisaDispatchingTimeGangguanMoM
        }
      } 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()
  dataSubSelected.value = null
  if (dataType.value == 'yoy' || dataType.value == 'mom') {
    getDetail()
  }
}
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 SUMKAL',
        id_uid: 230,
        nama_uid: 'WILAYAH KALIMANTAN TIMUR',
        id_up3: 231,
        nama_up3: 'UP3 SAMARINDA',
        id_ulp: 23156,
        nama_ulp: 'ULP SAMARINDA ULU',
        mom_bulan_ini: -213179,
        mom_bulan_kemarin: 673,
        persen_mom: 31775.994473750405,
        yoy_tahun_ini: 2069,
        yoy_tahun_kemarin: 1841,
        persen_yoy: -12.38457360130364
      },
      {
        id: 1,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 183,
        nama_up3: 'UP3 TANJUNGPINANG',
        id_ulp: 18302,
        nama_ulp: 'ULP KIJANG',
        mom_bulan_ini: -114,
        mom_bulan_kemarin: 373,
        persen_mom: 130.77740603697222,
        yoy_tahun_ini: 1324,
        yoy_tahun_kemarin: 1931,
        persen_yoy: 31.434489901605385
      },
      {
        id: 2,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 182,
        nama_up3: 'UP3 DUMAI',
        id_ulp: 18240,
        nama_ulp: 'ULP SELATPANJANG',
        mom_bulan_ini: -869,
        mom_bulan_kemarin: 493,
        persen_mom: 276.27086351782094,
        yoy_tahun_ini: 1454,
        yoy_tahun_kemarin: 702,
        persen_yoy: -107.12250712250713
      },
      {
        id: 3,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 120,
        nama_uid: 'WILAYAH SUMATERA UTARA',
        id_up3: 12400,
        nama_up3: 'UP3 PADANG SIDIMPUAN',
        id_ulp: 12415,
        nama_ulp: 'ULP NATAL',
        mom_bulan_ini: -16,
        mom_bulan_kemarin: 184,
        persen_mom: 108.95582431788799,
        yoy_tahun_ini: 426,
        yoy_tahun_kemarin: 536,
        persen_yoy: 20.522388059701495
      },
      {
        id: 4,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 230,
        nama_uid: 'WILAYAH KALIMANTAN TIMUR',
        id_up3: 231,
        nama_up3: 'UP3 SAMARINDA',
        id_ulp: 23102,
        nama_ulp: 'ULP SAMARINDA SEBERANG',
        mom_bulan_ini: -295198,
        mom_bulan_kemarin: 1025,
        persen_mom: 28899.899321562316,
        yoy_tahun_ini: 3193,
        yoy_tahun_kemarin: 2649,
        persen_yoy: -20.53605134012835
      },
      {
        id: 5,
        nama_regional: 'REGIONAL SULMAPANA',
        id_uid: 32,
        nama_uid: 'WILAYAH SULAWESI SELATAN, TENGGARA DAN BARAT',
        id_up3: 32200,
        nama_up3: 'UP3 WATAMPONE',
        id_ulp: 32240,
        nama_ulp: 'ULP SENGKANG',
        mom_bulan_ini: -107,
        mom_bulan_kemarin: 606,
        persen_mom: 117.772648051322,
        yoy_tahun_ini: 2082,
        yoy_tahun_kemarin: 1190,
        persen_yoy: -74.95798319327731
      },
      {
        id: 6,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 181,
        nama_up3: 'UP3 PEKANBARU',
        id_ulp: 18150,
        nama_ulp: 'ULP PERAWANG',
        mom_bulan_ini: -407,
        mom_bulan_kemarin: 916,
        persen_mom: 144.4547767778033,
        yoy_tahun_ini: 2897,
        yoy_tahun_kemarin: 2706,
        persen_yoy: -7.058388765705839
      },
      {
        id: 7,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 183,
        nama_up3: 'UP3 TANJUNGPINANG',
        id_ulp: 18306,
        nama_ulp: 'ULP TANJUNG BATU',
        mom_bulan_ini: -539,
        mom_bulan_kemarin: 69,
        persen_mom: 882.5544353427151,
        yoy_tahun_ini: 252,
        yoy_tahun_kemarin: 322,
        persen_yoy: 21.73913043478261
      },
      {
        id: 8,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 184,
        nama_up3: 'UP3 RENGAT',
        id_ulp: 18430,
        nama_ulp: 'ULP KUALA ENOK',
        mom_bulan_ini: -169,
        mom_bulan_kemarin: 188,
        persen_mom: 190.35948625202792,
        yoy_tahun_ini: 591,
        yoy_tahun_kemarin: 2752,
        persen_yoy: 78.52470930232558
      },
      {
        id: 9,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 181,
        nama_up3: 'UP3 PEKANBARU',
        id_ulp: 18170,
        nama_ulp: 'ULP SIAK SRI INDRAPURA',
        mom_bulan_ini: -11,
        mom_bulan_kemarin: 391,
        persen_mom: 102.89304140589162,
        yoy_tahun_ini: 1163,
        yoy_tahun_kemarin: 2109,
        persen_yoy: 44.85538169748696
      },
      {
        id: 10,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 182,
        nama_up3: 'UP3 DUMAI',
        id_ulp: 18260,
        nama_ulp: 'ULP BAGAN BATU',
        mom_bulan_ini: -600,
        mom_bulan_kemarin: 964,
        persen_mom: 162.33329138602699,
        yoy_tahun_ini: 3581,
        yoy_tahun_kemarin: 2965,
        persen_yoy: -20.775716694772346
      },
      {
        id: 11,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 230,
        nama_uid: 'WILAYAH KALIMANTAN TIMUR',
        id_up3: 231,
        nama_up3: 'UP3 SAMARINDA',
        id_ulp: 23112,
        nama_ulp: 'ULP TENGGARONG',
        mom_bulan_ini: -4524,
        mom_bulan_kemarin: 981,
        persen_mom: 561.2414600051343,
        yoy_tahun_ini: 3234,
        yoy_tahun_kemarin: 3514,
        persen_yoy: 7.968127490039841
      },
      {
        id: 12,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 183,
        nama_up3: 'UP3 TANJUNGPINANG',
        id_ulp: 18303,
        nama_ulp: 'ULP TANJUNG UBAN',
        mom_bulan_ini: -186,
        mom_bulan_kemarin: 191,
        persen_mom: 197.5691701222732,
        yoy_tahun_ini: 615,
        yoy_tahun_kemarin: 1058,
        persen_yoy: 41.87145557655955
      },
      {
        id: 13,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 184,
        nama_up3: 'UP3 RENGAT',
        id_ulp: 18410,
        nama_ulp: 'ULP RENGAT KOTA',
        mom_bulan_ini: -476,
        mom_bulan_kemarin: 955,
        persen_mom: 149.94027462127963,
        yoy_tahun_ini: 2931,
        yoy_tahun_kemarin: 4545,
        persen_yoy: 35.51155115511551
      },
      {
        id: 14,
        nama_regional: 'REGIONAL JMB',
        id_uid: 101,
        nama_uid: 'DISTRIBUSI JAWA TENGAH & DIY',
        id_up3: 52200,
        nama_up3: 'UP3 PURWOKERTO',
        id_ulp: 52201,
        nama_ulp: 'ULP PURWOKERTO KOTA',
        mom_bulan_ini: -63,
        mom_bulan_kemarin: 3642,
        persen_mom: 101.7401502360751,
        yoy_tahun_ini: 11511,
        yoy_tahun_kemarin: 14451,
        persen_yoy: 20.344612829561967
      },
      {
        id: 15,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 181,
        nama_up3: 'UP3 PEKANBARU',
        id_ulp: 18111,
        nama_ulp: 'ULP PEKANBARU KOTA BARAT',
        mom_bulan_ini: -1097,
        mom_bulan_kemarin: 1964,
        persen_mom: 155.88116671737166,
        yoy_tahun_ini: 6506,
        yoy_tahun_kemarin: 5316,
        persen_yoy: -22.385252069224983
      }
    ]
  }
})
</script>
