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

  <div id="data">
    <DxDataGrid
      @cell-click="onCellClicked"
      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"
    >
      <DxGrouping :auto-expand-all="false" :context-menu-enabled="true" />
      <DxSelection mode="single" />
      <!-- <DxLoadPanel
        shading-color="rgba(0,0,0,0.4)"
        :position="position"
        :show-indicator="showIndicator"
        :show-pane="showPane"
        :shading="shading"
        v-model:visible="loadingData"
        :enabled="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) => data.findIndex((i) => i == item) + 1"
        data-type="number"
        caption="No"
        cell-template="formatNumber"
      /> -->
      <DxColumn
        :width="150"
        alignment="center"
        data-field="nama_posko"
        caption="Nama Unit"
        css-class="custom-table-column"
        cell-template="formatText"
      />

      <DxColumn
        :width="150"
        alignment="center"
        data-field=""
        caption="Semua Unit"
        css-class="custom-table-column"
        cell-template="formatText"
        :group-index="0"
      />
      <DxColumn
        :width="150"
        alignment="center"
        data-field="nama_regional"
        caption="Regional"
        css-class="custom-table-column"
        cell-template="formatText"
        :group-index="1"
      />
      <DxColumn
        :width="150"
        alignment="center"
        data-field="nama_uid"
        caption="UID"
        css-class="custom-table-column"
        cell-template="formatText"
        :group-index="2"
      />
      <DxColumn
        :width="150"
        alignment="center"
        data-field="nama_up3"
        caption="UP3"
        css-class="custom-table-column"
        cell-template="formatText"
        :group-index="3"
      />
      <!-- <DxColumn
        :width="150"
        alignment="center"
        data-field="nama_posko"
        caption="Posko"
        css-class="custom-table-column"
        cell-template="formatText"
        name="namaPosko"
        :group-index="3"
      /> -->

      <DxColumn
        :width="150"
        alignment="center"
        data-field="total"
        data-type="number"
        caption="Total"
        :allow-resizing="false"
        css-class="custom-table-column"
        cell-template="formatNumber"
      />
      <DxColumn
        :width="150"
        alignment="center"
        data-field="total_selesai"
        caption="Selesai"
        :allow-resizing="false"
        css-class="custom-table-column"
        cell-template="formatNumber"
      />
      <DxColumn
        :width="70"
        alignment="center"
        data-field="persen_selesai"
        data-type="number"
        caption="%"
        :allow-resizing="false"
        css-class="custom-table-column"
        cell-template="formatNumber"
      />
      <DxColumn
        :width="150"
        alignment="center"
        data-field="total_inproses"
        data-type="number"
        caption="In Progress"
        :allow-resizing="false"
        css-class="custom-table-column"
        cell-template="formatNumber"
      />
      <DxColumn
        :width="70"
        alignment="center"
        data-field="persen_inproses"
        data-type="number"
        caption="%"
        :allow-resizing="false"
        css-class="custom-table-column"
        cell-template="formatNumber"
      />
      <DxColumn alignment="center" caption="Dispatching Time" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="avg_durasi_dispatch"
          data-type="number"
          caption="Rata-Rata"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatDPT"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="max_durasi_dispatch"
          data-type="number"
          caption="Max"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatTime"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="min_durasi_dispatch"
          data-type="number"
          caption="Min"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatTime"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_diatas_sla_dispatch"
          data-type="number"
          caption=">SLA"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_dibawah_sla_dispatch"
          data-type="number"
          caption="≤SLA"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
      </DxColumn>
      <DxColumn alignment="center" caption="Response Time" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="avg_durasi_response"
          data-type="number"
          caption="Rata-Rata"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatRPT"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="max_durasi_response"
          data-type="number"
          caption="Max"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatTime"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="min_durasi_response"
          data-type="number"
          caption="Min"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatTime"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_diatas_sla_response"
          data-type="number"
          caption=">SLA"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_dibawah_sla_response"
          data-type="number"
          caption="≤SLA"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
      </DxColumn>
      <DxColumn alignment="center" caption="Recovery Time" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="avg_durasi_recovery"
          data-type="number"
          caption="Rata-Rata"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatRCT"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="max_durasi_recovery"
          data-type="number"
          caption="Max"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatTime"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="min_durasi_recovery"
          data-type="number"
          caption="Min"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatTime"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_diatas_sla_recovery"
          data-type="number"
          caption=">SLA"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total_dibawah_sla_recovery"
          data-type="number"
          caption="≤SLA"
          :allow-resizing="false"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
      </DxColumn>

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

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

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

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

      <template #formatTime="{ data }">
        <p class="cursor-pointer" @click="setAgreementDialog(data.column.caption)">
          {{ parseInt(data.text) ? formatWaktu(data.text) : '-' }}
        </p>
      </template>

      <template #formatDPT="{ data }">
        <p
          class="text-right cursor-pointer"
          :class="[data.text < 5 ? 'text-green-500' : 'text-red-500']"
          @click="setAgreementDialog(data.column.caption)"
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatRPT="{ data }">
        <p
          class="text-right cursor-pointer"
          :class="[data.text < 45 ? 'text-green-500' : 'text-red-500']"
          @click="setAgreementDialog(data.column.caption)"
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatRCT="{ data }">
        <p
          class="text-right cursor-pointer"
          :class="[data.text < 180 ? 'text-green-500' : 'text-red-500']"
          @click="setAgreementDialog(data.column.caption)"
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>
    </DxDataGrid>
  </div>

  <DetailDialog
    :open="dialogDetail"
    title="Detail Gangguan All"
    @on-close="closedialogDetail"
    :full-width="true"
  >
    <div class="w-full mb-4 lg:w-[70%] lg:float-left">
      <div class="p-4 bg-white rounded-xl lg:mr-4">
        <DxDataGrid
          :allow-column-reordering="true"
          class="max-h-[calc(100vh-140px)]"
          :data-source="dataSub"
          :show-column-lines="true"
          :show-row-lines="false"
          :show-borders="true"
          :row-alternation-enabled="true"
          :hover-state-enabled="true"
          @selection-changed="onDataSubSelectionChanged"
          :column-width="100"
          @exporting="onExportingDetail"
          :allow-column-resizing="true"
          column-resizing-mode="widget"
        >
          <DxSelection mode="single" />
          <DxPaging :page-size="20" :enabled="true" />
          <DxPager
            :visible="true"
            :allowed-page-sizes="[20, 50, 100]"
            display-mode="full"
            :show-page-size-selector="true"
            :show-info="true"
            :show-navigation-buttons="true"
          />
          <!-- <DxLoadPanel
            shading-color="rgba(0,0,0,0.4)"
            :position="position"
            :show-indicator="showIndicator"
            :show-pane="showPane"
            :shading="shading"
            v-model:visible="loadingSubData"
            :enabled="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_posko"
            caption="Posko"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="no_laporan"
            caption="No Lapor"
            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"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_recovery"
            caption="Tgl/Jam Nyala"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="durasi_response_time"
            caption="Durasi Response Time"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="durasi_recovery_time"
            caption="Durasi Recovery Time"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field=""
            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="jarak_closing"
            caption="Jarak Closing (m)"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="dispatch_oleh"
            caption="Dispatch Oleh"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="idpel_nometer"
            caption="IDPEL/NO METER"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <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 Telp Pelapor"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="200"
            alignment="center"
            data-field="keterangan_pelapor"
            caption="Keterangan Pelapor"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="pembuat_laporan"
            caption="Sumber Lapor"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="diselesaikan_oleh"
            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="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="referensi_marking"
            caption="Referensi Marking"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="kode_gangguan"
            caption="Kode Gangguan"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="jenis_gangguan"
            caption="Jenis Gangguan"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="penyebab"
            caption="Penyebab"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="tindakan"
            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>
              {{ 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">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">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"
            class-name="flex-1"
            :value="
              parseInt(dataSubSelected?.durasi_recovery_time)
                ? formatWaktu(dataSubSelected?.durasi_recovery_time)
                : '-'
            "
          />
        </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="
              parseInt(dataSubSelected?.durasi_dispatch_time)
                ? formatWaktu(dataSubSelected?.durasi_dispatch_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">Jarak Closing (m):</h3>
          <InputText :readonly="true" :value="dataSubSelected?.jarak_closing" 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="dataSubSelected?.dispatch_oleh" 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="dataSubSelected?.pembuat_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">Diselesaikan Oleh:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.diselesaikan_oleh"
            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">Kode Gangguan:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.kode_gangguan" 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">Jenis Gangguan:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.jenis_gangguan"
            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 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>
    </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 { formatWaktu } from '@/components/Form/FiltersType/reference'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxExport,
  DxLoadPanel,
  DxPager,
  DxPaging,
  DxSearchPanel,
  DxSelection,
  DxSummary,
  DxGroupItem,
  DxGrouping
} from 'devextreme-vue/data-grid'
import { onMounted, ref } from 'vue'
import { requestGraphQl, queries } from '@/utils/api/api.graphql'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'
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,
  exportToXLSX,
  exportDetailToPDF,
  exportDetailToXLSX
} from '@/report/Gangguan/Rekap/RGangguan_ALL'
import { getDataRowGroup } from '@/utils/helper'
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<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 agreeToShowDialog = ref(false)
const progressSelected = ref(0)
const groupIndex = ref(0)
const groupDialog = ref(false)
const groupData = ref<any>(null)
const reportMeta = ref({
  uid: { id: 0, name: 'Semua Unit Induk Distribusi/Wilayah' },
  up3: { id: 0, name: 'Semua Unit Pelaksanaan Pelayanan Pelanggan' },
  posko: { id: 0, name: 'Semua Posko' },
  periode: ''
})

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

    setAgreementDialog(e.column.caption)
    const data = getDataRowGroup(e.data)
    console.table(data)
    groupData.value = data
    showDetail()
    // if (e.row.groupIndex == 0) {
    //   //
    // } else if (e.row.groupIndex == 1) {
    //   if (e.row.isExpanded) {
    //     const data = e.data.items[0].collapsedItems[0].items[0]
    //     groupData.value = data
    //   } else {
    //     const data = e.data.collapsedItems[0].items[0].items[0]
    //     groupData.value = data
    //   }
    // } else if (e.row.groupIndex == 2) {
    //   if (e.row.isExpanded) {
    //     const data = e.data.items[0].collapsedItems[0]
    //     groupData.value = data
    //   } else {
    //     const data = e.data.collapsedItems[0].items[0]
    //     groupData.value = data
    //   }
    // } else if (e.row.groupIndex == 3) {
    //   if (e.row.isExpanded) {
    //     const data = e.data.items[0]
    //     groupData.value = data
    //   } else {
    //     const data = e.data.collapsedItems[0]
    //     groupData.value = data
    //   }
    // }
    // showDetail()
  } else {
    groupDialog.value = false
  }
}

