<!-- Rekapitulasi Gangguan/Jenis Gangguan -->

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

  <div id="data">
    <DxDataGrid
      ref="dataGridRef"
      :allow-column-reordering="true"
      class="max-h-[calc(100vh-140px)] mb-10"
      :data-source="data"
      :show-column-lines="true"
      :show-row-lines="false"
      :show-borders="true"
      :row-alternation-enabled="true"
      :hover-state-enabled="true"
      @selection-changed="onDataSelectionChanged"
      @exporting="onExporting"
      :allow-column-resizing="true"
      column-resizing-mode="widget"
    >
      <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" />
      <DxGroupPanel :visible="true" />
      <DxGrouping :auto-expand-all="true" :context-menu-enabled="true" expand-mode="rowClick" />

      <DxColumn
        :width="60"
        alignment="center"
        data-field="no"
        caption="NO"
        css-class="custom-table-column"
        cell-template="formatNumber"
      />
      <DxColumn
        :width="120"
        alignment="center"
        data-field="kode"
        caption="Kode"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="120"
        alignment="center"
        data-field="sub_kelompok"
        caption="Kelompok"
        css-class="custom-table-column"
        group-index="0"
        cell-template="formatText"
      />
      <DxColumn
        :width="150"
        alignment="center"
        data-field="jenisGangguan"
        caption="Jenis Gangguan"
        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="laporan.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="laporan.sudahSelesai.jml"
            data-type="number"
            caption="Jml"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="70"
            alignment="center"
            data-field="laporan.sudahSelesai.persen"
            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="laporan.belumSelesai.jml"
            data-type="number"
            caption="Jml"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="70"
            alignment="center"
            data-field="laporan.belumSelesai.persen"
            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="responseTime.menit.total"
            data-type="number"
            caption="Total"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="responseTime.menit.rataRata"
            data-type="number"
            caption="Rata-Rata"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="responseTime.menit.max"
            data-type="number"
            caption="Max"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="responseTime.menit.min"
            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="responseTime.laporan.lebihSla"
            data-type="number"
            caption=">SLA"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="responseTime.laporan.kurangSla"
            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="recoveryTime.menit.total"
            data-type="number"
            caption="Total"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="recoveryTime.menit.rataRata"
            data-type="number"
            caption="Rata-Rata"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="recoveryTime.menit.max"
            data-type="number"
            caption="Max"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="recoveryTime.menit.min"
            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="recoveryTime.laporan.lebihSla"
            data-type="number"
            caption=">SLA"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="120"
            alignment="center"
            data-field="recoveryTime.laporan.kurangSla"
            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="laporan.total"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="laporan.sudahSelesai.jml"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="laporan.sudahSelesai.persen"
          summary-type="avg"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="laporan.belumSelesai.jml"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="laporan.belumSelesai.persen"
          summary-type="avg"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="responseTime.menit.total"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="responseTime.menit.rataRata"
          summary-type="avg"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="responseTime.menit.max"
          summary-type="max"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="responseTime.menit.min"
          summary-type="min"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="responseTime.laporan.lebihSla"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="responseTime.laporan.kurangSla"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="recoveryTime.menit.total"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="recoveryTime.menit.rataRata"
          summary-type="avg"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="recoveryTime.menit.max"
          summary-type="max"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="recoveryTime.menit.min"
          summary-type="min"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => (parseInt(e.value) ? formatWaktu(e.value) : '-')"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="recoveryTime.laporan.lebihSla"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="recoveryTime.laporan.kurangSla"
          summary-type="sum"
          display-format="{0}"
          css-class="!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>
</template>

<script setup lang="ts">
import Filters from '@/components/Form/Filters.vue'
import Type1 from '@/components/Form/FiltersType/Type1.vue'
import { formatWaktu } from '@/components/Form/FiltersType/reference'
import { onMounted, ref, watch } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxGroupItem,
  DxGroupPanel,
  DxGrouping,
  DxLoadPanel,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection,
  DxSummary
} from 'devextreme-vue/data-grid'
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, requestGraphQl } from '@/utils/api/api.graphql'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'
import { exportToPDF } from '@/report/Gangguan/Rekap/RGangguan_JenisGangguan'
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 closedialogDetail = () => (dialogDetail.value = false)
const loadingData = ref(false)
const loadingSubData = ref(false)
const reportMeta = ref({
  uid: { id: 0, name: 'Semua Unit Induk Distribusi/Wilayah' },
  up3: { id: 0, name: 'Semua Unit Pelaksanaan Pelayanan Pelanggan' },
  posko: { id: 0, name: 'Semua Posko' },
  periode: ''
})

