<template>
  <Filters @run-search="() => filterData(filters)" :report-button="true" class="mb-4">
    <Type3 @update:filters="(value) => (filters = value)" />
  </Filters>
  <div>
    <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" :word-wrap-enabled="true">
      <DxSelection mode="single" />
      <DxPaging :enabled="false" />
      <DxScrolling column-rendering-mode="virtual" mode="virtual" />
      <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" />
      <DxColumnFixing :enabled="true" />

      <DxColumn alignment="center" :width="170" data-field="nama_ulp" caption="Nama Unit" css-class="custom-table-column"
        cell-template="unitName" header-cell-template="title-header" />
      <template #unitName="{ data }">
        <p class="text-left cursor-pointer" @click="showDialog()">
          {{ data.text }}
        </p>
      </template>
      <DxColumn alignment="center" caption="Response Time" 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="defaults" />
        <DxColumn :width="150" alignment="center" data-field="total_selesai" data-type="number" caption="Selesai"
          css-class="custom-table-column" cell-template="defaults" />
        <DxColumn :width="150" alignment="center" data-field="persen_selesai" data-type="number" caption="%"
          css-class="custom-table-column" cell-template="percent" />
        <DxColumn :width="150" alignment="center" data-field="total_inproses" data-type="number" caption="InProgress"
          css-class="custom-table-column" cell-template="defaults" />
        <DxColumn :width="150" alignment="center" data-field="persen_inproses" data-type="number" caption="%"
          css-class="custom-table-column" cell-template="percent" />
        <DxColumn :width="150" alignment="center" data-field="avg_durasi_response" data-type="number" caption="Rata-Rata"
          css-class="custom-table-column" cell-template="defaults" />
        <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 :width="150" alignment="center" data-field="total_diatas_sla_response" data-type="number"
          caption="> SLA" css-class="custom-table-column" cell-template="defaults" />
        <DxColumn :width="150" alignment="center" data-field="total_dibawah_sla_response" data-type="number"
          caption="≤ SLA" css-class="custom-table-column" cell-template="defaults" />
      </DxColumn>
      <DxColumn alignment="center" caption="Penyelesaian" css-class="custom-table-column">
        <DxColumn :width="150" alignment="center" data-field="avg_durasi_recovery" data-type="number" caption="Rata-Rata"
          css-class="custom-table-column" cell-template="defaults" />
        <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 :width="150" alignment="center" data-field="total_diatas_sla_recovery" data-type="number"
          caption="> SLA" css-class="custom-table-column" cell-template="defaults" />
        <DxColumn :width="150" alignment="center" data-field="total_dibawah_sla_recovery" data-type="number"
          caption="≤ SLA" css-class="custom-table-column" cell-template="defaults" />
      </DxColumn>

      <template #formatTime="{ data }">
        <p class="cursor-pointer" @click="showDialog()">
          {{ formatWaktu(data.text) }}
        </p>
      </template>
      <template #percent="{ data }">
        <p class="cursor-pointer" @click="showDialog()">
          {{ data.text }}%
        </p>
      </template>
      <template #defaults="{ data }">
        <p class="cursor-pointer" @click="showDialog()">
          {{ data.text }}
        </p>
      </template>
      <template #title-header="{ data }">
        <p class="w-full text-center">
          {{ data.column.caption }}
        </p>
      </template>
    </DxDataGrid>
  </div>

  <DetailDialog :open="showDialogDetail" :full-width="true" title="Detail Rekapitulasi Keluhan All"
    @on-close="closeDetailDialog">
    <div class="flex flex-col w-full space-y-2 lg:space-x-4 lg:flex-row lg:justify-between">
      <div class="flex flex-1 p-4 bg-white rounded-xl">
        <div class="w-full">
          <!-- <DxDataGrid class="w-full" :data-source="dataDetail" :column-auto-width="true" :show-column-lines="true"
            :show-row-lines="false" :show-borders="true" :row-alternation-enabled="true" :hover-state-enabled="true"
            @selection-changed="onDataDetailSelectionChanged" @exporting="onExporting" :allow-column-resizing="true"
            column-resizing-mode="widget" :word-wrap-enabled="true">
            <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" />
            <DxScrolling column-rendering-mode="virtual" mode="virtual" />
            <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" />
            <DxColumnFixing :enabled="true" />

            <DxColumn :width="60" alignment="center" data-field="" caption="No" css-class="custom-table-column" />
            <DxColumn :width="170" alignment="center" data-field="" caption="No Laporan"
              css-class="custom-table-column" />
            <DxColumn :width="150" alignment="center" data-field="" data-type="number" caption="Total"
              css-class="custom-table-column" />
            <DxColumn :width="150" alignment="center" data-field="" data-type="number" caption="Selesai"
              css-class="custom-table-column" />
            <DxColumn :width="150" alignment="center" data-field="" data-type="number" caption="%"
              css-class="custom-table-column" />
            <DxColumn :width="150" alignment="center" data-field="" data-type="number" caption="InProgress"
              css-class="custom-table-column" />
            <DxColumn :width="150" alignment="center" data-field="" data-type="number" caption="%"
              css-class="custom-table-column" />
            <DxColumn :width="150" alignment="center" data-field="" data-type="number" caption="Rata-Rata"
              css-class="custom-table-column" />
            <DxColumn :width="150" alignment="center" data-field="" data-type="number" caption="Max"
              css-class="custom-table-column" />
            <DxColumn :width="150" alignment="center" data-field="" data-type="number" caption="Min"
              css-class="custom-table-column" />
            <DxColumn :width="150" alignment="center" data-field="" data-type="number" caption="> SLA"
              css-class="custom-table-column" />
            <DxColumn :width="150" alignment="center" data-field="" data-type="number" caption="≤ SLA"
              css-class="custom-table-column" />
          </DxDataGrid> -->
        </div>
      </div>
      <div class="w-full p-4 space-y-2 overflow-y-auto bg-white lg:w-2/6 rounded-xl">
        <div class="flex flex-row justify-between w-full">
          <h3 class="text-sm font-medium w-[170px] text-gray-800">No Laporan:</h3>
          <InputText :readonly="true" value="-" class-name="flex-1" />
        </div>

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

        <div class="flex flex-row justify-between w-full">
          <h3 class="text-sm font-medium w-[170px] text-gray-800">Dalam Proses Bidang:</h3>
          <InputText :readonly="true" value="-" class-name="flex-1" />
        </div>

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

        <div class="flex flex-row justify-between w-full">
          <h3 class="text-sm font-medium w-[170px] text-gray-800">Durasi Response Time:</h3>
          <InputText :readonly="true" value="-" class-name="flex-1" />
        </div>

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

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

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

        <div class="flex flex-row justify-between w-full">
          <h3 class="text-sm font-medium w-[170px] text-gray-800">Alamat Pelapor:</h3>
          <InputText :readonly="true" type="textarea" value="-" class-name="flex-1 h-[56px]" />
        </div>

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

        <div class="flex flex-row justify-between w-full">
          <h3 class="text-sm font-medium w-[170px] text-gray-800">Keterangan Pelapor:</h3>
          <InputText :readonly="true" type="textarea" value="-" class-name="flex-1 h-[56px]" />
        </div>

        <div class="flex flex-row justify-between w-full">
          <h3 class="text-sm font-medium w-[170px] text-gray-800">Rayon:</h3>
          <InputText :readonly="true" value="-" class-name="flex-1" />
        </div>

        <div class="flex flex-row justify-between w-full">
          <h3 class="text-sm font-medium w-[170px] text-gray-800">Uraian:</h3>
          <InputText :readonly="true" value="-" class-name="flex-1 h-[56px]" />
        </div>

        <div class="flex flex-row justify-between w-full">
          <h3 class="text-sm font-medium w-[170px] text-gray-800">Response Pelanggan:</h3>
          <InputText :readonly="true" value="-" class-name="flex-1 h-[56px]" />
        </div>
      </div>
    </div>
  </DetailDialog>
