<template>
  <div class="flex flex-row items-center w-full mb-6 space-x-4">
    <button
      @click="tab = 'gangguan'"
      type="button"
      class="px-1 py-4 text-sm"
      :class="[
        tab == 'gangguan'
          ? 'border-b-2 border-secondary-500 text-primary-500 font-semibold'
          : 'font-medium text-gray-500'
      ]"
    >
      Gangguan: Transaksi Aktif > SLA
    </button>
    <button
      @click="tab = 'keluhan'"
      type="button"
      class="px-1 py-4 text-sm"
      :class="[
        tab == 'keluhan'
          ? 'border-b-2 border-secondary-500 text-primary-500 font-semibold'
          : 'font-medium text-gray-500'
      ]"
    >
      Keluhan: Transaksi Aktif > SLA
    </button>
  </div>

  <Filters @reset-form="data = []" @run-search="() => filterData(filters)" class="mb-4">
    <Type17Gangguan v-if="tab == 'gangguan'" @update:filters="(value) => (filters = value)" />
    <Type17Keluhan v-else @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"
      v-if="loadingData == false"
      :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="['xlsx']" :allow-export-selected-data="false" />
      <DxColumnFixing :enabled="true" />

      <DxColumn
        :width="170"
        alignment="center"
        data-field="no_laporan"
        caption="No.Lapor"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        v-if="tab == 'keluhan'"
        :width="170"
        alignment="center"
        data-field="nama_issuetype"
        caption="Tipe Isu"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="nama_pelapor"
        caption="Nama"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        v-if="tab == 'gangguan'"
        :width="170"
        alignment="center"
        data-field="alamat_pelapor"
        caption="Alamat Pelapor"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        v-if="tab == 'gangguan'"
        :width="170"
        alignment="center"
        data-field="lokasi"
        caption="Lokasi"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        v-if="tab == 'gangguan'"
        :width="170"
        alignment="center"
        data-field="nama_posko"
        caption="Posko"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        v-if="tab == 'keluhan'"
        :width="170"
        alignment="center"
        data-field="nama_ulp"
        caption="Unit"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="no_telp_pelapor"
        caption="No.Telp"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        v-if="tab == 'keluhan'"
        :width="250"
        alignment="center"
        data-field="permasalahan"
        caption="Permasalahan"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="250"
        alignment="center"
        data-field="deskripsi"
        caption="Deskripsi"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="create_date"
        caption="Tgl Buat"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        v-if="tab == 'gangguan'"
        :width="170"
        alignment="center"
        data-field="waktu_padam"
        caption="Tgl Padam"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="jumlah_lapor"
        caption="Lap.Ulang"
        css-class="custom-table-column"
        cell-template="formatNumber"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="keterangan_lapor_ulang"
        caption="Ket.Lap.Ulang"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        v-if="tab == 'keluhan'"
        :width="170"
        alignment="center"
        data-field="status_akhir"
        caption="Status"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        v-if="tab == 'keluhan'"
        :width="170"
        alignment="center"
        data-field="durasi_time"
        caption="Durasi"
        css-class="custom-table-column"
        cell-template="formatTime"
      />

      <template #formatText="{ data }">
        <p class="text-left">
          {{ 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>
  <BufferDialog v-if="loadingData" />
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection
} from 'devextreme-vue/data-grid'
import { Type17Gangguan, Type17Keluhan } 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'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'
import { formatWaktu } from '@/components/Form/FiltersType/reference'
import { saveAs } from 'file-saver'
import { Workbook } from 'exceljs'
import { setHeaderStyle } from '@/report/utils/xlsx'
import { exportDataGrid as exportToExcel } from 'devextreme/excel_exporter'

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 tab = ref('gangguan')
const reportMeta = ref({
  uid: { id: 0, name: 'Pilih Unit' },
  up3: { id: 0, name: 'Pilih Area' },
  ulp: { id: 0, name: 'Pilih Rayon' },
  status: { id: 0, name: 'Pilih Status' },
  keyword: '',
  searchBy: { id: 1, title: 'No Lapor' },
  sla: {
    id: 1,
    name: '45 Menit',
    time: 45
  },
  periode: ''
})

const formatMetaData = (reportMeta: any) => {
  const periode = reportMeta.periode ? reportMeta.periode.split(' s/d ') : ''

  let dateFromFormat = ''
  let dateToFormat = ''
  let dayTo = ''

  if (periode != '') {
    const dateFrom = new Date(periode[0].split('-').reverse().join('-'))
    const dateTo = new Date(periode[1].split('-').reverse().join('-'))

    dateFromFormat = `${dateFrom.getDate()}-${dateFrom.toLocaleString('id-ID', {
      month: 'long'
    })}-${dateFrom.getFullYear()}`

    dateToFormat = `${dateTo.getDate()}-${dateTo.toLocaleString('id-ID', {
      month: 'long'
    })}-${dateTo.getFullYear()}`

    dayTo = dateTo.toLocaleString('id-ID', { weekday: 'long' })
  }

  return { dateFromFormat, dateToFormat, dayTo }
}

const onExporting = (e: any) => {
  const meta = formatMetaData(reportMeta.value)
  const workbook = new Workbook()
  const worksheet = workbook.addWorksheet('Transaksi APKT')

  setHeaderStyle(worksheet, 1, 1, 'PT. PLN(Persero)')
  setHeaderStyle(
    worksheet,
    2,
    1,
    `UNIT PLN : ${reportMeta.value.uid.id ? reportMeta.value.uid.name.toUpperCase() + ',' : ''} ${reportMeta.value.up3.id ? reportMeta.value.up3.name.toUpperCase() + ',' : ''} ${reportMeta.value.ulp.id ? reportMeta.value.ulp.name.toUpperCase() + ',' : ''}`
  )
  setHeaderStyle(
    worksheet,
    3,
    1,
    `STATUS : ${reportMeta.value.status ? reportMeta.value.status.name.toUpperCase() : ''}`
  )
  setHeaderStyle(
    worksheet,
    4,
    1,
    `SLA : ${reportMeta.value.sla ? reportMeta.value.sla.name.toUpperCase() : ''}`
  )
  setHeaderStyle(worksheet, 5, 1, `PENCARIAN : ${reportMeta.value.keyword.toUpperCase()}`)

  setHeaderStyle(worksheet, 7, 1, 'Transaksi APKT'.toUpperCase(), true)
  setHeaderStyle(
    worksheet,
    8,
    1,
    `PERIODE TANGGAL : ${meta.dateFromFormat} SD TGL ${meta.dateToFormat}`,
    true
  )

  worksheet.mergeCells('A1:M1')
  worksheet.mergeCells('A2:M2')
  worksheet.mergeCells('A3:M3')
  worksheet.mergeCells('A4:M4')
  worksheet.mergeCells('A5:M5')
  worksheet.mergeCells('A7:M7')
  worksheet.mergeCells('A8:M8')

  exportToExcel({
    component: e.component,
    worksheet,
    autoFilterEnabled: true,
    topLeftCell: { row: 10, column: 1 },
    loadPanel: {
      enabled: false
    }
  }).then(() => {
    workbook.xlsx.writeBuffer().then((buffer: any) => {
      saveAs(
        new Blob([buffer], { type: 'application/octet-stream' }),
        `Laporan Transaksi APKT.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, ulp, uid, up3, status, keyword, searchBy, sla } = 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),
    idPosko: posko ? posko.id : 0,
    idUid: uid ? uid.id : 0,
    idUp3: up3 ? up3.id : 0,
    idUlp: ulp ? ulp.id : 0,
    tipe_sla: sla ? sla.id : 0,
    operator_sla: '',
    status_akhir: status ? status.name : '',
    no_laporan: searchBy == 'No Lapor' ? keyword : '',
    nama_pelapor: searchBy == 'Nama Pelapor' ? keyword : '',
    permasalahan: searchBy == 'Permasalahan' ? keyword : ''
  }

  loadingData.value = true
  await requestGraphQl(
    tab.value == 'gangguan'
      ? queries.transaksi.transaksiApktGangguan
      : queries.transaksi.transaksiApktKeluhan,
    query
  )
    .then((result) => {
      if (result.data.data != undefined) {
        if (tab.value == 'gangguan') {
          data.value = result.data.data.transaksiApktGangguan
        } else {
          data.value = result.data.data.transaksiApktKeluhan
        }
      } else {
        data.value = []
      }

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