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

  <div id="data">
    <DxDataGrid
      ref="dataGridRef"
      :allow-column-reordering="true"
      class="max-h-[calc(100vh-140px)] mb-10"
      :data-source="data"
      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"
    >
      <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="50"
        alignment="center"
        caption="NO"
        data-type="number"
        :calculate-display-value="(item: any) => data.findIndex((i) => i == item) + 1"
        css-class="custom-table-column"
        cell-template="formatNumber"
      />
      <DxColumn
        :width="150"
        alignment="center"
        data-field="kode_regu"
        caption="Kode"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="200"
        alignment="center"
        data-field="nama_regu"
        caption="Nama Regu"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn alignment="center" caption="Laporan" css-class="custom-table-column">
        <DxColumn
          alignment="center"
          data-field="total"
          data-type="number"
          caption="Total"
          css-class="custom-table-column"
          cell-template="formatNumberLaporanTotal"
        />
        <DxColumn alignment="center" caption="Belum Selesai" css-class="custom-table-column">
          <DxColumn
            alignment="center"
            data-field="total_inproses"
            data-type="number"
            caption="Jml"
            css-class="custom-table-column"
            cell-template="formatNumberLaporanJmlBelumSelesai"
          />
          <DxColumn
            alignment="center"
            data-field="persen_inproses"
            data-type="number"
            caption="%"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
        <DxColumn alignment="center" caption="Sudah Selesai" css-class="custom-table-column">
          <DxColumn
            alignment="center"
            data-field="total_selesai"
            data-type="number"
            caption="Jml"
            css-class="custom-table-column"
            cell-template="formatNumberLaporanJmlSelesai"
          />
          <DxColumn
            alignment="center"
            data-field="persen_selesai"
            data-type="number"
            caption="%"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
      </DxColumn>
      <DxColumn alignment="center" caption="Rating" css-class="custom-table-column">
        <DxColumn alignment="center" caption="Bintang" css-class="custom-table-column">
          <DxColumn
            alignment="center"
            data-field="total_rating"
            data-type="number"
            caption="Jml"
            css-class="custom-table-column"
            cell-template="formatNumberRatingTotal"
          />
          <DxColumn
            alignment="center"
            data-field="nilai_rating1"
            data-type="number"
            caption="1"
            css-class="custom-table-column"
            cell-template="formatNumberRating1"
          />
          <DxColumn
            alignment="center"
            data-field="nilai_rating2"
            data-type="number"
            caption="2"
            css-class="custom-table-column"
            cell-template="formatNumberRating2"
          />
          <DxColumn
            alignment="center"
            data-field="nilai_rating3"
            data-type="number"
            caption="3"
            css-class="custom-table-column"
            cell-template="formatNumberRating3"
          />
          <DxColumn
            alignment="center"
            data-field="nilai_rating4"
            data-type="number"
            caption="4"
            css-class="custom-table-column"
            cell-template="formatNumberRating4"
          />
          <DxColumn
            alignment="center"
            data-field="nilai_rating5"
            data-type="number"
            caption="5"
            css-class="custom-table-column"
            cell-template="formatNumberRating5"
          />
          <DxColumn
            alignment="center"
            data-field="indeks_rating"
            data-type="number"
            caption="Index"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
      </DxColumn>

      <DxColumn alignment="center" caption="Non Rating" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_nonrating"
          data-type="number"
          caption="Jml"
          css-class="custom-table-column"
          cell-template="formatNumberJmlNonRating"
        />
        <DxColumn
          :width="70"
          alignment="center"
          data-field="persen_nonrating"
          data-type="number"
          caption="%"
          css-class="custom-table-column"
          cell-template="formatPercentage"
        />
      </DxColumn>

      <template #formatText="{ data }">
        <p
          class="text-left cursor-pointer"
          @click="
            setParameterRequest({
              dialog: false,
              progress: 0,
              rating: 0,
              nonRating: 0
            })
          "
        >
          {{ data.text }}
        </p>
      </template>

      <template #formatPercentage="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setParameterRequest({
              dialog: false,
              progress: 0,
              rating: 0,
              nonRating: 0
            })
          "
        >
          {{ isNumber(data.text) ? formatPercentage(data.text) : data.text }}
        </p>
      </template>

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

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

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

      <template #formatNumberLaporanJmlBelumSelesai="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setParameterRequest({
              dialog: true,
              progress: 2,
              rating: 0,
              nonRating: 0
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatTime="{ data }">
        <p
          class="!text-right cursor-pointer"
          @click="
            setParameterRequest({
              dialog: false,
              progress: 0,
              rating: 0,
              nonRating: 0
            })
          "
        >
          {{ parseInt(data.text) ? formatWaktu(data.text) : '-' }}
        </p>
      </template>

      <template #formatNumberRatingTotal="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setParameterRequest({
              dialog: true,
              progress: 0,
              rating: 0,
              nonRating: 2
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatNumberRating1="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setParameterRequest({
              dialog: true,
              progress: 0,
              rating: 1,
              nonRating: 0
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatNumberRating2="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setParameterRequest({
              dialog: true,
              progress: 0,
              rating: 2,
              nonRating: 0
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatNumberRating3="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setParameterRequest({
              dialog: true,
              progress: 0,
              rating: 3,
              nonRating: 0
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatNumberRating4="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setParameterRequest({
              dialog: true,
              progress: 0,
              rating: 4,
              nonRating: 0
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatNumberRating5="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setParameterRequest({
              dialog: true,
              progress: 0,
              rating: 5,
              nonRating: 0
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatNumberJmlNonRating="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setParameterRequest({
              dialog: true,
              progress: 0,
              rating: 0,
              nonRating: 1
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>
    </DxDataGrid>
  </div>

  <DetailDialog
    :open="dialogDetail"
    title="Detail Rating Per Regu"
    @on-close="closeDialog"
    :full-width="true"
  >
    <div class="w-full mb-4 lg:w-[70%] lg:float-left">
      <div class="p-4 bg-white rounded-xl lg:mr-4">
        <DxDataGrid
          :allow-column-reordering="true"
          class="max-h-[calc(100vh-140px)]"
          :data-source="dataSub"
          :show-column-lines="true"
          :show-row-lines="false"
          :show-borders="true"
          :row-alternation-enabled="true"
          :hover-state-enabled="true"
          @selection-changed="onDataSubSelectionChanged"
          :column-width="100"
          @exporting="onExportingDetail"
          :allow-column-resizing="true"
          column-resizing-mode="widget"
        >
          <DxSelection mode="single" />
          <DxPaging :page-size="20" :enabled="true" />
          <DxPager
            :visible="true"
            :allowed-page-sizes="[20, 50, 100]"
            display-mode="full"
            :show-page-size-selector="true"
            :show-info="true"
            :show-navigation-buttons="true"
          />
          <!--  -->
          <DxSearchPanel :visible="true" :highlight-case-sensitive="true" />
          <DxExport
            :enabled="true"
            :formats="['pdf', 'xlsx', 'document']"
            :allow-export-selected-data="false"
          />

          <DxColumn
            css-class="custom-table-column"
            :width="50"
            alignment="center"
            :calculate-display-value="(item: any) => dataSub.findIndex((i) => i == item) + 1"
            data-type="number"
            caption="No"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="no_laporan"
            caption="No Laporan"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nilai_rating"
            caption="Rating"
            css-class="custom-table-column"
            cell-template="formatRating"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_lapor"
            caption="Tgl Lapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_response"
            caption="Tgl Datang"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_recovery"
            caption="Tgl Nyala"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="durasi_response_time"
            caption="Durasi Response Time"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="durasi_recovery_time"
            caption="Durasi Recovery Time"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="status_akhir"
            caption="Status"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="referensi_marking"
            caption="Referensi Marking"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="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="200"
            alignment="center"
            data-field="keterangan_pelapor"
            caption="Keterangan Pelapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_posko"
            caption="Posko"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="tindakan"
            caption="Tidakan"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="penyebab"
            caption="Penyebab"
            css-class="custom-table-column"
            cell-template="formatText"
          />

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

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

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

          <template #formatRating="{ data }">
            <div class="flex justify-center cursor-pointer">
              <vue3starRatings
                v-model="data.text"
                :starSize="20"
                starColor="#CCCC00"
                inactiveColor="#D1D5DB"
                :numberOfStars="5"
                :disableClick="true"
              />
            </div>
          </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">Rating:</h3>
          <InputText
            :readonly="true"
            :value="
              parseInt(dataSubSelected?.nilai_rating)
                ? parseInt(dataSubSelected?.nilai_rating) > 0
                  ? `${parseInt(dataSubSelected?.nilai_rating)} Bintang`
                  : `Tidak Ada Bintang`
                : `Tidak Ada Bintang`
            "
            class-name="flex-1"
          />
        </div>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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()
