<!-- Rekapitulasi Gangguan Per Posko -->

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

  <div id="data">
    <DxDataGrid
      ref="dataGridRef"
      :allow-column-reordering="true"
      class="max-h-[calc(100vh-140px)] mb-10"
      :data-source="data"
      :show-column-lines="true"
      :show-row-lines="false"
      :show-borders="true"
      :row-alternation-enabled="true"
      :hover-state-enabled="true"
      @selection-changed="onDataSelectionChanged"
      :column-width="100"
      @exporting="onExporting"
      :allow-column-resizing="true"
      column-resizing-mode="widget"
      :word-wrap-enabled="true"
    >
      <DxGrouping expand-mode="rowClick" />
      <DxSelection mode="single" />
      <DxPaging :enabled="false" />
      <DxScrolling column-rendering-mode="virtual" mode="virtual" />
      <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"
      />
      <DxColumnFixing :enabled="true" />

      <DxColumn
        :width="60"
        alignment="center"
        data-field="no"
        caption="NO"
        css-class="custom-table-column"
        :calculateCellValue="(item: any) => data.findIndex((i) => i == item) + 1"
        cell-template="formatNumber"
      />
      <DxColumn
        :width="150"
        name="poskoGroup"
        alignment="center"
        data-field="nama_up3"
        caption="UP3"
        css-class="custom-table-column"
        :group-index="0"
        cell-template="formatText"
      />
      <DxColumn
        :width="150"
        alignment="center"
        data-field="nama_posko"
        caption="Posko"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn alignment="center" caption="Laporan" css-class="custom-table-column">
        <DxColumn
          :width="120"
          alignment="center"
          data-field="total"
          data-type="number"
          caption="Total"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
        <DxColumn alignment="center" caption="Sudah Selesai" css-class="custom-table-column">
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_selesai"
            data-type="number"
            caption="Jml"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="70"
            alignment="center"
            data-field="persen_selesai"
            data-type="number"
            caption="%"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
        <DxColumn alignment="center" caption="Belum Selesai" css-class="custom-table-column">
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_inproses"
            data-type="number"
            caption="Jml"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="70"
            alignment="center"
            data-field="persen_inproses"
            data-type="number"
            caption="%"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
      </DxColumn>
      <DxColumn alignment="center" caption="Response Time" css-class="custom-table-column">
        <DxColumn alignment="center" caption="Menit" css-class="custom-table-column">
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_durasi_response"
            data-type="number"
            caption="Total"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="avg_durasi_response"
            data-type="number"
            caption="Rata-Rata"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="max_durasi_response"
            data-type="number"
            caption="Max"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="min_durasi_response"
            data-type="number"
            caption="Min"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
        </DxColumn>
        <DxColumn alignment="center" caption="Laporan" css-class="custom-table-column">
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_diatas_sla_response"
            data-type="number"
            caption=">SLA"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_dibawah_sla_response"
            data-type="number"
            caption="≤SLA"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
      </DxColumn>
      <DxColumn alignment="center" caption="Recovery Time" css-class="custom-table-column">
        <DxColumn alignment="center" caption="Menit" css-class="custom-table-column">
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_durasi_recovery"
            data-type="number"
            caption="Total"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="avg_durasi_recovery"
            data-type="number"
            caption="Rata-Rata"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="max_durasi_recovery"
            data-type="number"
            caption="Max"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="min_durasi_recovery"
            data-type="number"
            caption="Min"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
        </DxColumn>
        <DxColumn alignment="center" caption="Laporan" css-class="custom-table-column">
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_diatas_sla_recovery"
            data-type="number"
            caption=">SLA"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="total_dibawah_sla_recovery"
            data-type="number"
            caption="≤SLA"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
      </DxColumn>

      <DxSummary>
        <DxGroupItem
          :show-in-group-footer="true"
          column="no"
          display-format="Total"
          css-class="!text-left"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total"
          summary-type="sum"
          :customize-text="(e: any) => formatNumber(e.value)"
          css-class="!text-right"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_selesai"
          summary-type="sum"
          :customize-text="(e: any) => formatNumber(e.value)"
          css-class="!text-right"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="persen_selesai"
          summary-type="avg"
          :customize-text="(e: any) => formatPercentage(e.value)"
          css-class="!text-right"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_inproses"
          summary-type="sum"
          :customize-text="(e: any) => formatNumber(e.value)"
          css-class="!text-right"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="persen_inproses"
          summary-type="avg"
          :customize-text="(e: any) => formatPercentage(e.value)"
          css-class="!text-right"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_durasi_response"
          summary-type="sum"
          :customize-text="(e: any) => formatNumber(e.value)"
          css-class="!text-right"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="avg_durasi_response"
          summary-type="avg"
          :customize-text="(e: any) => formatNumber(e.value)"
          css-class="!text-right"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="max_durasi_response"
          summary-type="max"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="min_durasi_response"
          summary-type="min"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_diatas_sla_response"
          summary-type="sum"
          :customize-text="(e: any) => formatNumber(e.value)"
          css-class="!text-right"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_dibawah_sla_response"
          summary-type="sum"
          :customize-text="(e: any) => formatNumber(e.value)"
          css-class="!text-right"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_durasi_recovery"
          summary-type="sum"
          :customize-text="(e: any) => formatNumber(e.value)"
          css-class="!text-right"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="avg_durasi_recovery"
          summary-type="avg"
          :customize-text="(e: any) => formatNumber(e.value)"
          css-class="!text-right"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="max_durasi_recovery"
          summary-type="max"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="min_durasi_recovery"
          summary-type="min"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
          css-class="!text-right"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_diatas_sla_recovery"
          summary-type="sum"
          :customize-text="(e: any) => formatNumber(e.value)"
          css-class="!text-right"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="total_dibawah_sla_recovery"
          summary-type="sum"
          :customize-text="(e: any) => formatNumber(e.value)"
          css-class="!text-right"
        />

        <DxTotalItem
          summary-type="sum"
          display-format="Total"
          show-in-column="no"
          css-class="text-white !text-right"
        />
        <DxTotalItem
          summary-type="sum"
          show-in-column="total"
          column="total"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="total_selesai"
          summary-type="sum"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="persen_selesai"
          summary-type="avg"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
        <DxTotalItem
          column="total_inproses"
          summary-type="sum"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="persen_inproses"
          summary-type="avg"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
        <DxTotalItem
          column="total_durasi_response"
          summary-type="sum"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="avg_durasi_response"
          summary-type="avg"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="max_durasi_response"
          summary-type="max"
          css-class="text-white !text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxTotalItem
          column="min_durasi_response"
          summary-type="min"
          css-class="text-white !text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxTotalItem
          column="total_diatas_sla_response"
          summary-type="sum"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="total_dibawah_sla_response"
          summary-type="sum"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="total_durasi_recovery"
          summary-type="sum"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="avg_durasi_recovery"
          summary-type="avg"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="max_durasi_recovery"
          summary-type="max"
          css-class="text-white !text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxTotalItem
          column="min_durasi_recovery"
          summary-type="min"
          css-class="text-white !text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxTotalItem
          column="total_diatas_sla_recovery"
          summary-type="sum"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="total_dibawah_sla_recovery"
          summary-type="sum"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
      </DxSummary>

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

      <template #formatNumber="{ data }">
        <p class="text-right cursor-pointer">
          {{
            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">
          {{ parseInt(data.text) ? formatWaktu(data.text) : '-' }}
        </p>
      </template>
    </DxDataGrid>
  </div>

  <DetailDialog
    :open="dialogDetail"
    title="Detail Rekapitulasi Gangguan Per Posko"
    @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="onExporting"
          :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"
            :calculateCellValue="(item: any) => dataSub.findIndex((i) => i == item) + 1"
            data-type="number"
            caption="No"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="no_laporan"
            caption="No Laporan"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_lapor"
            caption="Tgl Lapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_response"
            caption="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>
        </DxDataGrid>
      </div>
    </div>
    <div class="w-full mb-4 lg:w-[30%] lg:float-right">
      <div class="p-4 space-y-2 bg-white rounded-xl">
        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">No Laporan:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.no_laporan" class-name="flex-1" />
        </div>

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

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">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>
</template>

<script setup lang="ts">
import Filters from '@/components/Form/Filters.vue'
import { formatWaktu } from '@/components/Form/FiltersType/reference'
import Type8 from '@/components/Form/FiltersType/Type8.vue'
import { onMounted, ref, watch } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxGroupItem,
  DxGrouping,
  DxLoadPanel,
  DxPager,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection,
  DxSummary,
  DxTotalItem
} from 'devextreme-vue/data-grid'
import { jsPDF } from 'jspdf'
import { exportDataGrid as exportToPdf } from 'devextreme/pdf_exporter'
import { exportDataGrid as exportToExcel } from 'devextreme/excel_exporter'
import { saveAs } from 'file-saver'
import { Workbook } from 'exceljs'
import { useQuery } from '@vue/apollo-composable'
import { 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'

const client = apolloClient()
provideApolloClient(client)
const position = { of: '#data' }
const showIndicator = ref(true)
const shading = ref(true)
const showPane = ref(true)
const data = ref<any[]>([])
const dataSub = ref<any[]>([])
const dataSelected = ref<any>()
const dataSubSelected = ref<any>()
const dialogDetail = ref(false)
const loadingData = ref(false)
const loadingSubData = ref(false)

const getDetail = () => {
  loadingSubData.value = true
  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,
    idUlp: ref?.id_ulp ? ref?.id_ulp : 0,
    namaRegional: ref?.nama_regional ? ref?.nama_regional : '',
    media: ref?.media ? ref?.media : ''
  }

  const { onResult, onError, loading, refetch } = useQuery(
    queries.gangguan.rekap.gangguanAllDetail,
    query
  )

  onResult((queryResult) => {
    if (queryResult.data != undefined) {
      dataSub.value = queryResult.data.detailGangguan
    }
  })

  onError((error) => {
    console.log(error)
  })

  watch(loading, (value) => {
    loadingSubData.value = value
  })
}

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

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

const onExporting = (e: any) => {
  if (e.format === 'pdf') {
    const doc = new jsPDF()

    exportToPdf({
      jsPDFDocument: doc,
      component: e.component,
      indent: 5
    }).then(() => {
      doc.save(`.pdf`)
    })
  } else {
    const workbook = new Workbook()
    const worksheet = workbook.addWorksheet('Employees')

    exportToExcel({
      component: e.component,
      worksheet,
      autoFilterEnabled: true
    }).then(() => {
      workbook.xlsx.writeBuffer().then((buffer: any) => {
        saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'DataGrid.xlsx')
      })
    })

    e.cancel = true
  }
}

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 filterData = (params: any) => {
  const dateValue = params.periode.split(' s/d ')
  const { posko, uid, up3 } = params

  const { onResult, onError, loading, refetch } = useQuery(
    queries.gangguan.rekap.gangguanPerPosko,
    {
      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
    }
  )

  onResult((queryResult) => {
    if (queryResult.data != undefined) {
      const result: any[] = [...queryResult.data.rekapitulasiGangguanPerPosko]
      console.table(result)
      data.value = result.sort((a: any, b: any) => a?.nama_up3.localeCompare(b?.nama_up3))
    }
  })

  onError((error) => {
    console.log(error)
  })

  watch(loading, (value) => {
    loadingData.value = value
  })
}

