<template>
  <Filters @reset-form="resetData" @run-search="() => filterData()" class="mb-4">
    <Type3 @update:filters="(value) => (filters = value)" />
  </Filters>

  <div id="data">
    <DxDataGrid
      ref="dataGridRef"
      @option-changed="handleRequestChange"
      :allow-column-reordering="true"
      class="max-h-[calc(100vh-140px)] mb-10"
      :data-source="data"
      :remote-operations="true"
      :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="false"
    >
      <DxLoadPanel :enabled="true" />
      <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"
      />
      <DxColumnFixing :enabled="true" />

      <DxColumn
        :allow-sorting="false"
        css-class="custom-table-column !text-right"
        :width="50"
        alignment="center"
        data-type="number"
        data-field="no"
        caption="No"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="no_laporan"
        caption="No Laporan"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="waktu_lapor"
        caption="Tgl Lapor"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="waktu_response"
        caption="Tgl Response"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="waktu_recovery"
        caption="Tgl Recovery"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="durasi_response_time"
        caption="Durasi Response Time"
        css-class="custom-table-column"
        cell-template="formatTime"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="durasi_recovery_time"
        caption="Durasi Recovery Time"
        css-class="custom-table-column"
        cell-template="formatTime"
      />
      <DxColumn
        :width="120"
        alignment="center"
        data-field="status_akhir"
        caption="Status"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="idpel_nometer"
        caption="IDPEL/NO METER"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="nama_pelapor"
        caption="Nama Pelapor"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="alamat_pelapor"
        caption="Alamat Pelapor"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="no_telp_pelapor"
        caption="No Telp Pelapor"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="170"
        alignment="center"
        data-field="keterangan_pelapor"
        caption="Keterangan Pelapor"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="150"
        alignment="center"
        data-field="media"
        caption="Sumber Lapor"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        :width="150"
        alignment="center"
        data-field="nama_ulp"
        caption="Nama ULP"
        css-class="custom-table-column"
        cell-template="formatText"
      />

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

      <template #formatTime="{ data }">
        <p class="cursor-pointer !text-right">
          {{ parseInt(data.text) ? formatWaktu(data.text) : '-' }}
        </p>
      </template>
    </DxDataGrid>
  </div>

  <DetailDialog :open="dialogDetail" title="Detail Keluhan" @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 Laporan:</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">Tgl Lapor:</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">Tanggal Response:</h3>
        <InputText :readonly="true" :value="dataSelected?.waktu_response" 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">Tanggal Recovery:</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">Response Time:</h3>
        <InputText
          :readonly="true"
          :value="
            parseInt(dataSelected?.durasi_response_time)
              ? formatWaktu(dataSelected?.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-[170px] text-gray-800">Recovery Time:</h3>
        <InputText
          :readonly="true"
          :value="
            parseInt(dataSelected?.durasi_recovery_time)
              ? formatWaktu(dataSelected?.durasi_recovery_time)
              : '-'
          "
          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">Status:</h3>
        <InputText :readonly="true" :value="dataSelected?.status_akhir" 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">IDPEL/NO METER:</h3>
        <InputText :readonly="true" :value="dataSelected?.idpel_nometer" 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">Alamat Pelapor:</h3>
        <InputText
          :readonly="true"
          type="textarea"
          :value="dataSelected?.alamat_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">No Telp Pelapor:</h3>
        <InputText :readonly="true" :value="dataSelected?.no_telp_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">Keterangan Pelapor:</h3>
        <InputText
          :readonly="true"
          type="textarea"
          :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">Sumber Lapor:</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 ULP:</h3>
        <InputText :readonly="true" :value="dataSelected?.nama_ulp" class-name="flex-1" />
      </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 CustomStore from 'devextreme/data/custom_store'

import { formatWaktu } from '@/components/Form/FiltersType/reference'
import { reactive, ref } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxLoadPanel,
  DxPager,
  DxPaging,
  DxSearchPanel,
  DxSelection
} from 'devextreme-vue/data-grid'
import { queries, requestGraphQl } from '@/utils/api/api.graphql'
import { exportToPDF, exportToXLSX, exportToDOCX } from '@/report/Keluhan/Daftar/DKeluhan_STIDP'

import type { IRequestOptions } from '@/types/requestParams'

const requestOptions = reactive<IRequestOptions>({
  skip: 0,
  take: 20,
  requireTotalCount: true,
  sort: null,
  filter: null
})

