<template>
  <Filters @run-search="() => filterData(filters)" class="mb-4">
    <Type17 @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="onSelectionChanged"
      :column-width="100"
      @exporting="onExporting"
      :allow-column-resizing="true"
      column-resizing-mode="widget"
      :word-wrap-enabled="true"
      @row-prepared="onRowPrepared"
    >
      <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
        :width="170"
        alignment="center"
        data-field=""
        caption="No.Lapor"
        css-class="custom-table-column"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field=""
        caption="Tipe Isu"
        css-class="custom-table-column"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field=""
        caption="Nama"
        css-class="custom-table-column"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field=""
        caption="Unit"
        css-class="custom-table-column"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field=""
        caption="No.Telp"
        css-class="custom-table-column"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field=""
        caption="Permasalahan"
        css-class="custom-table-column"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field=""
        caption="Deskripsi"
        css-class="custom-table-column"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field=""
        caption="Tgl Buat"
        css-class="custom-table-column"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field=""
        caption="Lap.Ulang"
        css-class="custom-table-column"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field=""
        caption="Ket.Lap.Ulang"
        css-class="custom-table-column"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field=""
        caption="Status"
        css-class="custom-table-column"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field=""
        caption="Durasi"
        css-class="custom-table-column"
      />
    </DxDataGrid>
  </div>
  <BufferDialog v-if="loadingData" />
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxLoadPanel,
  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 { Type17 } from '@/components/Form/FiltersType'
import Filters from '@/components/Form/Filters.vue'
import BufferDialog from '@/components/Dialogs/BufferDialog.vue'
import { queries, requestGraphQl } from '@/utils/api/api.graphql'
const position = { of: '#data' }
const showIndicator = ref(true)
const shading = ref(true)
const showPane = ref(true)
const data = ref<any[]>([])
const dataSub = ref<any[]>([])
const dataSelected = ref<any>()
const dataSubSelected = ref<any>()
const dialogDetail = ref(false)
const loadingData = ref(false)
const 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 dataGridRef = ref<DxDataGrid | null>(null)
const clearSelection = () => {
  const dataGrid = dataGridRef.value!.instance!
  dataGrid.clearSelection()
}
const showDetail = () => {
  clearSelection()
  dataSub.value = []
  dataSubSelected.value = null
  dialogDetail.value = true
}
const closeDialog = () => {
  dialogDetail.value = false
}

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

const onRowPrepared = (e: any) => {
  if (e.rowType === 'data') {
    if (e.data.Speed > e.data.SpeedLimit) {
      // e.cellElement.style.cssText = "color: white; background-color: red";
      // or
      e.rowElement.classList.add('my-class')
      // To override alternation color
      // e.rowElement.className = e.rowElement.className.replace("dx-row-alt", "");
    }
  }
}

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

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

  loadingData.value = true
  await requestGraphQl(queries.transaksi.transaksiAPKT, query)
    .then((result) => {
      if (result.data.data != undefined) {
        data.value = result.data.data.rekapitulasiPemakaianMaterial
      } else {
        data.value = []
      }
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingData.value = false
    })
}
</script>