const dataSubSelected = ref()
const dialogDetail = ref(false)
const loadingData = ref(false)
const loadingSubData = ref(false)
const reportMeta = ref({
  uid: { id: 0, name: 'Semua Unit Induk Distribusi/Wilayah' },
  up3: { id: 0, name: 'Semua Unit Pelaksanaan Pelayanan Pelanggan' },
  posko: { id: 0, name: 'Semua Posko' },
  periode: ''
})
const parameterRequest = ref({
  dialog: false,
  progress: 0,
  rating: 0,
  nonRating: 0
})
const setParameterRequest = (data: any) => {
  parameterRequest.value = data
}

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

  const query = {
    dateFrom: dateValue[0]
      ? dateValue[0].split('-').reverse().join('-')
      : new Date().toISOString().slice(0, 10),
    dateTo: dateValue[1]
      ? dateValue[1].split('-').reverse().join('-')
      : new Date().toISOString().slice(0, 10),
    posko: ref?.id_posko ? ref?.id_posko : 0,
    idUid: ref?.id_uid ? ref?.id_uid : 0,
    idUp3: ref?.id_up3 ? ref?.id_up3 : 0,
    idRegu: ref?.id_regu ? ref?.id_regu : 0,
    namaRegional: ref?.nama_regional ? ref?.nama_regional : '',
    isSelesai: parameterRequest.value.progress,
    isNonRating: parameterRequest.value.nonRating,
    nilaiRating: parameterRequest.value.rating
  }

  loadingSubData.value = true
  await requestGraphQl(queries.gangguan.rekap.gangguanRatingDetail, query)
    .then((result) => {
      if (result.data.data != undefined) {
        dataSub.value = result.data.data.detailRekapitulasiGangguanBerdasarkanRating
      } else {
        dataSub.value = []
      }

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

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

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

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

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

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

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

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

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

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

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

      reportMeta.value = filters.value
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingData.value = false
    })
}
const filters = ref()
onMounted(() => {
  if (import.meta.env.DEV) {
    data.value = [
      {
        id: 16,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 221,
        nama_uid: 'WILAYAH KALIMANTAN SELATAN DAN TENGAH',
        id_up3: 2210,
        nama_up3: 'UP3 BANJARMASIN',
        id_ulp: 22120,
        nama_ulp: 'ULP BANJARBARU',
        id_posko: 221201,
        kode_regu: 'BANJARBARU12',
        nama_regu: 'BANJARBARU12',
        nama_posko: 'POSKO ULP BANJARBARU',
        total: 13,
        total_selesai: 13,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_rating: 2,
        persen_rating: 15.384615384615385,
        nilai_rating1: 0,
        nilai_rating2: 0,
        nilai_rating3: 0,
        nilai_rating4: 0,
        nilai_rating5: 2,
        indeks_rating: 1,
        total_nonrating: 11,
        persen_nonrating: 84.61538461538461
      },
      {
        id: 17,
        nama_regional: 'REGIONAL SULMAPANA',
        id_uid: 31,
        nama_uid: 'WILAYAH SULAWESI UTARA,TENGAH DAN GORONTALO',
        id_up3: 31700,
        nama_up3: 'UP3 KOTAMOBAGU',
        id_ulp: 31710,
        nama_ulp: 'ULP IMANDI',
        id_posko: 317101,
        kode_regu: 'MIKE',
        nama_regu: 'MIKE',
        nama_posko: 'POSKO ULP IMANDI',
        total: 3,
        total_selesai: 3,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_rating: 1,
        persen_rating: 33.33333333333333,
        nilai_rating1: 0,
        nilai_rating2: 0,
        nilai_rating3: 0,
        nilai_rating4: 0,
        nilai_rating5: 1,
        indeks_rating: 1,
        total_nonrating: 2,
        persen_nonrating: 66.66666666666666
      },
      {
        id: 18,
        nama_regional: 'REGIONAL JMB',
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 143,
        nama_up3: 'UP3 BOJONEGORO',
        id_ulp: 51808,
        nama_ulp: 'ULP SUMBER REJO',
        id_posko: 518088,
        kode_regu: 'SUMBERREJO14',
        nama_regu: 'SUMBERREJO14',
        nama_posko: 'POSKO ULP SUMBER REJO',
        total: 12,
        total_selesai: 12,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_rating: null,
        persen_rating: null,
        nilai_rating1: 0,
        nilai_rating2: 0,
        nilai_rating3: 0,
        nilai_rating4: 0,
        nilai_rating5: 0,
        indeks_rating: null,
        total_nonrating: null,
        persen_nonrating: null
      },
      {
        id: 19,
        nama_regional: 'REGIONAL SULMAPANA',
        id_uid: 42,
        nama_uid: 'WILAYAH PAPUA DAN PAPUA BARAT',
        id_up3: 426,
        nama_up3: 'UP3 TIMIKA',
        id_ulp: 42610,
        nama_ulp: 'ULP TIMIKA KOTA',
        id_posko: 426101,
        kode_regu: 'TIMIKA21',
        nama_regu: 'TIMIKA21',
        nama_posko: 'POSKO ULP TIMIKA KOTA',
        total: 5,
        total_selesai: 5,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_rating: null,
        persen_rating: null,
        nilai_rating1: 0,
        nilai_rating2: 0,
        nilai_rating3: 0,
        nilai_rating4: 0,
        nilai_rating5: 0,
        indeks_rating: null,
        total_nonrating: null,
        persen_nonrating: null
      },
      {
        id: 20,
        nama_regional: 'REGIONAL JMB',
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 156,
        nama_up3: 'UP3 SURABAYA SELATAN',
        id_ulp: 51146,
        nama_ulp: 'ULP GEDANGAN',
        id_posko: 511465,
        kode_regu: 'SDA KOTA 17',
        nama_regu: 'SDA KOTA 17',
        nama_posko: 'POSKO ULP GEDANGAN',
        total: 1,
        total_selesai: 1,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_rating: null,
        persen_rating: null,
        nilai_rating1: 0,
        nilai_rating2: 0,
        nilai_rating3: 0,
        nilai_rating4: 0,
        nilai_rating5: 0,
        indeks_rating: null,
        total_nonrating: null,
        persen_nonrating: null
      },
      {
        id: 21,
        nama_regional: 'REGIONAL JMB',
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 150,
        nama_up3: 'UP3 PAMEKASAN',
        id_ulp: 51730,
        nama_ulp: 'ULP BANGKALAN',
        id_posko: 517304,
        kode_regu: 'BKLN.MS2',
        nama_regu: 'BKLN.MS2',
        nama_posko: 'POSKO ULP BANGKALAN',
        total: 23,
        total_selesai: 23,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_rating: 15,
        persen_rating: 65.21739130434783,
        nilai_rating1: 0,
        nilai_rating2: 0,
        nilai_rating3: 0,
        nilai_rating4: 0,
        nilai_rating5: 15,
        indeks_rating: 1,
        total_nonrating: 8,
        persen_nonrating: 34.78260869565217
      }
    ]
    // .sort((a: any, b: any) => a.nama_up3.localeCompare(b.nama_up3))
    // .map((ref: any, index: number) => {
    //   return {
    //     ...ref,
    //     number: index + 1
    //   }
    // })
  }
})
</script>