const setAgreementDialog = (column: string) => {
  if (column == 'Total' || column == 'Selesai' || column == 'In Progress') {
    agreeToShowDialog.value = true
    if (column == 'Total') {
      progressSelected.value = 0
    } else if (column == 'Selesai') {
      progressSelected.value = 1
    } else {
      progressSelected.value = 2
    }
  } else {
    agreeToShowDialog.value = false
  }
}

const calculateCustomSummary = (options: any) => {
  if (options.name == 'persenSelesai') {
    console.log(options.component.persen_selesai)

    switch (options.summaryProcess) {
      case 'start':
        // Initializing "totalValue" here
        options.totalValue = 1
        break
      case 'calculate':
        // Modifying "totalValue" here
        break
      case 'finalize':
        // Assigning the final value to "totalValue" here
        break
    }
  }
}

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

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

  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.gangguanAll, query)
    .then((result) => {
      if (result.data.data != null) {
        data.value = result.data.data.rekapitulasiAllGangguan
      } else {
        data.value = []
      }

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

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

  var query = {
    dateFrom: dateValue[0]
      ? dateValue[0].split('-').reverse().join('-')
      : new Date().toISOString().slice(0, 10),
    dateTo: dateValue[1]
      ? dateValue[1].split('-').reverse().join('-')
      : new Date().toISOString().slice(0, 10),
    posko: 0,
    idUid: 0,
    idUp3: 0,
    idRegu: 0,
    idUlp: 0,
    namaRegional: '',
    media: '',
    isSelesai: progressSelected.value,
    tanggal: ''
  }
  if (groupDialog.value) {
    // if (groupColumnCaption.value != 'Semua Unit') {
    //   if (groupColumnCaption.value == 'Regional') {
    //     query = {
    //       ...query,
    //       namaRegional: groupData.value?.nama_regional ? groupData.value?.nama_regional : ''
    //     }
    //   } else if (groupColumnCaption.value == 'UID') {
    //     query = {
    //       ...query,
    //       idUid: groupData.value?.id_uid ? groupData.value?.id_uid : 0,
    //       namaRegional: groupData.value?.nama_regional ? groupData.value?.nama_regional : ''
    //     }
    //   } else if (groupColumnCaption.value == '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 : ''
    //     }
    //   }
    // }
    if (groupIndex.value == 1) {
      query = {
        ...query,
        namaRegional: groupData.value?.nama_regional ? groupData.value?.nama_regional : ''
      }
    } else if (groupIndex.value == 2) {
      query = {
        ...query,
        idUid: groupData.value?.id_uid ? groupData.value?.id_uid : 0,
        namaRegional: groupData.value?.nama_regional ? groupData.value?.nama_regional : ''
      }
    } else if (groupIndex.value == 3) {
      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),
      posko: selected?.id_posko ? selected?.id_posko : 0,
      idUid: selected?.id_uid ? selected?.id_uid : 0,
      idUp3: selected?.id_up3 ? selected?.id_up3 : 0,
      idRegu: selected?.id_regu ? selected?.id_regu : 0,
      idUlp: selected?.id_ulp ? selected?.id_ulp : 0,
      namaRegional: selected?.nama_regional ? selected?.nama_regional : '',
      media: selected?.media ? selected?.media : '',
      isSelesai: progressSelected.value,
      tanggal: ''
    }
  }
  console.table(query)

  await requestGraphQl(queries.gangguan.rekap.gangguanAllDetail, query)
    .then((result) => {
      if (result.data.data != null) {
        dataSub.value = result.data.data.detailGangguan
      } else {
        dataSub.value = []
      }
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingSubData.value = false
      dialogDetail.value = true
    })
}
const dataGridRef = ref<DxDataGrid | null>(null)
const clearSelection = () => {
  try {
    dataGridRef.value?.instance?.clearSelection()
  } catch (error) {
    console.log(error)
  }
}
const showDetail = () => {
  clearSelection()
  if (agreeToShowDialog.value) {
    dataSub.value = []
    dataSubSelected.value = null
    // dialogDetail.value = true
    getDetail()
  }
}

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 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: 443201,
        nama_regional: 'REGIONAL SULMAPANA',
        id_uid: 44,
        nama_uid: 'WILAYAH NUSA TENGGARA BARAT',
        id_up3: 443,
        nama_up3: 'UP3 BIMA',
        id_ulp: 44320,
        nama_ulp: 'ULP DOMPU',
        id_posko: 443201,
        nama_posko: 'POSKO ULP DOMPU',
        total: 34,
        total_selesai: 34,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        avg_durasi_dispatch: 4.735294117647059,
        min_durasi_dispatch: 11,
        max_durasi_dispatch: 2562,
        total_dibawah_sla_dispatch: 19,
        total_diatas_sla_dispatch: 15,
        avg_durasi_response: 29.848484848484848,
        min_durasi_response: 625,
        max_durasi_response: 4202,
        total_dibawah_sla_response: 27,
        total_diatas_sla_response: 6,
        avg_durasi_recovery: 50.53125,
        min_durasi_recovery: 1282,
        max_durasi_recovery: 5794,
        total_dibawah_sla_recovery: 32,
        total_diatas_sla_recovery: 0,
        total_dispatch: 34,
        total_response: 33,
        total_recovery: 32
      },
      {
        id: 316201,
        nama_regional: 'REGIONAL SULMAPANA',
        id_uid: 31,
        nama_uid: 'WILAYAH SULAWESI UTARA,TENGAH DAN GORONTALO',
        id_up3: 31600,
        nama_up3: 'UP3 GORONTALO',
        id_ulp: 31620,
        nama_ulp: 'ULP MARISA',
        id_posko: 316201,
        nama_posko: 'POSKO ULP MARISA',
        total: 19,
        total_selesai: 19,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        avg_durasi_dispatch: 1.6111111111111112,
        min_durasi_dispatch: 12,
        max_durasi_dispatch: 437,
        total_dibawah_sla_dispatch: 16,
        total_diatas_sla_dispatch: 2,
        avg_durasi_response: 17.22222222222222,
        min_durasi_response: 483,
        max_durasi_response: 2541,
        total_dibawah_sla_response: 18,
        total_diatas_sla_response: 0,
        avg_durasi_recovery: 31.38888888888889,
        min_durasi_recovery: 1183,
        max_durasi_recovery: 3216,
        total_dibawah_sla_recovery: 18,
        total_diatas_sla_recovery: 0,
        total_dispatch: 18,
        total_response: 18,
        total_recovery: 18
      },
      {
        id: 433801,
        nama_regional: 'REGIONAL SULMAPANA',
        id_uid: 430,
        nama_uid: 'WILAYAH NUSA TENGGARA TIMUR',
        id_up3: 433,
        nama_up3: 'UP3 SUMBA',
        id_ulp: 43380,
        nama_ulp: 'ULP SUMBA BARAT DAYA',
        id_posko: 433801,
        nama_posko: 'POSKO ULP SUMBA BARAT DAYA',
        total: 34,
        total_selesai: 34,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        avg_durasi_dispatch: 2.5185185185185186,
        min_durasi_dispatch: 17,
        max_durasi_dispatch: 473,
        total_dibawah_sla_dispatch: 23,
        total_diatas_sla_dispatch: 4,
        avg_durasi_response: 35.34615384615385,
        min_durasi_response: 768,
        max_durasi_response: 5726,
        total_dibawah_sla_response: 19,
        total_diatas_sla_response: 7,
        avg_durasi_recovery: 57.34615384615385,
        min_durasi_recovery: 1571,
        max_durasi_recovery: 7213,
        total_dibawah_sla_recovery: 26,
        total_diatas_sla_recovery: 0,
        total_dispatch: 27,
        total_response: 26,
        total_recovery: 26
      },
      {
        id: 514603,
        nama_regional: 'REGIONAL JMB',
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 149,
        nama_up3: 'UP3 MOJOKERTO',
        id_ulp: 51460,
        nama_ulp: 'ULP NGANJUK',
        id_posko: 514603,
        nama_posko: 'POSKO ULP NGANJUK',
        total: 183,
        total_selesai: 183,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        avg_durasi_dispatch: 11.38888888888889,
        min_durasi_dispatch: 12,
        max_durasi_dispatch: 4932,
        total_dibawah_sla_dispatch: 53,
        total_diatas_sla_dispatch: 37,
        avg_durasi_response: 14.10204081632653,
        min_durasi_response: 315,
        max_durasi_response: 2385,
        total_dibawah_sla_response: 49,
        total_diatas_sla_response: 0,
        avg_durasi_recovery: 21.73469387755102,
        min_durasi_recovery: 424,
        max_durasi_recovery: 3989,
        total_dibawah_sla_recovery: 49,
        total_diatas_sla_recovery: 0,
        total_dispatch: 90,
        total_response: 49,
        total_recovery: 49
      },
      {
        id: 532931,
        nama_regional: 'REGIONAL JMB',
        id_uid: 427,
        nama_uid: 'DISTRIBUSI JAWA BARAT',
        id_up3: 540,
        nama_up3: 'UP3 GARUT',
        id_ulp: 53293,
        nama_ulp: 'ULP LELES',
        id_posko: 532931,
        nama_posko: 'POSKO ULP LELES',
        total: 36,
        total_selesai: 36,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        avg_durasi_dispatch: 0.6388888888888888,
        min_durasi_dispatch: 5,
        max_durasi_dispatch: 271,
        total_dibawah_sla_dispatch: 36,
        total_diatas_sla_dispatch: 0,
        avg_durasi_response: 10.38888888888889,
        min_durasi_response: 295,
        max_durasi_response: 1270,
        total_dibawah_sla_response: 36,
        total_diatas_sla_response: 0,
        avg_durasi_recovery: 21.63888888888889,
        min_durasi_recovery: 926,
        max_durasi_recovery: 1886,
        total_dibawah_sla_recovery: 36,
        total_diatas_sla_recovery: 0,
        total_dispatch: 36,
        total_response: 36,
        total_recovery: 36
      }
    ]
    dataSub.value = []
  }
})
</script>