const dataSelected = ref<any>()
const dialogDetail = ref(false)
const reportData: any = ref(null)
const dataGridRef = ref<DxDataGrid | null>(null)
const filters = ref()
const reportMeta = ref({
  uid: { id: 0, name: 'Semua Unit Induk Distribusi/Wilayah' },
  up3: { id: 0, name: 'Semua Unit Pelaksanaan Pelayanan Pelanggan' },
  ulp: { id: 0, name: 'Semua Unit Layanan Pelanggan' },
  periode: ''
})

const allowTableRequest = ref(false)
const data = new CustomStore({
  load: async (loadOptions: any) => {
    if (allowTableRequest.value) {
      loadOptions.requireTotalCount = true

      const query = {
        skip: loadOptions.skip,
        take: loadOptions.take,
        sort: loadOptions.sort ? loadOptions.sort : null,
        filter: loadOptions.filter ? mapSearchOptions(loadOptions.filter) : null,
        requireTotalCount: loadOptions.requireTotalCount,
        ...createQuery(filters.value)
      }

      return await requestGraphQl(
        queries.keluhan.daftar.ssdaftarKeluhanSelesaiTanpaIdPelanggan,
        query
      )
        .then((result) => {
          const response = result.data.data.ssdaftarKeluhanSelesaiTanpaIdPelanggan

          let no = query.skip ?? 0

          for (const data of response.data) {
            data.no = ++no
          }

          return {
            data: response.data,
            totalCount: response.totalCount
          }
        })
        .catch((err) => {
          throw Error(err)
        })
        .finally(() => {
          reportMeta.value = filters.value
        })
    } else {
      return new Promise(function (resolve) {
        resolve({
          data: [],
          totalCount: 0
        })
      })
    }
  }
})

const resetData = () => {
  allowTableRequest.value = false

  const dataGrid = dataGridRef.value!.instance!
  const dataGridDataSource = dataGrid.getDataSource()

  dataGridDataSource.reload()
}

const handleRequestChange = (e: any) => {
  if (e.name === 'searchPanel') {
    if (e.value !== '') {
      requestOptions.filter = createSearchOptions(e.value)
    } else {
      requestOptions.filter = null
    }
  }

  if (e.name === 'paging') {
    requestOptions.take = e.value
  }

  if (e.name === 'columns') {
    const columnIndex = parseInt(e.fullName.match(/\[(\d+)\]/)[1])
    const columnDataField = e.component.columnOption(columnIndex).dataField

    requestOptions.sort = [
      {
        selector: columnDataField,
        desc: e.value === 'desc'
      }
    ]
  }
}

const createSearchOptions = (keyword: string) => {
  const dataGrid = dataGridRef.value!.instance!
  const columns = dataGrid.getVisibleColumns()

  const searchOptions = []

  for (const column of columns) {
    if (column.dataField === 'no' || !column.dataField) {
      continue
    }

    searchOptions.push({
      field: column.dataField,
      value: keyword
    })
  }

  return searchOptions
}

const mapSearchOptions = (searchOptions: any) => {
  const result = searchOptions.map((option: any) => {
    if (Array.isArray(option) && option[0] !== 'no') {
      return {
        field: option[0],
        value: option[2]
      }
    }
  })

  return result.filter((item: any) => item)
}

const filterData = () => {
  allowTableRequest.value = true

  const dataGrid = dataGridRef.value!.instance!
  const dataGridDataSource = dataGrid.getDataSource()

  dataGridDataSource.reload()
}

const createQuery = (params: any) => {
  const dateValue = params.periode.split(' s/d ')
  const { ulp, uid, up3 } = params

  return {
    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: ulp ? ulp.id : 0,
    idUid: uid ? uid.id : 0,
    idUp3: up3 ? up3.id : 0
  }
}

const closeDialog = () => {
  dialogDetail.value = false
}

const clearSelection = () => {
  const dataGrid = dataGridRef.value!.instance!
  dataGrid.clearSelection()
}

const showDetail = () => {
  clearSelection()
  dialogDetail.value = true
}

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

const onExporting = async (e: any) => {
  const dataGrid = dataGridRef.value!.instance!

  if (e.format === 'pdf' || e.format === 'document') {
    reportData.value = await data.load()
  }

  if (e.format === 'pdf' && reportData.value) {
    dataGrid.beginCustomLoading('')
    const pdf = await exportToPDF(reportMeta, reportData)

    if (pdf) {
      dataGrid.endCustomLoading()
    }
  } else if (e.format === 'xlsx') {
    exportToXLSX(reportMeta, e)
  } else if (e.format === 'document' && reportData.value) {
    dataGrid.beginCustomLoading('')
    const doc = await exportToDOCX(reportMeta, reportData)

    if (doc) {
      dataGrid.endCustomLoading()
    }
  }
}
</script>
