<template>
  <Filters
    @reset-form="data = []"
    :report-button="true"
    @run-search="() => filterData(filters)"
    @run-report="() => exportToPDF(reportMeta, data, true)"
    class="mb-4"
  >
    <Type1 @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="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
        shading-color="rgba(0,0,0,0.4)"
        :position="position"
        :show-indicator="showIndicator"
        :show-pane="showPane"
        :shading="shading"
        v-model:visible="loadingData"
        :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
        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"
        data-field="no"
        cell-template="formatNumber"
      />
      <DxColumn
        :width="170"
        data-field="media"
        caption="Nama Media"
        alignment="center"
        cell-template="formatText"
        css-class="custom-table-column"
        header-cell-template="title-header"
      />
      <DxColumn alignment="center" caption="Tanggal" css-class="custom-table-column">
        <DxColumn
          v-for="i in 31"
          :width="100"
          alignment="center"
          :data-field="`tgl${i}`"
          data-type="number"
          :caption="i"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
      </DxColumn>
      <DxColumn
        :width="170"
        alignment="center"
        data-field="total"
        caption="Total"
        css-class="custom-table-column"
        cell-template="formatNumber"
      />

      <template #formatText="{ data }">
        <p class="text-left cursor-pointer" @click="setDate(data.column.caption)">
          {{ data.text == null || data.text == '' ? '-' : data.text }}
        </p>
      </template>

      <template #formatNumber="{ data }">
        <p class="text-right cursor-pointer" @click="setDate(data.column.caption)">
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #title-header="{ data }">
        <p class="w-full text-center">
          {{ data.column.caption }}
        </p>
      </template>

      <DxSummary>
        <DxTotalItem
          display-format="Total"
          show-in-column="media"
          css-class="text-white !text-left"
        />
        <DxTotalItem
          v-for="i in 31"
          summary-type="sum"
          display-format="{0}"
          :column="`tgl${i}`"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="total"
          summary-type="sum"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
      </DxSummary>
    </DxDataGrid>
  </div>

  <DetailDialog
    :open="dialogDetail"
    title="Detail Rekapitulasi Gangguan Berdasarkan Media"
    @on-close="closeDialog"
    :full-width="true"
  >
    <div class="w-full mb-4 lg:w-[70%] lg:float-left">
      <div class="p-4 bg-white rounded-xl lg:mr-4">
        <DxDataGrid
          :allow-column-reordering="true"
          class="max-h-[calc(100vh-140px)]"
          :data-source="dataSub"
          :show-column-lines="true"
          :show-row-lines="false"
          :show-borders="true"
          :row-alternation-enabled="true"
          :hover-state-enabled="true"
          @selection-changed="onDataSubSelectionChanged"
          :column-width="100"
          @exporting="onExportingDetail"
          :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"
          />
          <!-- <DxLoadPanel
            shading-color="rgba(0,0,0,0.4)"
            :position="position"
            :show-indicator="showIndicator"
            :show-pane="showPane"
            :shading="shading"
            v-model:visible="loadingSubData"
            :enabled="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) => dataSub.findIndex((i) => i == item) + 1"
            data-type="number"
            caption="No"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="no_laporan"
            caption="No Laporan"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_lapor"
            caption="Tgl Lapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_response"
            caption="Tgl Datang"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_recovery"
            caption="Tgl Nyala"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="durasi_response_time"
            caption="Durasi Response Time"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="durasi_recovery_time"
            caption="Durasi Recovery Time"
            css-class="custom-table-column"
            cell-template="formatTime"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="status_akhir"
            caption="Status"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="referensi_marking"
            caption="Referensi Marking"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="idpel_nometer"
            caption="IDPEL/NO METER"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_pelapor"
            caption="Nama Pelapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="alamat_pelapor"
            caption="Alamat Pelapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="no_telp_pelapor"
            caption="No Telp Pelapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="200"
            alignment="center"
            data-field="keterangan_pelapor"
            caption="Keterangan Pelapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_posko"
            caption="Posko"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="tindakan"
            caption="Tidakan"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="penyebab"
            caption="Penyebab"
            css-class="custom-table-column"
            cell-template="formatText"
          />

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

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

          <template #formatTime="{ data }">
            <p>
              {{ parseInt(data.text) ? formatWaktu(data.text) : '-' }}
            </p>
          </template>
        </DxDataGrid>
      </div>
    </div>
    <div class="w-full mb-4 lg:w-[30%] lg:float-right">
      <div class="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-[135px] text-gray-800">No Laporan:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.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-[135px] text-gray-800">Tgl Lapor:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.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-[135px] text-gray-800">Tgl Datang:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.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-[135px] text-gray-800">Tgl Nyala:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.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-[135px] text-gray-800">Durasi Response Time:</h3>
          <InputText
            :readonly="true"
            :value="
              parseInt(dataSubSelected?.durasi_response_time)
                ? formatWaktu(dataSubSelected?.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-[135px] text-gray-800">Durasi Recovery Time:</h3>
          <InputText
            :readonly="true"
            :value="
              parseInt(dataSubSelected?.durasi_recovery_time)
                ? formatWaktu(dataSubSelected?.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-[135px] text-gray-800">Status:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.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-[135px] text-gray-800">Referensi Marking:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.referensi_marking"
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">IDPEL/NO METER:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.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-[135px] text-gray-800">Nama Pelapor:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.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-[135px] text-gray-800">Alamat Pelapor:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.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-[135px] text-gray-800">No Telp Pelapor:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.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-[135px] text-gray-800">Keterangan Pelapor:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.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-[135px] text-gray-800">Posko:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.nama_posko" class-name="flex-1" />
        </div>

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

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

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

<script setup lang="ts">
import Filters from '@/components/Form/Filters.vue'
import Type1 from '@/components/Form/FiltersType/Type1.vue'
import { onMounted, ref } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxLoadPanel,
  DxPager,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection,
  DxSummary,
  DxTotalItem
} from 'devextreme-vue/data-grid'
import { queries, requestGraphQl } from '@/utils/api/api.graphql'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'
import DetailDialog from '@/components/Dialogs/DetailDialog.vue'
import { formatWaktu } from '@/components/Form/FiltersType/reference'
import InputText from '@/components/InputText.vue'
import { apolloClient } from '@/utils/api/api.graphql'
import { provideApolloClient } from '@vue/apollo-composable'
import {
  exportToPDF,
  exportDetailToPDF,
  exportToXLSX,
  exportDetailToXLSX
} from '@/report/Gangguan/Rekap/RGangguan_BerdasarMedia'
import BufferDialog from '@/components/Dialogs/BufferDialog.vue'

const client = apolloClient()
provideApolloClient(client)
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 loadingSubData = ref(false)
const date = ref('2023-02-04')
const reportMeta = ref({
  uid: { id: 0, name: 'Semua Unit Induk Distribusi/Wilayah' },
  up3: { id: 0, name: 'Semua Unit Pelaksanaan Pelayanan Pelanggan' },
  posko: { id: 0, name: 'Semua Posko' },
  periode: ''
})

const setDate = (value: any) => {
  if (isNumber(value)) {
    const tanggal = value < 10 ? `0${value}` : value
    const dateValue = filters.value.periode.split(' s/d ')
    const dateYear = dateValue[0].split('-').reverse().join('-').slice(0, -2) + tanggal
    console.log('date', dateYear)
    date.value = dateYear
  } else {
    date.value = ''
  }
}

const getDetail = async () => {
  const ref = dataSelected.value

  const query = {
    tanggal: date.value,
    posko: ref?.id_posko ? ref?.id_posko : 0,
    idUid: ref?.id_uid ? ref?.id_uid : 0,
    idUp3: ref?.id_up3 ? ref?.id_up3 : 0,
    namaRegional: ref?.nama_regional ? ref?.nama_regional : '',
    media: ref?.media ? ref?.media : ''
  }

  loadingSubData.value = true
  await requestGraphQl(queries.gangguan.rekap.berdasarkanMediaDetail, query)
    .then((result) => {
      if (result.data.data != undefined) {
        dataSub.value = result.data.data.detailRekapitulasiGangguanBerdasarkanMedia
      } else {
        dataSub.value = []
      }
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingSubData.value = false
      dialogDetail.value = true
    })
}

const dataGridRef = ref<DxDataGrid | null>(null)
const clearSelection = () => {
  const dataGrid = dataGridRef.value!.instance!
  dataGrid.clearSelection()
}
const showDetail = () => {
  clearSelection()
  dataSub.value = []
  dataSubSelected.value = null
  if (date.value != '') {
    // dialogDetail.value = true
    getDetail()
  }
}

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

const onExporting = (e: any) => {
  if (e.format === 'pdf') {
    exportToPDF(reportMeta.value, data.value)
  } else if (e.format === 'xlsx') {
    exportToXLSX(reportMeta.value, e)
  } else {
  }
}

const onExportingDetail = (e: any) => {
  if (e.format === 'pdf') {
    exportDetailToPDF(reportMeta.value, dataSub.value)
  } else if (e.format === 'xlsx') {
    exportDetailToXLSX(reportMeta.value, e)
  } else {
  }
}

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

const onDataSubSelectionChanged = ({ selectedRowsData }: any) => {
  if (selectedRowsData[0] != undefined) {
    dataSubSelected.value = selectedRowsData[0]
  }
}

const resetData = () => {
  data.value = []
  dataSub.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),
    posko: posko ? posko.id : 0,
    idUid: uid ? uid.id : 0,
    idUp3: up3 ? up3.id : 0
  }

  loadingData.value = true
  await requestGraphQl(queries.gangguan.rekap.berdasarkanMedia, query)
    .then((result) => {
      if (result.data.data != undefined) {
        data.value = result.data.data.rekapitulasiGangguanBerdasarkanMedia
      } else {
        data.value = []
      }

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

const filters = ref()
onMounted(() => {
  if (import.meta.env.DEV) {
    data.value = [
      {
        media: '',
        tgl1: 266,
        tgl2: 193,
        tgl3: 235,
        tgl4: 334,
        tgl5: 323,
        tgl6: 279,
        tgl7: 213,
        tgl8: 313,
        tgl9: 288,
        tgl10: 225,
        tgl11: 265,
        tgl12: 261,
        tgl13: 270,
        tgl14: 186,
        tgl15: 266,
        tgl16: 275,
        tgl17: 275,
        tgl18: 233,
        tgl19: 223,
        tgl20: 322,
        tgl21: 295,
        tgl22: 311,
        tgl23: 336,
        tgl24: 332,
        tgl25: 284,
        tgl26: 255,
        tgl27: 301,
        tgl28: 290,
        tgl29: 299,
        tgl30: 263,
        tgl31: 253,
        total: 8464
      },
      {
        media: 'Facebook',
        tgl1: 6,
        tgl2: 2,
        tgl3: 6,
        tgl4: 9,
        tgl5: 2,
        tgl6: 3,
        tgl7: 4,
        tgl8: 5,
        tgl9: 4,
        tgl10: 5,
        tgl11: 3,
        tgl12: 12,
        tgl13: 49,
        tgl14: 20,
        tgl15: 18,
        tgl16: 32,
        tgl17: 36,
        tgl18: 46,
        tgl19: 37,
        tgl20: 31,
        tgl21: 57,
        tgl22: 31,
        tgl23: 16,
        tgl24: 8,
        tgl25: 14,
        tgl26: 43,
        tgl27: 13,
        tgl28: 44,
        tgl29: 33,
        tgl30: 39,
        tgl31: 44,
        total: 672
      },
      {
        media: 'EMS',
        tgl1: 0,
        tgl2: 0,
        tgl3: 1,
        tgl4: 0,
        tgl5: 0,
        tgl6: 0,
        tgl7: 1,
        tgl8: 1,
        tgl9: 1,
        tgl10: 0,
        tgl11: 0,
        tgl12: 0,
        tgl13: 0,
        tgl14: 2,
        tgl15: 0,
        tgl16: 1,
        tgl17: 0,
        tgl18: 0,
        tgl19: 0,
        tgl20: 3,
        tgl21: 0,
        tgl22: 0,
        tgl23: 1,
        tgl24: 0,
        tgl25: 0,
        tgl26: 0,
        tgl27: 0,
        tgl28: 0,
        tgl29: 0,
        tgl30: 0,
        tgl31: 0,
        total: 11
      },
      {
        media: 'Email',
        tgl1: 77,
        tgl2: 54,
        tgl3: 83,
        tgl4: 85,
        tgl5: 73,
        tgl6: 61,
        tgl7: 52,
        tgl8: 63,
        tgl9: 87,
        tgl10: 81,
        tgl11: 92,
        tgl12: 85,
        tgl13: 72,
        tgl14: 66,
        tgl15: 89,
        tgl16: 103,
        tgl17: 74,
        tgl18: 96,
        tgl19: 51,
        tgl20: 104,
        tgl21: 99,
        tgl22: 116,
        tgl23: 74,
        tgl24: 86,
        tgl25: 81,
        tgl26: 42,
        tgl27: 79,
        tgl28: 90,
        tgl29: 94,
        tgl30: 92,
        tgl31: 70,
        total: 2471
      },
      {
        media: 'Twitter',
        tgl1: 5,
        tgl2: 8,
        tgl3: 3,
        tgl4: 6,
        tgl5: 2,
        tgl6: 2,
        tgl7: 4,
        tgl8: 2,
        tgl9: 7,
        tgl10: 5,
        tgl11: 11,
        tgl12: 40,
        tgl13: 48,
        tgl14: 26,
        tgl15: 27,
        tgl16: 50,
        tgl17: 41,
        tgl18: 45,
        tgl19: 35,
        tgl20: 47,
        tgl21: 38,
        tgl22: 53,
        tgl23: 28,
        tgl24: 11,
        tgl25: 28,
        tgl26: 40,
        tgl27: 28,
        tgl28: 38,
        tgl29: 20,
        tgl30: 34,
        tgl31: 11,
        total: 743
      }
    ]
  }
})
</script>
