<template>
  <Filters
    :report-button="true"
    @reset-form="data = []"
    @run-search="() => filterData(filters)"
    class="mb-4"
  >
    <Type2 @update:filters="(value) => (filters = value)" />
  </Filters>

  <div id="data">
    <DxDataGrid
      class="max-h-[calc(100vh-140px)]"
      :remote-operations="true"
      :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"
      @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
        :position="position"
        :show-indicator="showIndicator"
        :show-pane="showPane"
        :shading="shading"
        v-if="loading"
        v-model:visible.sync="loading"
        :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
        alignment="center"
        :min-width="170"
        data-type="text"
        data-field="nama_ulp"
        caption="Nama Unit"
        css-class="custom-table-column"
        :group-index="0"
      />
      <DxColumn
        alignment="center"
        :min-width="170"
        data-type="text"
        data-field="nama_ulp"
        caption="Nama Unit"
        css-class="custom-table-column"
      />
      <DxColumn alignment="center" caption="Jumlah Kali Gangguan" css-class="custom-table-column">
        <DxColumn alignment="center" caption="MoM" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="mom_bulan_kemarin"
            data-type="number"
            :caption="`${getMonthName(bulanSekarang)} ${tahunLalu}`"
            css-class="custom-table-column"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="mom_bulan_ini"
            data-type="number"
            :caption="`${getMonthName(bulanSekarang)} ${tahunSekarang}`"
            css-class="custom-table-column"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="persen_mom"
            data-type="number"
            caption="%"
            css-class="custom-table-column"
          />
        </DxColumn>
        <DxColumn alignment="center" caption="YoY" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="yoy_tahun_kemarin"
            data-type="number"
            :caption="`s.d ${getMonthName(bulanSekarang)} ${tahunLalu}`"
            css-class="custom-table-column"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="yoy_tahun_ini"
            data-type="number"
            :caption="`s.d ${getMonthName(bulanSekarang)} ${tahunSekarang}`"
            css-class="custom-table-column"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="persen_yoy"
            data-type="number"
            caption="%"
            css-class="custom-table-column"
          />
        </DxColumn>
      </DxColumn>

      <!-- <DxSummary>
        <DxGroupItem :show-in-group-footer="true" column="nama_ulp" display-format="Total" />
        <DxGroupItem
          :show-in-group-footer="true"
          column="mom_bulan_kemarin"
          summary-type="sum"
          display-format="{0}"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="mom_bulan_ini"
          summary-type="sum"
          display-format="{0}"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="persen_mom"
          summary-type="sum"
          display-format="{0}"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="yoy_tahun_kemarin"
          summary-type="sum"
          display-format="{0}"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="yoy_tahun_ini"
          summary-type="sum"
          display-format="{0}"
        />
        <DxGroupItem
          :show-in-group-footer="true"
          column="persen_yoy"
          summary-type="sum"
          display-format="{0}"
        />
      </DxSummary> -->
    </DxDataGrid>
  </div>
</template>

<script setup lang="ts">
import Filters from '@/components/Form/Filters.vue'
import Type2 from '@/components/Form/FiltersType/Type2.vue'
import { ref } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import { getMonthName } from '@/utils/texts'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxGroupItem,
  DxLoadPanel,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection,
  DxSummary
} 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 { useQuery } from '@vue/apollo-composable'
import gql from 'graphql-tag'

const position = { of: '#data' }
const showIndicator = ref(true)
const shading = ref(true)
const showPane = ref(true)
const data = ref<any[]>([])

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 tahunSekarang = ref(new Date().getFullYear())
const bulanSekarang = ref(new Date().getMonth())
const tahunLalu = ref(tahunSekarang.value - 1)

// const MONALISAJUMLAHKALIGANGGUAN = gql`
//   query DaftarMonalisaJumlahKaliGangguan(
//     $regional: Int
//     $idUid: Int
//     $idUp3: Int
//     $idUlp: Int
//     $bulan: Int
//     $tahun: Int
//   ) {
//     monalisaJumlahKaliGangguan(
//       regional: $regional
//       idUid: $idUid
//       idUp3: $idUp3
//       $idUlp: $idUlp
//       bulan: $bulan
//       tahun: $tahun
//     ) {
//       jumlah_bulan
//       jumlah_bulan_n_1
//       jumlah_tahun
//       jumlah_tahun_n_1
//       nama_posko
//       persen_bulan
//       persen_tahun
//     }
//   }
// `

const MONALISAJUMLAHKALIGANGGUAN = gql`
  query DaftarMonalisaJumlahKaliGangguan(
    $idUid: Int
    $idUp3: Int
    $idUlp: Int
    $bulan: Int
    $tahun: Int
  ) {
    monalisaJumlahKaliGangguan(
      idUid: $idUid
      idUp3: $idUp3
      idUlp: $idUlp
      bulan: $bulan
      tahun: $tahun
    ) {
      nama_ulp
      mom_bulan_ini
      mom_bulan_kemarin
      persen_mom
      yoy_tahun_ini
      yoy_tahun_kemarin
      persen_yoy
    }
  }
`

const { onResult, onError, loading, refetch } = useQuery(MONALISAJUMLAHKALIGANGGUAN, {
  // regional: 0,
  idUp3: 0,
  idUid: 0,
  idUlp: 0,
  bulan: bulanSekarang.value,
  tahun: tahunSekarang.value
})

const filterData = (params: any) => {
  const { regional, idUlp, idUid, idUp3, bulan, tahun } = params
  bulanSekarang.value = bulan.id
  tahunSekarang.value = tahun.id
  tahunLalu.value = tahun.id - 1
  refetch({
    // regional: regional,
    idUid: idUid ? idUid.id : 0,
    idUp3: idUp3 ? idUp3.id : 0,
    idUlp: idUlp ? idUlp.id : 0,
    bulan: bulan ? bulan.id : bulanSekarang.value,
    tahun: bulan ? tahun.id : tahunSekarang.value
  })
  onResult((queryResult) => {
    if (queryResult.data != undefined) {
      data.value = queryResult.data.monalisaJumlahKaliGangguan
    }
    console.log(queryResult.data)
    console.log(queryResult.loading)
    console.log(queryResult.networkStatus)
  })
  onError((error) => {
    console.log(error)
  })
}

const onSelectionChanged = ({ selectedRowsData }: any) => {
  const data = selectedRowsData[0]
  console.log(data)
}

const filters = ref()
</script>