</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 { onMounted, ref } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxLoadPanel,
  DxPager,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection
} from 'devextreme-vue/data-grid'
import { jsPDF } from 'jspdf'
import { exportDataGrid as exportToPdf } from 'devextreme/pdf_exporter'
import { exportDataGrid as exportToExcel } from 'devextreme/excel_exporter'
import { saveAs } from 'file-saver'
import { Workbook } from 'exceljs'
import { useQuery } from '@vue/apollo-composable'
import gql from 'graphql-tag'
import { formatWaktu } from '@/components/Form/FiltersType/reference'
const position = { of: '#data' }
const showIndicator = ref(true)
const shading = ref(true)
const showPane = ref(true)
const dataSelected = ref<any>()
const dataDetailSelected = ref<any>()
const showDialogDetail = ref(false)
const dataDetail = ref<any[]>([])

const closeDetailDialog = () => {
  showDialogDetail.value = false
}

const showDialog = () => {
  showDialogDetail.value = true
}

const onDataSelectionChanged = ({ selectedRowsData }: any) => {
  dataSelected.value = selectedRowsData[0]
  console.log(selectedRowsData[0])
}

const onDataDetailSelectionChanged = ({ selectedRowsData }: any) => {
  dataDetailSelected.value = selectedRowsData[0]
  console.log(selectedRowsData[0])
}

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 data = ref<any[]>([])
const GET_DATA = gql`
  query rekapitulasiKeluhanAll(
    $dateFrom: Date!
    $dateTo: Date!
    $idUlp: Int!
    $idUid: Int!
    $idUp3: Int!
  ) {
    rekapitulasiKeluhanAll(
      dateFrom: $dateFrom
      dateTo: $dateTo
      idUlp: $idUlp
      idUid: $idUid
      idUp3: $idUp3
    ) {
      id_ulp
      nama_ulp
      total
      total_selesai
      persen_selesai
      total_inproses
      persen_inproses
      avg_durasi_response
      min_durasi_response
      max_durasi_response
      total_dibawah_sla_response
      total_diatas_sla_response
      avg_durasi_recovery
      min_durasi_recovery
      max_durasi_recovery
      total_dibawah_sla_recovery
      total_diatas_sla_recovery
    }
  }
`

const { onResult, onError, loading, refetch } = useQuery(GET_DATA, {
  dateFrom: new Date('2023-10-01').toISOString().slice(0, 10),
  dateTo: new Date('2023-10-01').toISOString().slice(0, 10),
  idUlp: 0,
  idUid: 0,
  idUp3: 0
})
const filters = ref()

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

  onResult((queryResult) => {
    if (queryResult.data != undefined) {
      data.value = queryResult.data.rekapitulasiKeluhanAll
    }
    console.log(queryResult.data)
    console.log(queryResult.loading)
    console.log(queryResult.networkStatus)
  })
  onError((error) => {
    console.log(error)
  })
}
</script>
