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

  <div id="data">
    <DxDataGrid
      ref="dataGridRef"
      :allow-column-reordering="true"
      class="max-h-[calc(100vh-140px)] mb-10"
      :data-source="data"
      v-if="loadingData == false"
      :show-column-lines="true"
      :show-row-lines="false"
      :show-borders="true"
      :row-alternation-enabled="true"
      :hover-state-enabled="true"
      @selection-changed="onDataSelectionChanged"
      :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" />

      <DxSearchPanel :visible="true" :highlight-case-sensitive="true" />
      <DxExport
        :enabled="true"
        :formats="['pdf', 'xlsx', 'document']"
        :allow-export-selected-data="false"
      />
      <DxColumnFixing :enabled="true" />

      <DxColumn
        css-class="custom-table-column"
        :width="50"
        alignment="center"
        data-type="number"
        data-field="number"
        caption="No"
        cell-template="formatNumber"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="tipe_keluhan"
        caption="Jenis Keluhan"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="grouping_tipe_keluhan"
        caption=""
        name="tipeKeluhan"
        css-class="custom-table-column"
        :group-index="0"
      />
      <DxColumn alignment="center" caption="Laporan" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="total"
          data-type="number"
          caption="Total"
          css-class="custom-table-column"
          cell-template="formatNumberLaporanTotal"
        />
        <DxColumn alignment="center" caption="Sudah Selesai" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="total_selesai"
            data-type="number"
            caption="Jml"
            css-class="custom-table-column"
            cell-template="formatNumberLaporanJmlSelesai"
          />
          <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="150"
            alignment="center"
            data-field="total_inproses"
            data-type="number"
            caption="Jml"
            css-class="custom-table-column"
            cell-template="formatNumberLaporanJmlBelumSelesai"
          />
          <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="Hari" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="total_durasi_response"
            data-type="number"
            caption="Total"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :visible="false"
            :width="150"
            alignment="center"
            data-field="count_durasi_response"
            data-type="number"
            caption="Jumlah Response"
            css-class="custom-table-column"
            cell-template="formatNumber"
            :calculate-cell-value="
              (rowData: any) => rowData.total_durasi_response * rowData.avg_durasi_response
            "
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="avg_durasi_response"
            data-type="number"
            caption="Rata-Rata"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="max_durasi_response"
            data-type="number"
            caption="Max"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            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="150"
            alignment="center"
            data-field="total_diatas_sla_response"
            data-type="number"
            caption=">SLA"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="150"
            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="Penyelesaian" css-class="custom-table-column">
        <DxColumn alignment="center" caption="Hari" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="total_durasi_recovery"
            data-type="number"
            caption="Total"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :visible="false"
            :width="150"
            alignment="center"
            data-field="count_durasi_recovery"
            data-type="number"
            caption="Jumlah Recovery"
            css-class="custom-table-column"
            cell-template="formatNumber"
            :calculate-cell-value="
              (rowData: any) => rowData.total_durasi_recovery * rowData.avg_durasi_recovery
            "
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="avg_durasi_recovery"
            data-type="number"
            caption="Rata-Rata"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="max_durasi_recovery"
            data-type="number"
            caption="Max"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            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="150"
            alignment="center"
            data-field="total_diatas_sla_recovery"
            data-type="number"
            caption=">SLA"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="total_dibawah_sla_recovery"
            data-type="number"
            caption="≤SLA"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
      </DxColumn>

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

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

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

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

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

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

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

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

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

          <DxSearchPanel :visible="true" :highlight-case-sensitive="true" />
          <DxExport
            :enabled="true"
            :formats="['pdf', 'xlsx', 'document']"
            :allow-export-selected-data="false"
          />

          <DxColumn
            css-class="custom-table-column"
            :width="50"
            alignment="center"
            :calculate-display-value="(item: any) => dataSub.findIndex((i) => i == item) + 1"
            data-type="number"
            caption="No"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="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="Dalam Proses Bidang"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_recovery"
            caption="Selesai Bidang Unit"
            :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="status_akhir"
            caption="Status"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="idpel_nometer"
            caption="IDPEL/NO METER"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_pelapor"
            caption="Nama Pelapor"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="200"
            alignment="center"
            data-field="alamat_pelapor"
            caption="Alamat Pelapor"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="no_telp_pelapor"
            caption="No Tlp Pelapor"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="200"
            alignment="center"
            data-field="keterangan_pelapor"
            caption="Keterangan Pelapor"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_ulp"
            caption="Rayon"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="uraian"
            caption="Uraian"
            :allow-resizing="false"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="respon_pelanggan"
            caption="Respon Pelanggan"
            :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">
              {{
                isNumber(data.text)
                  ? data.column.caption == '%'
                    ? formatPercentage(data.text)
                    : formatNumber(data.text)
                  : 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">Dalam Proses Bidang:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.waktu_response"
            class-name="flex-1"
          />
        </div>

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

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

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

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

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

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

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

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

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

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

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

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

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

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 closedialogDetail = () => (dialogDetail.value = false)
const loadingData = ref(false)
const loadingSubData = ref(false)
const agreeToShowDialog = ref(false)
const progressSelected = ref(0)
const reportMeta = ref({
  uid: { id: 0, name: 'Semua Unit Induk Distribusi/Wilayah' },
  up3: { id: 0, name: 'Semua Unit Pelaksanaan Pelayanan Pelanggan' },
  ulp: { id: 0, name: 'Semua Unit Layanan Pelanggan' },
  periode: ''
})

let total = 0
let total_selesai = 0
let total_inproses = 0
let count_durasi_response = 0
let total_durasi_response = 0
let total_durasi_recovery = 0
let count_durasi_recovery = 0
const calculateCustomSummary = (options: any) => {
  if (options.name === 'total') {
    if (options.summaryProcess === 'calculate') {
      total += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = total
    }
  }

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

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

  if (options.name === 'persen_selesai') {
    if (options.summaryProcess === 'start') {
      total = 0
      total_selesai = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = !isFinite(total_selesai / total)
        ? 0
        : total_selesai == 0
          ? 0
          : (total_selesai / total) * 100
    }
  }

  if (options.name === 'persen_inproses') {
    if (options.summaryProcess === 'start') {
      total = 0
      total_inproses = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = !isFinite(total_inproses / total)
        ? 0
        : total_inproses == 0
          ? 0
          : (total_inproses / total) * 100
    }
  }

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

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

  if (options.name === 'avg_durasi_response') {
    if (options.summaryProcess === 'start') {
      total_durasi_response = 0
      count_durasi_response = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = !isFinite(count_durasi_response / total_durasi_response)
        ? 0
        : count_durasi_response == 0
          ? 0
          : count_durasi_response / total_durasi_response
    }
  }

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

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

  if (options.name === 'avg_durasi_recovery') {
    if (options.summaryProcess === 'start') {
      count_durasi_recovery = 0
      total_durasi_recovery = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = !isFinite(count_durasi_recovery / total_durasi_recovery)
        ? 0
        : count_durasi_recovery == 0
          ? 0
          : count_durasi_recovery / total_durasi_recovery
    }
  }
}

const setAgreementDialog = (status: boolean, progress: number) => {
  agreeToShowDialog.value = status
  progressSelected.value = progress
}

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

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

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

  loadingData.value = true
  await requestGraphQl(queries.keluhan.rekap.keluhanPerJenisKeluhan, query)
    .then((result) => {
      if (result.data.data != undefined) {
        data.value = [...result.data.data.rekapitulasiKeluhanPerJenisKeluhan]
          .sort((a: any, b: any) => a.tipe_keluhan.localeCompare(b.tipe_keluhan))
          .map((item: any, index: number) => {
            return {
              ...item,
              number: index + 1
            }
          })
      } else {
        data.value = []
      }

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

const getDetail = async () => {
  const dateValue = filters.value.periode.split(' s/d ')
  const selected = 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),
    idUlp: selected?.id_ulp ? selected?.id_ulp : 0,
    idUid: selected?.id_uid ? selected?.id_uid : 0,
    idUp3: selected?.id_up3 ? selected?.id_up3 : 0,
    namaRegional: '',
    isSelesai: progressSelected.value,
    media: '',
    tanggal: '',
    namaIssuetype: '',
    namaSubissuetype: selected?.tipe_keluhan ? selected?.tipe_keluhan : ''
  }

  loadingSubData.value = true
  await requestGraphQl(queries.keluhan.rekap.rekapKeluhanAllDetail, query)
    .then((result) => {
      if (result.data.data != undefined) {
        dataSub.value = result.data.data.detailKeluhanAll
      } else {
        dataSub.value = []
      }
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingSubData.value = false
      dialogDetail.value = true
    })
}

const dataGridRef = ref<DxDataGrid | null>(null)
const clearSelection = () => {
  const dataGrid = dataGridRef.value!.instance!
  dataGrid.clearSelection()
}
const showDetail = () => {
  clearSelection()
  dataSubSelected.value = null
  if (agreeToShowDialog.value) {
    getDetail()
  }
}

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

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

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

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

const filters = ref()

onMounted(() => {
  if (import.meta.env.DEV) {
    data.value = [
      {
        tipe_keluhan: 'ULP BATURAJA',
        total: 83,
        total_selesai: 83,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 2141418,
        avg_durasi_response: 25800.21686746988,
        min_durasi_response: 64,
        max_durasi_response: 173218,
        total_dibawah_sla_response: 38,
        total_diatas_sla_response: 45,
        total_durasi_recovery: 281389649,
        avg_durasi_recovery: 3390236.734939759,
        min_durasi_recovery: 1064,
        max_durasi_recovery: 5111318,
        total_dibawah_sla_recovery: 7,
        total_diatas_sla_recovery: 76
      },
      {
        tipe_keluhan: 'ULP KIJANG',
        total: 42,
        total_selesai: 42,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 44360,
        avg_durasi_response: 1056.1904761904761,
        min_durasi_response: 118,
        max_durasi_response: 3920,
        total_dibawah_sla_response: 42,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 9516017,
        avg_durasi_recovery: 226571.83333333334,
        min_durasi_recovery: 74,
        max_durasi_recovery: 5006890,
        total_dibawah_sla_recovery: 40,
        total_diatas_sla_recovery: 2
      },
      {
        tipe_keluhan: 'ULP BARABAI',
        total: 40,
        total_selesai: 40,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 34356,
        avg_durasi_response: 858.9,
        min_durasi_response: 62,
        max_durasi_response: 2169,
        total_dibawah_sla_response: 40,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 89781586,
        avg_durasi_recovery: 2244539.65,
        min_durasi_recovery: 117,
        max_durasi_recovery: 5110821,
        total_dibawah_sla_recovery: 17,
        total_diatas_sla_recovery: 23
      },
      {
        tipe_keluhan: 'ULP PROBOLINGGO',
        total: 455,
        total_selesai: 455,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 3057270,
        avg_durasi_response: 6719.274725274725,
        min_durasi_response: 18,
        max_durasi_response: 85788,
        total_dibawah_sla_response: 388,
        total_diatas_sla_response: 67,
        total_durasi_recovery: 1182178874,
        avg_durasi_recovery: 2598195.3274725275,
        min_durasi_recovery: 53,
        max_durasi_recovery: 5137065,
        total_dibawah_sla_recovery: 144,
        total_diatas_sla_recovery: 311
      },
      {
        tipe_keluhan: 'ULP TANJUNGPINANG KOTA',
        total: 60,
        total_selesai: 60,
        persen_selesai: 100,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 1705437164,
        avg_durasi_response: 28423952.733333334,
        min_durasi_response: 40,
        max_durasi_response: 1705354030,
        total_dibawah_sla_response: 59,
        total_diatas_sla_response: 1,
        total_durasi_recovery: 7027977,
        avg_durasi_recovery: 117132.95,
        min_durasi_recovery: 99,
        max_durasi_recovery: 3642771,
        total_dibawah_sla_recovery: 58,
        total_diatas_sla_recovery: 2
      }
    ]
      .sort((a: any, b: any) => a.tipe_keluhan.localeCompare(b.tipe_keluhan))
      .map((item: any, index: number) => {
        return {
          ...item,
          number: index + 1
        }
      })
  }
})
</script>
