<template>
  <div class="mt-4 lg:mt-6 max-w-7xl">
    <h1 class="text-xl font-medium md:text-2xl text-dark">Laporan Pengaduan Total</h1>
  </div>
  <DxDataGrid
    @cell-click="onCellClicked"
    ref="dataGridRef"
    :data-source="data"
    v-if="loading == false"
    :allow-column-reordering="true"
    class="max-h-[calc(100vh-140px)] mb-10"
    :show-column-lines="true"
    :show-row-lines="false"
    :show-borders="true"
    :row-alternation-enabled="true"
    :hover-state-enabled="true"
    @selection-changed="onDataSelectionChanged"
    :column-width="100"
    @exporting="onExporting"
    :allow-column-resizing="true"
    column-resizing-mode="widget"
    :word-wrap-enabled="true"
  >
    <DxGrouping :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
      :width="170"
      alignment="center"
      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="Total WO" css-class="custom-table-column">
      <DxColumn alignment="center" caption="CC 123" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="wo_cc123"
          data-type="number"
          caption="a"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
      </DxColumn>
      <DxColumn alignment="center" caption="PLN Mobile" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="wo_pln_mobile"
          data-type="number"
          caption="b"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
      </DxColumn>
      <DxColumn alignment="center" caption="Loket" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="wo_loket"
          data-type="number"
          caption="c"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
      </DxColumn>
      <DxColumn alignment="center" caption="Lainnya" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="wo_lainnya"
          data-type="number"
          caption="d"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
      </DxColumn>
      <DxColumn alignment="center" caption="Total" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="wo_total"
          data-type="number"
          caption="e=a+b+c+d"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
      </DxColumn>
    </DxColumn>
    <DxColumn
      alignment="center"
      caption="Total Pengaduan Yang Diselesaikan Secara Anomali"
      css-class="custom-table-column"
    >
      <DxColumn alignment="center" caption="PLN Mobile" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="anomali_pln_mobile"
          data-type="number"
          caption="f"
          css-class="custom-table-column"
          cell-template="formatNumberPLNMobile"
        />
      </DxColumn>
      <DxColumn alignment="center" caption="CC 123" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="anomali_cc123"
          data-type="number"
          caption="g"
          css-class="custom-table-column"
          cell-template="formatNumberCC"
        />
      </DxColumn>
      <DxColumn alignment="center" caption="Total" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_anomali"
          data-type="number"
          caption="h=f+g"
          css-class="custom-table-column"
          cell-template="formatNumberTotal"
        />
      </DxColumn>
    </DxColumn>

    <DxColumn
      alignment="center"
      caption="% Pengaduan Yang Diselesaikan Secara Anomali"
      css-class="custom-table-column"
    >
      <DxColumn alignment="center" caption="PLN Mobile" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="persen_anomali_pln_mobile"
          data-type="number"
          caption="i=f/e"
          css-class="custom-table-column"
          cell-template="formatPercentage"
        />
      </DxColumn>
      <DxColumn alignment="center" caption="CC 123" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="persen_anomali_cc123"
          data-type="number"
          caption="j=g/e"
          css-class="custom-table-column"
          cell-template="formatPercentage"
        />
      </DxColumn>
      <DxColumn alignment="center" caption="Total" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_persen_anomali"
          data-type="number"
          caption="k=i+j"
          css-class="custom-table-column"
          cell-template="formatPercentage"
        />
      </DxColumn>
    </DxColumn>

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

    <template #formatNumberCC="{ data }">
      <p class="text-right cursor-pointer" @click="setParameterRequest('Call PLN 123')">
        {{
          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="setParameterRequest('')">
        {{
          isNumber(data.text)
            ? data.column.caption == '%'
              ? formatPercentage(data.text)
              : formatNumber(data.text)
            : data.text
        }}
      </p>
    </template>

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

    <template #formatPercentage="{ data }">
      <p class="text-right cursor-pointer" @click="setParameterRequest(null)">
        {{ isNumber(data.text) ? formatPercentage(data.text) : data.text }}
      </p>
    </template>

    <template #formatText="{ data }">
      <p class="text-left cursor-pointer" @click="setParameterRequest(null)">
        {{ data.text }}
      </p>
    </template>

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

    <DxSummary :calculate-custom-summary="calculateCustomSummary">
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="wo_cc123"
        name="wo_cc123"
        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="wo_pln_mobile"
        name="wo_pln_mobile"
        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="wo_loket"
        name="wo_loket"
        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="wo_lainnya"
        name="wo_lainnya"
        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="wo_total"
        name="wo_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="anomali_pln_mobile"
        summary-type="custom"
        name="anomali_pln_mobile"
        css-class="!text-right cursor-pointer"
        :customize-text="(e: any) => formatNumber(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="anomali_cc123"
        summary-type="custom"
        name="anomali_cc123"
        css-class="!text-right cursor-pointer"
        :customize-text="(e: any) => formatNumber(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="total_anomali"
        summary-type="custom"
        name="total_anomali"
        css-class="!text-right cursor-pointer"
        :customize-text="(e: any) => formatNumber(e.value)"
      />

      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="persen_anomali_pln_mobile"
        summary-type="custom"
        css-class="!text-right"
        name="persen_anomali_pln_mobile"
        :customize-text="(e: any) => formatPercentage(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="persen_anomali_cc123"
        summary-type="custom"
        css-class="!text-right"
        name="persen_anomali_cc123"
        :customize-text="(e: any) => formatPercentage(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="total_persen_anomali"
        summary-type="custom"
        css-class="!text-right"
        name="total_persen_anomali"
        :customize-text="(e: any) => formatPercentage(e.value)"
      />
    </DxSummary>
  </DxDataGrid>

  <DetailDialog
    :open="dialogDetail"
    title="Daftar Detail Anomali Penanganan Pengaduan"
    @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: any) => i == item) + 1"
            data-type="number"
            caption="No"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_uid"
            caption="UIW/D"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_up3"
            caption="UP3"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_ulp"
            caption="Rayon"
            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="referensi_marking"
            caption="No Laporan Referensi"
            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"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_recovery"
            caption="Selesai Bidang Unit"
            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="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="idpel_nometer"
            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="150"
            alignment="center"
            data-field="keterangan_pelapor"
            caption="Keterangan Pelapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="uraian"
            caption="Uraian"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="respon_pelanggan"
            caption="Response Pelanggan"
            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">UIW/D:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.nama_uid" 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">UP3:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.nama_up3" 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">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">No Laporan Referensi:</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">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"
            type="textarea"
            :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">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="loading || loadingSubData" />
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxGroupItem,
  DxGrouping,
  DxPager,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection,
  DxSummary
} from 'devextreme-vue/data-grid'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'
import { formatWaktu } from '@/components/Form/FiltersType/reference'
import { queries, requestGraphQl } from '@/utils/api/api.graphql'
import DetailDialog from '@/components/Dialogs/DetailDialog.vue'
import InputText from '@/components/InputText.vue'
import {
  exportToPDF,
  exportToXLSX,
  exportDetailToPDF,
  exportDetailToXLSX,
  exportToDOCX,
  exportDetailToDOCX
} from '@/report/Anomali/Keluhan/Anomali_LAPPKU_LPT'
import BufferDialog from '@/components/Dialogs/BufferDialog.vue'
import { getDataRowGroup } from '@/utils/helper'

