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

  <div id="data">
    <DxDataGrid 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">
      <DxSelection mode="single" />
      <DxPaging :page-size="5" :enabled="true" />
      <DxPager :visible="true" :allowed-page-sizes="[5, 10, 20]" display-mode="full" :show-page-size-selector="true"
        :show-info="true" :show-navigation-buttons="true" />
      <DxLoadPanel :position="position" :show-indicator="showIndicator" :show-pane="showPane" :shading="shading"
        v-if="loading" v-model:visible="loading" :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) => data.findIndex((i) => i == item) + 1" data-type="number" caption="No" />

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

      <template #cellCenter="{ data }">
        <p class="cursor-pointer" @click="showDialogDataSelected()">
          {{ data.text }}
        </p>
      </template>

      <template #cellLeft="{ data }">
        <p class="text-left cursor-pointer" @click="showDialogDataSelected()">
          {{ data.text }}
        </p>
      </template>

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

      <template #data-waktu="{ data }">
        <p @click="showDialogDataSelected()">
          {{ parseInt(data.text) ? formatWaktu(data.text) : '-' }}
        </p>
      </template>
    </DxDataGrid>
  </div>

  <DetailDialog :open="dialogDataSelected" title="Detail Gangguan All" @on-close="closeDialogDataSelected"
    :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 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="5" :enabled="true" />
          <DxPager :visible="true" :allowed-page-sizes="[5, 10, 20]" display-mode="full" :show-page-size-selector="true"
            :show-info="true" :show-navigation-buttons="true" />
          <DxLoadPanel :position="position" :show-indicator="showIndicator" :show-pane="showPane" :shading="shading"
            v-if="loading" v-model:visible="loading" :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) => data.findIndex((i) => i == item) + 1" data-type="number" caption="No"
            cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Posko" css-class="custom-table-column"
            cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="No Lapor" css-class="custom-table-column"
            cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Tgl/Jam Lapor"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Tgl/Jam Datang" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Tgl/Jam Nyala" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Durasi Response Time" :allow-resizing="false"
            css-class="custom-table-column" cell-template="data-waktu" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Durasi Recovery Time" :allow-resizing="false"
            css-class="custom-table-column" cell-template="data-waktu" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Durasi Penugasan Regu"
            :allow-resizing="false" css-class="custom-table-column" cell-template="data-waktu" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Duras Perjalanan Regu"
            :allow-resizing="false" css-class="custom-table-column" cell-template="data-waktu" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Jarak Closing (m)" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Dispatch Oleh" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="IDPEL/NO METER" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Nama Pelapor" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Alamat Pelapor" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="No Telp Pelapor" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Keterangan Pelapor" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Sumber Lapor" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Diselesaikan Oleh" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Status" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Referensi Marking" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Kode Gangguan" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Jenis Gangguan" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Penyebab" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />
          <DxColumn :width="150" alignment="center" data-field="" caption="Tindakan" :allow-resizing="false"
            css-class="custom-table-column" cell-template="cellLeft" />


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

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

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

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

    </div>
    <div class="w-full mb-4 lg:w-[30%] lg:float-right">
      <div class="p-4 space-y-2 bg-white rounded-xl">
        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Posko:</h3>
          <InputText :readonly="true" :value="dataSubSelected" class-name="flex-1" />
        </div>

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

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

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

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Tgl/Jam Nyala:</h3>
          <InputText :readonly="true" :value="dataSubSelected" 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="dataSubSelected" 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_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 Penugasan Regu:</h3>
          <InputText :readonly="true" class-name="flex-1" :value="parseInt(dataSubSelected?.durasi_recovery_time)
    ? formatWaktu(dataSubSelected?.durasi_recovery_time)
    : '-'
    " />
        </div>

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

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Jarak Closing (m):</h3>
          <InputText :readonly="true" :value="dataSubSelected" class-name="flex-1" />
        </div>

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

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

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

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

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


      </div>
    </div>

  </DetailDialog>
</template>

<script setup lang="ts">
import Filters from '@/components/Form/Filters.vue'
import Type1 from '@/components/Form/FiltersType/Type1.vue'
import { formatWaktu } from '@/components/Form/FiltersType/reference'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxExport,
  DxLoadPanel,
  DxPager,
  DxPaging,
  DxSearchPanel,
  DxSelection
} from 'devextreme-vue/data-grid'
import { onMounted, ref } from 'vue'
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 { dummyData } from '@/utils/dummy'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'
import DetailDialog from '@/components/Dialogs/DetailDialog.vue'
import InputText from '@/components/InputText.vue'

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 dialogDataSelected = ref(false)
const closeDialogDataSelected = () => dialogDataSelected.value = false
const showDialogDataSelected = () => dialogDataSelected.value = true

const { onResult, onError, loading, refetch } = useQuery(queries.gangguan.rekap.gangguanAll, {
  dateFrom: new Date().toISOString().slice(0, 10),
  dateTo: new Date().toISOString().slice(0, 10),
  posko: 0,
  idUid: 0,
  idUp3: 0
})

const filterData = (params: any) => {
  const { posko, uid, up3 } = params
  const dateValue = params.periode.split(' s/d ')
  refetch({
    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) {
      data.value = queryResult.data.rekapitulasiAllGangguan
    }
    console.log(queryResult.loading)
    console.log(queryResult.networkStatus)
  })
  onError((error) => {
    console.log(error)
  })
}

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) => {
  const data = selectedRowsData[0]
  dataSelected.value = data
  console.log(data)
}

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

const filters = ref()
onMounted(() => {
  data.value = dummyData.gangguan.rekap.rekapitulasiAllGangguan
})
</script>@/utils/api/graphql
