<template>
  <Filters @run-search="() => filterData(filters)" class="mb-4">
    <Type14 @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"
    >
      <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) => data.findIndex((i) => i == item) + 1"
        data-type="number"
        caption="No"
        cell-template="formatNumber"
      />

      <DxColumn
        css-class="custom-table-column"
        :width="170"
        alignment="center"
        data-field="no_laporan"
        caption="Nomor Gangguan"
        cell-template="formatText"
      />
      <DxColumn
        css-class="custom-table-column"
        :width="170"
        alignment="center"
        data-field="nama_pelapor"
        caption="Nama Pelanggan"
        cell-template="formatText"
      />
      <DxColumn
        css-class="custom-table-column"
        :width="300"
        alignment="center"
        data-field="keterangan_pelapor"
        caption="Isi Laporan"
        cell-template="formatText"
      />
      <DxColumn
        css-class="custom-table-column"
        :width="300"
        alignment="center"
        data-field="penyebab"
        caption="Penyebab Gangguan"
        cell-template="formatText"
      />
      <DxColumn
        css-class="custom-table-column"
        :width="170"
        alignment="center"
        data-field="waktu_lapor"
        caption="Tgl Padam"
        cell-template="formatText"
      />
      <DxColumn
        css-class="custom-table-column"
        :width="170"
        alignment="center"
        data-field="waktu_recovery"
        caption="Tgl Nyala"
        cell-template="formatText"
      />
      <DxColumn
        css-class="custom-table-column"
        :width="170"
        alignment="center"
        data-field="regu"
        caption="Regu"
        cell-template="formatText"
      />
      <DxColumn css-class="custom-table-column" alignment="center" caption="Material Yang Dipakai">
        <DxColumn
          css-class="custom-table-column"
          :width="170"
          alignment="center"
          data-field="media"
          caption="Sumber"
          cell-template="formatText"
        />
        <DxColumn
          css-class="custom-table-column"
          :width="170"
          alignment="center"
          data-field="nama_material"
          caption="Nama"
          cell-template="formatText"
        />
        <DxColumn
          css-class="custom-table-column"
          :width="170"
          alignment="center"
          data-field="satuan_material"
          caption="Satuan"
          cell-template="formatText"
        />
        <DxColumn
          css-class="custom-table-column"
          :width="170"
          alignment="center"
          data-field="volume_material"
          caption="Vol"
          cell-template="formatText"
        />
      </DxColumn>

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

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

  <DetailDialog :open="dialogDetail" title="Detail Gangguan dan Material" @on-close="closeDialog">
    <div class="w-full 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-[170px] text-gray-800">No Gangguan:</h3>
        <InputText :readonly="true" :value="dataSelected?.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-[170px] text-gray-800">Nama Pelapor:</h3>
        <InputText :readonly="true" :value="dataSelected?.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-[170px] text-gray-800">Isi Laporan:</h3>
        <InputText :readonly="true" :value="dataSelected?.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-[170px] text-gray-800">Penyebab Gangguan:</h3>
        <InputText :readonly="true" :value="dataSelected?.penyebab" class-name="flex-1" />
      </div>

      <div class="flex flex-row items-center justify-between w-full">
        <h3 class="text-sm font-medium w-[170px] text-gray-800">Tgl Padam:</h3>
        <InputText :readonly="true" :value="dataSelected?.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-[170px] text-gray-800">Tgl Nyala:</h3>
        <InputText :readonly="true" :value="dataSelected?.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-[170px] text-gray-800">Regu:</h3>
        <InputText :readonly="true" :value="dataSelected?.regu" class-name="flex-1" />
      </div>

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

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

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

      <div class="flex flex-row items-center justify-between w-full">
        <h3 class="text-sm font-medium w-[170px] text-gray-800">Vol:</h3>
        <InputText :readonly="true" :value="dataSelected?.volume_material" class-name="flex-1" />
      </div>
    </div>
  </DetailDialog>

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

<script setup lang="ts">
import { ref } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxExport,
  DxLoadPanel,
  DxPager,
  DxPaging,
  DxSearchPanel,
  DxSelection
} from 'devextreme-vue/data-grid'
import Filters from '@/components/Form/Filters.vue'
import { Type14 } from '@/components/Form/FiltersType'
import { queries, requestGraphQl } from '@/utils/api/api.graphql'
import BufferDialog from '@/components/Dialogs/BufferDialog.vue'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'
import DetailDialog from '@/components/Dialogs/DetailDialog.vue'
import InputText from '@/components/InputText.vue'
import { exportToPDF, exportToXLSX } from '@/report/Material/Daftar/Material_DGMYG'

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 reportMeta = ref({
  uid: {
    id: 0,
    name: 'Semua Distribusi/Wilayah'
  },
  up3: {
    id: 0,
    name: 'Semua Area'
  },
  posko: {
    id: 0,
    name: 'Semua Unit Layanan Pelanggan'
  },
  periode: ''
})

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

const filterData = async (params: any) => {
  resetData()
  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),
    idUid: uid ? uid.id : 0,
    idUp3: up3 ? up3.id : 0,
    idPosko: posko ? posko.id : 0
  }

  loadingData.value = true
  await requestGraphQl(queries.material.daftar.daftarGangguanDanMaterialDipakai, query)
    .then((result) => {
      if (result.data.data != undefined) {
        data.value = result.data.data.daftarGangguanDanMaterialDipakai
      } else {
        data.value = []
      }

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

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 onExporting = (e: any) => {
  if (e.format === 'pdf') {
    exportToPDF(reportMeta, data)
  } else if (e.format === 'xlsx') {
    exportToXLSX(reportMeta, e)
  } else {
  }
}

const filters = ref()
</script>