const position = { of: '#data' }
const showIndicator = ref(true)
const shading = ref(true)
const showPane = ref(true)
const props = defineProps({
  data: Array as () => any[],
  filters: Object as () => any,
  loading: {
    type: Boolean,
    default: false
  },
  grouping: {
    type: Array as () => any[],
    default: []
  }
})
const filters = ref<any>(computed(() => props.filters))
const data = computed(() => props.data)
const dataSub = ref<any[]>([])
const dataSelected = ref<any>(null)
const dataSubSelected = ref<any>(null)
const dialogDetail = ref(false)
const closedialogDetail = () => (dialogDetail.value = false)
const loadingData = ref(false)
const loadingSubData = ref(false)
const isDialogEnabled = ref(false)
const mediaSelected = ref<any>(null)
const reportMeta = ref<any>(computed(() => props.filters))
const groupDialog = ref(false)
const groupData = ref<any>(null)
const groupIndex = ref(0)

const setParameterRequest = (media: any) => {
  mediaSelected.value = media

  if (media != null) {
    isDialogEnabled.value = true
  } else {
    isDialogEnabled.value = false
  }
}

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

    if (e.column.dataField == 'anomali_pln_mobile') {
      setParameterRequest('PLN Mobile')
    } else if (e.column.dataField == 'anomali_cc123') {
      setParameterRequest('Call PLN 123')
    } else if (e.column.dataField == 'total_anomali') {
      setParameterRequest('')
    } else {
      setParameterRequest(null)
    }
    groupData.value = getDataRowGroup(e.data)
    showDetail()
  } else {
    groupDialog.value = false
  }
}

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