const filters = ref()
onMounted(() => {
  if (import.meta.env.DEV) {
    data.value = [
      {
        id: 0,
        id_uid: 41,
        nama_uid: 'WILAYAH MALUKU DAN MALUKU UTARA',
        id_up3: 412,
        nama_up3: 'UP3 TERNATE',
        id_ulp: 41210,
        nama_ulp: 'ULP SOA SIU',
        id_posko: 412101,
        nama_posko: 'POSKO ULP SOA SIU',
        total: 1279,
        total_selesai: 1279,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 1109359,
        avg_durasi_response: 14.466828478964402,
        min_durasi_response: 178,
        max_durasi_response: 5057,
        total_dibawah_sla_response: 1230,
        total_diatas_sla_response: 6,
        avg_durasi_recovery: 25.940149625935163,
        min_durasi_recovery: 556,
        max_durasi_recovery: 6326,
        total_dibawah_sla_recovery: 1203,
        total_diatas_sla_recovery: 0,
        total_response: 1236,
        total_recovery: 1203
      },
      {
        id: 1,
        id_uid: 2,
        nama_uid: 'DISTRIBUSI JAKARTA RAYA',
        id_up3: 10,
        nama_up3: 'UP3 BINTARO',
        id_ulp: 54380,
        nama_ulp: 'UP3 BINTARO',
        id_posko: 543801,
        nama_posko: 'POSKO BINTARO',
        total: 157216,
        total_selesai: 157215,
        persen_selesai: 99.99936393242417,
        total_inproses: 1,
        persen_inproses: 0.000636067575819255,
        total_durasi_response: 158788877,
        avg_durasi_response: 25.398031657829346,
        min_durasi_response: 15,
        max_durasi_response: 86579,
        total_dibawah_sla_response: 92755,
        total_diatas_sla_response: 9463,
        avg_durasi_recovery: 35.06668004012036,
        min_durasi_recovery: 96,
        max_durasi_recovery: 86640,
        total_dibawah_sla_recovery: 99671,
        total_diatas_sla_recovery: 29,
        total_response: 102218,
        total_recovery: 99700
      },
      {
        id: 2,
        id_uid: 210,
        nama_uid: 'WILAYAH KALIMANTAN BARAT',
        id_up3: 318,
        nama_up3: 'UP3 SANGGAU',
        id_ulp: 21310,
        nama_ulp: 'ULP SINTANG',
        id_posko: 213101,
        nama_posko: 'POSKO ULP SINTANG',
        total: 4135,
        total_selesai: 4135,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 2837167,
        avg_durasi_response: 16.833272260901428,
        min_durasi_response: 128,
        max_durasi_response: 6874,
        total_dibawah_sla_response: 2679,
        total_diatas_sla_response: 50,
        avg_durasi_recovery: 27.390607528885575,
        min_durasi_recovery: 445,
        max_durasi_recovery: 8520,
        total_dibawah_sla_recovery: 2683,
        total_diatas_sla_recovery: 0,
        total_response: 2729,
        total_recovery: 2683
      },
      {
        id: 3,
        id_uid: 427,
        nama_uid: 'DISTRIBUSI JAWA BARAT',
        id_up3: 538,
        nama_up3: 'UP3 DEPOK',
        id_ulp: 53874,
        nama_ulp: 'ULP CIMANGGIS',
        id_posko: 538741,
        nama_posko: 'POSKO ULP CIMANGGIS',
        total: 30978,
        total_selesai: 30977,
        persen_selesai: 99.99677190264057,
        total_inproses: 1,
        persen_inproses: 0.0032280973594163596,
        total_durasi_response: 14476477,
        avg_durasi_response: 21.982580344666978,
        min_durasi_response: 114,
        max_durasi_response: 6822,
        total_dibawah_sla_response: 10488,
        total_diatas_sla_response: 247,
        avg_durasi_recovery: 35.48166666666667,
        min_durasi_recovery: 413,
        max_durasi_recovery: 8701,
        total_dibawah_sla_recovery: 10200,
        total_diatas_sla_recovery: 0,
        total_response: 10735,
        total_recovery: 10200
      },
      {
        id: 4,
        id_uid: 101,
        nama_uid: 'DISTRIBUSI JAWA TENGAH & DIY',
        id_up3: 52200,
        nama_up3: 'UP3 PURWOKERTO',
        id_ulp: 52205,
        nama_ulp: 'ULP WONOSOBO',
        id_posko: 522051,
        nama_posko: 'POSKO ULP WONOSOBO',
        total: 38061,
        total_selesai: 38061,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 44624414,
        avg_durasi_response: 24.358238380058143,
        min_durasi_response: 120,
        max_durasi_response: 7132,
        total_dibawah_sla_response: 29647,
        total_diatas_sla_response: 280,
        avg_durasi_recovery: 40.50045376625996,
        min_durasi_recovery: 240,
        max_durasi_recovery: 47311,
        total_dibawah_sla_recovery: 29747,
        total_diatas_sla_recovery: 4,
        total_response: 29927,
        total_recovery: 29751
      },
      {
        id: 5,
        id_uid: 101,
        nama_uid: 'DISTRIBUSI JAWA TENGAH & DIY',
        id_up3: 52300,
        nama_up3: 'UP3 SEMARANG',
        id_ulp: 52302,
        nama_ulp: 'ULP SEMARANG BARAT',
        id_posko: 523021,
        nama_posko: 'POSKO ULP SEMARANG BARAT',
        total: 50978,
        total_selesai: 50977,
        persen_selesai: 99.99803836949272,
        total_inproses: 1,
        persen_inproses: 0.0019616305072776494,
        total_durasi_response: 35390553,
        avg_durasi_response: 23.690932886180523,
        min_durasi_response: 75,
        max_durasi_response: 11432,
        total_dibawah_sla_response: 22305,
        total_diatas_sla_response: 2146,
        avg_durasi_recovery: 39.20744371521143,
        min_durasi_recovery: 305,
        max_durasi_recovery: 11701,
        total_dibawah_sla_recovery: 24072,
        total_diatas_sla_recovery: 2,
        total_response: 24451,
        total_recovery: 24074
      },
      {
        id: 6,
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 156,
        nama_up3: 'UP3 SURABAYA SELATAN',
        id_ulp: 51143,
        nama_ulp: 'ULP RUNGKUT',
        id_posko: 511434,
        nama_posko: 'POSKO ULP RUNGKUT',
        total: 53364,
        total_selesai: 53363,
        persen_selesai: 99.99812607750543,
        total_inproses: 1,
        persen_inproses: 0.0018739224945656247,
        total_durasi_response: 48283813,
        avg_durasi_response: 24.316152897657215,
        min_durasi_response: 89,
        max_durasi_response: 10456,
        total_dibawah_sla_response: 28298,
        total_diatas_sla_response: 4142,
        avg_durasi_recovery: 40.426895221227745,
        min_durasi_recovery: 157,
        max_durasi_recovery: 11526,
        total_dibawah_sla_recovery: 31611,
        total_diatas_sla_recovery: 8,
        total_response: 32440,
        total_recovery: 31619
      },
      {
        id: 7,
        id_uid: 56,
        nama_uid: 'DISTRIBUSI BANTEN',
        id_up3: 19,
        nama_up3: 'UP3 TELUK NAGA',
        id_ulp: 56660,
        nama_ulp: 'UP3 TELUK NAGA',
        id_posko: 566601,
        nama_posko: 'POSKO TELUK NAGA',
        total: 11038,
        total_selesai: 11038,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 4374336,
        avg_durasi_response: 23.703285761699302,
        min_durasi_response: 132,
        max_durasi_response: 7023,
        total_dibawah_sla_response: 2888,
        total_diatas_sla_response: 125,
        avg_durasi_recovery: 42.21269487750557,
        min_durasi_recovery: 203,
        max_durasi_recovery: 8273,
        total_dibawah_sla_recovery: 2694,
        total_diatas_sla_recovery: 0,
        total_response: 3013,
        total_recovery: 2694
      },
      {
        id: 8,
        id_uid: 221,
        nama_uid: 'WILAYAH KALIMANTAN SELATAN DAN TENGAH',
        id_up3: 2250,
        nama_up3: 'UP3 KUALAKAPUAS',
        id_ulp: 22540,
        nama_ulp: 'ULP MUARA TEWEH',
        id_posko: 225401,
        nama_posko: 'POSKO ULP MUARA TEWEH',
        total: 9756,
        total_selesai: 9756,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 7859823,
        avg_durasi_response: 21.342666666666666,
        min_durasi_response: 54,
        max_durasi_response: 5665,
        total_dibawah_sla_response: 5959,
        total_diatas_sla_response: 41,
        avg_durasi_recovery: 31.966321697947727,
        min_durasi_recovery: 481,
        max_durasi_recovery: 5111,
        total_dibawah_sla_recovery: 5701,
        total_diatas_sla_recovery: 0,
        total_response: 6000,
        total_recovery: 5701
      },
      {
        id: 9,
        id_uid: 120,
        nama_uid: 'WILAYAH SUMATERA UTARA',
        id_up3: 12300,
        nama_up3: 'UP3 SIBOLGA',
        id_ulp: 12314,
        nama_ulp: 'ULP TARUTUNG',
        id_posko: 123144,
        nama_posko: 'POSKO ULP TARUTUNG',
        total: 8192,
        total_selesai: 8192,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 2179469,
        avg_durasi_response: 4.472642925364989,
        min_durasi_response: -33,
        max_durasi_response: 5165,
        total_dibawah_sla_response: 7325,
        total_diatas_sla_response: 4,
        avg_durasi_recovery: 12.521217082821668,
        min_durasi_recovery: 246,
        max_durasi_recovery: 5938,
        total_dibawah_sla_recovery: 7329,
        total_diatas_sla_recovery: 0,
        total_response: 7329,
        total_recovery: 7329
      },
      {
        id: 10,
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 145,
        nama_up3: 'UP3 JEMBER',
        id_ulp: 51606,
        nama_ulp: 'ULP KLAKAH',
        id_posko: 516066,
        nama_posko: 'POSKO ULP KLAKAH',
        total: 11862,
        total_selesai: 11862,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 5452643,
        avg_durasi_response: 17.78001206515182,
        min_durasi_response: 213,
        max_durasi_response: 3700,
        total_dibawah_sla_response: 4958,
        total_diatas_sla_response: 15,
        avg_durasi_recovery: 26.647035094796287,
        min_durasi_recovery: 449,
        max_durasi_recovery: 4810,
        total_dibawah_sla_recovery: 4958,
        total_diatas_sla_recovery: 0,
        total_response: 4973,
        total_recovery: 4958
      },
      {
        id: 11,
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 157,
        nama_up3: 'UP3 SURABAYA UTARA',
        id_ulp: 51106,
        nama_ulp: 'ULP EMBONG WUNGU',
        id_posko: 511065,
        nama_posko: 'POSKO ULP EMBONG WUNGU',
        total: 11445,
        total_selesai: 11445,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 7620419,
        avg_durasi_response: 17.186943207126948,
        min_durasi_response: 106,
        max_durasi_response: 29305,
        total_dibawah_sla_response: 7121,
        total_diatas_sla_response: 63,
        avg_durasi_recovery: 30.80646087580761,
        min_durasi_recovery: 198,
        max_durasi_recovery: 29736,
        total_dibawah_sla_recovery: 6964,
        total_diatas_sla_recovery: 1,
        total_response: 7184,
        total_recovery: 6965
      },
      {
        id: 12,
        id_uid: 42,
        nama_uid: 'WILAYAH PAPUA DAN PAPUA BARAT',
        id_up3: 424,
        nama_up3: 'UP3 MANOKWARI',
        id_ulp: 42440,
        nama_ulp: 'ULP BINTUNI',
        id_posko: 424401,
        nama_posko: 'POSKO ULP BINTUNI',
        total: 2663,
        total_selesai: 2663,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 3068943,
        avg_durasi_response: 19.565047021943574,
        min_durasi_response: 328,
        max_durasi_response: 4863,
        total_dibawah_sla_response: 2453,
        total_diatas_sla_response: 99,
        avg_durasi_recovery: 28.1744094488189,
        min_durasi_recovery: 579,
        max_durasi_recovery: 7598,
        total_dibawah_sla_recovery: 2540,
        total_diatas_sla_recovery: 0,
        total_response: 2552,
        total_recovery: 2540
      },
      {
        id: 13,
        id_uid: 42,
        nama_uid: 'WILAYAH PAPUA DAN PAPUA BARAT',
        id_up3: 422,
        nama_up3: 'UP3 BIAK',
        id_ulp: 42210,
        nama_ulp: 'ULP BIAK KOTA',
        id_posko: 422101,
        nama_posko: 'POSKO ULP BIAK KOTA',
        total: 4219,
        total_selesai: 4218,
        persen_selesai: 99.97629770087698,
        total_inproses: 1,
        persen_inproses: 0.02370229912301493,
        total_durasi_response: 3741829,
        avg_durasi_response: 15.516816431322209,
        min_durasi_response: 45,
        max_durasi_response: 16738,
        total_dibawah_sla_response: 3871,
        total_diatas_sla_response: 24,
        avg_durasi_recovery: 21.664947124064998,
        min_durasi_recovery: 69,
        max_durasi_recovery: 17096,
        total_dibawah_sla_recovery: 3876,
        total_diatas_sla_recovery: 1,
        total_response: 3895,
        total_recovery: 3877
      },
      {
        id: 14,
        id_uid: 32,
        nama_uid: 'WILAYAH SULAWESI SELATAN, TENGGARA DAN BARAT',
        id_up3: 32300,
        nama_up3: 'UP3 KENDARI',
        id_ulp: 32330,
        nama_ulp: 'ULP BENU BENUA',
        id_posko: 323301,
        nama_posko: 'POSKO ULP BENU BENUA',
        total: 22651,
        total_selesai: 22651,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 18218233,
        avg_durasi_response: 18.958301306687165,
        min_durasi_response: 30,
        max_durasi_response: 18055,
        total_dibawah_sla_response: 14724,
        total_diatas_sla_response: 888,
        avg_durasi_recovery: 29.802055551941717,
        min_durasi_recovery: 90,
        max_durasi_recovery: 18414,
        total_dibawah_sla_recovery: 15367,
        total_diatas_sla_recovery: 6,
        total_response: 15612,
        total_recovery: 15373
      }
    ].sort((a, b) => (a.nama_up3 > b.nama_up3 ? 1 : -1))
    // sort data.value by nama_up3
    // data.value.sort((a, b) => (a.nama_up3 > b.nama_up3 ? 1 : -1))
  }
})
</script>