const onExporting = (e: any) => {
  if (e.format === 'pdf') {
    exportToPDF(reportMeta.value, data.value)
  } 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 getDetail = () => {
  // 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
  // }
  // const { onResult, onError, loading } = useQuery(
  //   queries.keluhan.rekap.rekapKeluhanAllDetail,
  //   query
  // )
  // onResult((queryResult) => {
  //   if (queryResult.data != undefined) {
  //     dataSub.value = queryResult.data.detailKeluhanAll
  //   }
  // })
  // 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()
  dataSubSelected.value = null
  dialogDetail.value = true
  getDetail()
}

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

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

  loadingData.value = true
  await requestGraphQl(queries.gangguan.rekap.jenisGangguan, query)
    .then((result) => {
      if (result.data.data != undefined) {
        data.value = [...result.data.data.rekapitulasiPerJenisGangguan].map(
          (item: any, index: number) => {
            return {
              no: ++index,
              sub_kelompok: item.sub_kelompok,
              kode: item.kode,
              jenisGangguan: item.tipe_permasalahan,
              laporan: {
                total: item.total,
                sudahSelesai: {
                  jml: item.total_selesai,
                  persen: item.persen_selesai
                },
                belumSelesai: {
                  jml: item.total_inproses,
                  persen: item.persen_inproses
                }
              },
              responseTime: {
                menit: {
                  total: item.total_durasi_response,
                  rataRata: item.avg_durasi_response,
                  max: item.max_durasi_response,
                  min: item.min_durasi_response
                },
                laporan: {
                  lebihSla: item.total_diatas_sla_response,
                  kurangSla: item.total_dibawah_sla_response
                }
              },
              recoveryTime: {
                menit: {
                  total: item.total_durasi_recovery,
                  rataRata: item.avg_durasi_recovery,
                  max: item.max_durasi_recovery,
                  min: item.min_durasi_recovery
                },
                laporan: {
                  lebihSla: item.total_diatas_sla_recovery,
                  kurangSla: item.total_dibawah_sla_recovery
                }
              }
            }
          }
        )
      } else {
        data.value = []
      }
      reportMeta.value = filters.value
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingData.value = false
    })
}

const filters = ref()
onMounted(() => {
  if (import.meta.env.DEV) {
    data.value = [
      {
        id: 0,
        kode: '01a',
        tipe_permasalahan: 'Pelebur pembatas putus/rusak',
        total: 0,
        total_selesai: 0,
        persen_selesai: 0,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 0,
        avg_durasi_response: 0,
        min_durasi_response: 0,
        max_durasi_response: 0,
        total_dibawah_sla_response: 0,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 0,
        avg_durasi_recovery: 0,
        min_durasi_recovery: 0,
        max_durasi_recovery: 0,
        total_dibawah_sla_recovery: 0,
        total_diatas_sla_recovery: 0
      },
      {
        id: 1,
        kode: '01b',
        tipe_permasalahan: 'MCB pembatas rusak',
        total: 0,
        total_selesai: 0,
        persen_selesai: 0,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 0,
        avg_durasi_response: 0,
        min_durasi_response: 0,
        max_durasi_response: 0,
        total_dibawah_sla_response: 0,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 0,
        avg_durasi_recovery: 0,
        min_durasi_recovery: 0,
        max_durasi_recovery: 0,
        total_dibawah_sla_recovery: 0,
        total_diatas_sla_recovery: 0
      },
      {
        id: 2,
        kode: '01c',
        tipe_permasalahan: 'RELAY dan / atau CB rusak',
        total: 0,
        total_selesai: 0,
        persen_selesai: 0,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 0,
        avg_durasi_response: 0,
        min_durasi_response: 0,
        max_durasi_response: 0,
        total_dibawah_sla_response: 0,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 0,
        avg_durasi_recovery: 0,
        min_durasi_recovery: 0,
        max_durasi_recovery: 0,
        total_dibawah_sla_recovery: 0,
        total_diatas_sla_recovery: 0
      },
      {
        id: 3,
        kode: '01d',
        tipe_permasalahan: 'Pelebur putus dan LBS jatuh atau rusak',
        total: 0,
        total_selesai: 0,
        persen_selesai: 0,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 0,
        avg_durasi_response: 0,
        min_durasi_response: 0,
        max_durasi_response: 0,
        total_dibawah_sla_response: 0,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 0,
        avg_durasi_recovery: 0,
        min_durasi_recovery: 0,
        max_durasi_recovery: 0,
        total_dibawah_sla_recovery: 0,
        total_diatas_sla_recovery: 0
      },
      {
        id: 4,
        kode: '06a',
        tipe_permasalahan: 'Kubikel APP/komponennya rusak atau gagal bekerja',
        total: 0,
        total_selesai: 0,
        persen_selesai: 0,
        total_inproses: 0,
        persen_inproses: 0,
        total_durasi_response: 0,
        avg_durasi_response: 0,
        min_durasi_response: 0,
        max_durasi_response: 0,
        total_dibawah_sla_response: 0,
        total_diatas_sla_response: 0,
        total_durasi_recovery: 0,
        avg_durasi_recovery: 0,
        min_durasi_recovery: 0,
        max_durasi_recovery: 0,
        total_dibawah_sla_recovery: 0,
        total_diatas_sla_recovery: 0
      }
    ].map((item: any, index: number) => {
      return {
        no: ++index,
        sub_kelompok: item.sub_kelompok,
        kode: item.kode,
        jenisGangguan: item.tipe_permasalahan,
        laporan: {
          total: item.total,
          sudahSelesai: {
            jml: item.total_selesai,
            persen: item.persen_selesai
          },
          belumSelesai: {
            jml: item.total_inproses,
            persen: item.persen_inproses
          }
        },
        responseTime: {
          menit: {
            total: item.total_durasi_response,
            rataRata: item.avg_durasi_response,
            max: item.max_durasi_response,
            min: item.min_durasi_response
          },
          laporan: {
            lebihSla: item.total_diatas_sla_response,
            kurangSla: item.total_dibawah_sla_response
          }
        },
        recoveryTime: {
          menit: {
            total: item.total_durasi_recovery,
            rataRata: item.avg_durasi_recovery,
            max: item.max_durasi_recovery,
            min: item.min_durasi_recovery
          },
          laporan: {
            lebihSla: item.total_diatas_sla_recovery,
            kurangSla: item.total_dibawah_sla_recovery
          }
        }
      }
    })
  }
})
</script>