const getDetail = async () => {
  resetData()
  const { ulp, uid, up3, jenisLaporan, periode } = filters.value
  console.table('LAPPGU', jenisLaporan)
  console.log('Media', mediaSelected.value)
  console.log('periode', periode)

  const dateValue = periode.split(' s/d ')
  const selected = dataSelected.value
  let 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: '',
    media: mediaSelected.value
  }

  if (groupDialog.value) {
    if (props.grouping[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 (props.grouping[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: mediaSelected.value
    }
  }

  loadingSubData.value = true
  await requestGraphQl(
    jenisLaporan.name == 'Laporan Berulang Unit'
      ? queries.anomali.keluhan.unitBerulangDetail
      : jenisLaporan.name == 'Laporan Rating Negatif'
        ? queries.anomali.keluhan.unitRatingNegatifDetail
        : queries.anomali.keluhan.unitSkipStepDetail,
    query
  )
    .then((result) => {
      if (result.data.data != undefined) {
        if (jenisLaporan.name == 'Laporan Berulang Unit') {
          dataSub.value =
            result.data.data.detailAnomaliLaporanPenangananPengaduanKeluhanUnitBerulang
        } else if (jenisLaporan.name == 'Laporan Rating Negatif') {
          dataSub.value =
            result.data.data.detailAnomaliLaporanPenangananPengaduanKeluhanUnitRatingNegatif
        } else {
          dataSub.value =
            result.data.data.detailAnomaliLaporanPenangananPengaduanKeluhanUnitSkipStep
        }
      } else {
        dataSub.value = []
      }
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingSubData.value = false
      dialogDetail.value = true
    })
}

let wo_cc123 = 0
let wo_pln_mobile = 0
let wo_loket = 0
let wo_lainnya = 0
let wo_total = 0
let anomali_pln_mobile = 0
let anomali_cc123 = 0
let total_anomali = 0
let persen_anomali_pln_mobile = 0
let persen_anomali_cc123 = 0
let total_persen_anomali = 0

const calculateCustomSummary = (options: any) => {
  if (options.name === 'wo_cc123') {
    if (options.summaryProcess === 'calculate') {
      wo_cc123 += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = wo_cc123
    }
  }

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

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

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

  if (options.name === 'wo_total') {
    if (options.summaryProcess === 'start') {
      wo_cc123 = 0
      wo_pln_mobile = 0
      wo_loket = 0
      wo_lainnya = 0
    } else if (options.summaryProcess === 'calculate') {
      wo_total = wo_cc123 + wo_pln_mobile + wo_loket + wo_lainnya
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = wo_cc123 + wo_pln_mobile + wo_loket + wo_lainnya
    }
  }

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

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

  if (options.name === 'total_anomali') {
    if (options.summaryProcess === 'start') {
      anomali_pln_mobile = 0
      anomali_cc123 = 0
    } else if (options.summaryProcess === 'calculate') {
      total_anomali = anomali_pln_mobile + anomali_cc123
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = anomali_pln_mobile + anomali_cc123
    }
  }

  if (options.name === 'persen_anomali_pln_mobile') {
    if (options.summaryProcess === 'start') {
      anomali_pln_mobile = 0
      wo_total = 0
    } else if (options.summaryProcess === 'calculate') {
      persen_anomali_pln_mobile =
        !isFinite(anomali_pln_mobile / wo_total) || anomali_pln_mobile == 0
          ? 0
          : (anomali_pln_mobile / wo_total) * 100
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue =
        !isFinite(anomali_pln_mobile / wo_total) || anomali_pln_mobile == 0
          ? 0
          : (anomali_pln_mobile / wo_total) * 100
    }
  }

  if (options.name === 'persen_anomali_cc123') {
    if (options.summaryProcess === 'start') {
      anomali_cc123 = 0
      wo_total = 0
    } else if (options.summaryProcess === 'calculate') {
      persen_anomali_cc123 =
        !isFinite(anomali_cc123 / wo_total) || anomali_cc123 == 0
          ? 0
          : (anomali_cc123 / wo_total) * 100
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue =
        !isFinite(anomali_cc123 / wo_total) || anomali_cc123 == 0
          ? 0
          : (anomali_cc123 / wo_total) * 100
    }
  }

  if (options.name === 'total_persen_anomali') {
    if (options.summaryProcess === 'start') {
      persen_anomali_pln_mobile = 0
      persen_anomali_cc123 = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = persen_anomali_pln_mobile + persen_anomali_cc123
    }
  }
}

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 dataGridRef = ref<DxDataGrid | null>(null)
const clearSelection = () => {
  try {
    dataGridRef.value?.instance?.clearSelection()
  } catch (error) {
    console.log(error)
  }
}

const showDetail = () => {
  clearSelection()
  dataSub.value = []
  dataSubSelected.value = null
  if (isDialogEnabled.value) {
    getDetail()
  }
}

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

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