<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)] 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"
      @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"
        name="namaULP"
        cell-template="formatText"
      />
      <DxColumn
        alignment="center"
        :min-width="170"
        data-type="text"
        data-field="nama_uid"
        caption="Nama UID"
        css-class="custom-table-column"
        :group-index="0"
      />
      <DxColumn
        alignment="center"
        :min-width="170"
        data-type="text"
        data-field="nama_up3"
        caption="Nama UP3"
        css-class="custom-table-column"
        :group-index="1"
      />
      <DxColumn
        alignment="center"
        :min-width="170"
        data-type="text"
        data-field="nama_ulp"
        caption="Nama ULP"
        css-class="custom-table-column"
        :group-index="2"
      />
      <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(currentMonth)} ${lastYear}`"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="mom_bulan_ini"
            data-type="number"
            :caption="`${getMonthName(currentMonth)} ${currentYear}`"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="70"
            alignment="center"
            data-field="persen_mom"
            data-type="number"
            caption="%"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </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(currentMonth)} ${lastYear}`"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="yoy_tahun_ini"
            data-type="number"
            :caption="`s.d ${getMonthName(currentMonth)} ${currentYear}`"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="70"
            alignment="center"
            data-field="persen_yoy"
            data-type="number"
            caption="%"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
      </DxColumn>

      <DxSummary>
        <DxGroupItem
          :align-by-column="true"
          column="mom_bulan_kemarin"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(parseFloat(e.value.toString()))"
        />
        <DxGroupItem
          :align-by-column="true"
          column="mom_bulan_ini"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(parseFloat(e.value.toString()))"
        />
        <DxGroupItem
          :align-by-column="true"
          column="persen_mom"
          summary-type="avg"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(parseFloat(e.value.toString()))"
        />
        <DxGroupItem
          :align-by-column="true"
          column="yoy_tahun_kemarin"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(parseFloat(e.value.toString()))"
        />
        <DxGroupItem
          :align-by-column="true"
          column="yoy_tahun_ini"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(parseFloat(e.value.toString()))"
        />
        <DxGroupItem
          :align-by-column="true"
          column="persen_yoy"
          summary-type="avg"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(parseFloat(e.value.toString()))"
        />

        <DxTotalItem
          summary-type="sum"
          display-format="Total"
          show-in-column="namaULP"
          css-class="text-white !text-left"
        />
        <DxTotalItem
          column="mom_bulan_kemarin"
          summary-type="sum"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(parseFloat(e.value.toString()))"
        />
        <DxTotalItem
          column="mom_bulan_ini"
          summary-type="sum"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(parseFloat(e.value.toString()))"
        />
        <DxTotalItem
          column="persen_mom"
          summary-type="avg"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatPercentage(parseFloat(e.value.toString()))"
        />
        <DxTotalItem
          column="yoy_tahun_kemarin"
          summary-type="sum"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(parseFloat(e.value.toString()))"
        />
        <DxTotalItem
          column="yoy_tahun_ini"
          summary-type="sum"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(parseFloat(e.value.toString()))"
        />
        <DxTotalItem
          column="persen_yoy"
          summary-type="avg"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatPercentage(parseFloat(e.value.toString()))"
        />
      </DxSummary>

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

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

<script setup lang="ts">
import Filters from '@/components/Form/Filters.vue'
import Type2 from '@/components/Form/FiltersType/Type2.vue'
import { onMounted, ref } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import { getMonthName } from '@/utils/texts'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxGroupItem,
  DxLoadPanel,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection,
  DxSummary,
  DxTotalItem
} 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 { queries } from '@/utils/api/api.graphql'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'

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 currentYear = ref(new Date().getFullYear())
const currentMonth = ref(new Date().getMonth())
const lastYear = ref(currentYear.value - 1)

const { onResult, onError, loading, refetch } = useQuery(
  queries.monalisa.gangguan.rekap.jumlahKaliGangguan,
  {
    // regional: 0,
    idUp3: 0,
    idUid: 0,
    idUlp: 0,
    bulan: currentMonth.value,
    tahun: currentYear.value
  }
)

const filterData = (params: any) => {
  const { regional, ulp, uid, up3, bulan, tahun } = params
  currentMonth.value = bulan.id
  currentYear.value = tahun.id
  lastYear.value = tahun.id - 1
  refetch({
    // regional: regional,
    idUid: uid ? uid.id : 0,
    idUp3: up3 ? up3.id : 0,
    idUlp: ulp ? ulp.id : 0,
    bulan: bulan ? bulan.id : currentMonth.value,
    tahun: bulan ? tahun.id : currentYear.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()
onMounted(() => {
  if (import.meta.env.DEV) {
    data.value = [
      {
        id: 0,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 120,
        nama_uid: 'WILAYAH SUMATERA UTARA',
        id_up3: 12100,
        nama_up3: 'UP3 PEMATANG SIANTAR',
        id_ulp: 12102,
        nama_ulp: 'ULP LIMA PULUH',
        mom_bulan_ini: 42,
        mom_bulan_kemarin: 43,
        persen_mom: 2.3255813953488373,
        yoy_tahun_ini: 126,
        yoy_tahun_kemarin: 460,
        persen_yoy: 72.60869565217392
      },
      {
        id: 1,
        nama_regional: 'REGIONAL SULMAPANA',
        id_uid: 41,
        nama_uid: 'WILAYAH MALUKU DAN MALUKU UTARA',
        id_up3: 412,
        nama_up3: 'UP3 TERNATE',
        id_ulp: 41230,
        nama_ulp: 'ULP BACAN',
        mom_bulan_ini: 421,
        mom_bulan_kemarin: 511,
        persen_mom: 17.61252446183953,
        yoy_tahun_ini: 1195,
        yoy_tahun_kemarin: 107,
        persen_yoy: -1016.822429906542
      },
      {
        id: 2,
        nama_regional: 'REGIONAL JMB',
        id_uid: 101,
        nama_uid: 'DISTRIBUSI JAWA TENGAH & DIY',
        id_up3: 52150,
        nama_up3: 'UP3 MAGELANG',
        id_ulp: 52156,
        nama_ulp: 'ULP PARAKAN',
        mom_bulan_ini: 1085,
        mom_bulan_kemarin: 1072,
        persen_mom: -1.212686567164179,
        yoy_tahun_ini: 3399,
        yoy_tahun_kemarin: 3359,
        persen_yoy: -1.1908306043465318
      },
      {
        id: 3,
        nama_regional: 'REGIONAL SULMAPANA',
        id_uid: 31,
        nama_uid: 'WILAYAH SULAWESI UTARA,TENGAH DAN GORONTALO',
        id_up3: 31500,
        nama_up3: 'UP3 TOLITOLI',
        id_ulp: 31530,
        nama_ulp: 'ULP BANGKIR',
        mom_bulan_ini: 53,
        mom_bulan_kemarin: 69,
        persen_mom: 23.18840579710145,
        yoy_tahun_ini: 242,
        yoy_tahun_kemarin: 745,
        persen_yoy: 67.51677852348993
      },
      {
        id: 4,
        nama_regional: 'REGIONAL JMB',
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 154,
        nama_up3: 'UP3 SITUBONDO',
        id_ulp: 51654,
        nama_ulp: 'ULP WONOSARI',
        mom_bulan_ini: 1845,
        mom_bulan_kemarin: 1397,
        persen_mom: -32.06871868289191,
        yoy_tahun_ini: 4705,
        yoy_tahun_kemarin: 3969,
        persen_yoy: -18.54371378180902
      },
      {
        id: 5,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 110,
        nama_uid: 'WILAYAH ACEH',
        id_up3: 116,
        nama_up3: 'UP3 SIGLI',
        id_ulp: 11662,
        nama_ulp: 'ULP MEUREUDU',
        mom_bulan_ini: 756,
        mom_bulan_kemarin: 605,
        persen_mom: -24.958677685950413,
        yoy_tahun_ini: 1994,
        yoy_tahun_kemarin: 1391,
        persen_yoy: -43.350107836089144
      },
      {
        id: 6,
        nama_regional: 'REGIONAL JMB',
        id_uid: 287,
        nama_uid: 'DISTRIBUSI BALI',
        id_up3: 329,
        nama_up3: 'UP3 BALI UTARA',
        id_ulp: 55340,
        nama_ulp: 'ULP GILIMANUK',
        mom_bulan_ini: 698,
        mom_bulan_kemarin: 858,
        persen_mom: 18.64801864801865,
        yoy_tahun_ini: 2349,
        yoy_tahun_kemarin: 2398,
        persen_yoy: 2.043369474562135
      },
      {
        id: 7,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 131,
        nama_uid: 'WILAYAH SUMATERA BARAT',
        id_up3: 13300,
        nama_up3: 'UP3 SOLOK',
        id_ulp: 13334,
        nama_ulp: 'ULP SILUNGKANG',
        mom_bulan_ini: 226,
        mom_bulan_kemarin: 305,
        persen_mom: 25.901639344262296,
        yoy_tahun_ini: 737,
        yoy_tahun_kemarin: 1076,
        persen_yoy: 31.505576208178436
      },
      {
        id: 8,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 221,
        nama_uid: 'WILAYAH KALIMANTAN SELATAN DAN TENGAH',
        id_up3: 2220,
        nama_up3: 'UP3 BARABAI',
        id_ulp: 22230,
        nama_ulp: 'ULP AMUNTAI',
        mom_bulan_ini: 467,
        mom_bulan_kemarin: 323,
        persen_mom: -44.58204334365325,
        yoy_tahun_ini: 1122,
        yoy_tahun_kemarin: 1696,
        persen_yoy: 33.84433962264151
      },
      {
        id: 9,
        nama_regional: 'REGIONAL SULMAPANA',
        id_uid: 31,
        nama_uid: 'WILAYAH SULAWESI UTARA,TENGAH DAN GORONTALO',
        id_up3: 31700,
        nama_up3: 'UP3 KOTAMOBAGU',
        id_ulp: 31730,
        nama_ulp: 'ULP MODAYAG',
        mom_bulan_ini: 130,
        mom_bulan_kemarin: 136,
        persen_mom: 4.411764705882353,
        yoy_tahun_ini: 417,
        yoy_tahun_kemarin: 781,
        persen_yoy: 46.60691421254802
      },
      {
        id: 10,
        nama_regional: 'REGIONAL JMB',
        id_uid: 427,
        nama_uid: 'DISTRIBUSI JAWA BARAT',
        id_up3: 546,
        nama_up3: 'UP3 TASIKMALAYA',
        id_ulp: 53231,
        nama_ulp: 'ULP CIAMIS',
        mom_bulan_ini: 2179,
        mom_bulan_kemarin: 2235,
        persen_mom: 2.505592841163311,
        yoy_tahun_ini: 6792,
        yoy_tahun_kemarin: 5573,
        persen_yoy: -21.873317782164005
      },
      {
        id: 11,
        nama_regional: 'REGIONAL JMB',
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 157,
        nama_up3: 'UP3 SURABAYA UTARA',
        id_ulp: 51101,
        nama_ulp: 'ULP INDRAPURA',
        mom_bulan_ini: 596,
        mom_bulan_kemarin: 778,
        persen_mom: 23.39331619537275,
        yoy_tahun_ini: 2279,
        yoy_tahun_kemarin: 2310,
        persen_yoy: 1.341991341991342
      },
      {
        id: 12,
        nama_regional: 'REGIONAL SULMAPANA',
        id_uid: 41,
        nama_uid: 'WILAYAH MALUKU DAN MALUKU UTARA',
        id_up3: 414,
        nama_up3: 'UP3 MASOHI',
        id_ulp: 41430,
        nama_ulp: 'ULP MASOHI',
        mom_bulan_ini: 157,
        mom_bulan_kemarin: 306,
        persen_mom: 48.69281045751634,
        yoy_tahun_ini: 586,
        yoy_tahun_kemarin: 645,
        persen_yoy: 9.147286821705427
      },
      {
        id: 13,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 131,
        nama_uid: 'WILAYAH SUMATERA BARAT',
        id_up3: 13100,
        nama_up3: 'UP3 PADANG',
        id_ulp: 13105,
        nama_ulp: 'ULP LUBUK ALUNG',
        mom_bulan_ini: 781,
        mom_bulan_kemarin: 772,
        persen_mom: -1.16580310880829,
        yoy_tahun_ini: 2269,
        yoy_tahun_kemarin: 4363,
        persen_yoy: 47.994499197799676
      },
      {
        id: 14,
        nama_regional: 'REGIONAL JMB',
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 153,
        nama_up3: 'UP3 SIDOARJO',
        id_ulp: 51182,
        nama_ulp: 'ULP PORONG',
        mom_bulan_ini: 3246,
        mom_bulan_kemarin: 2883,
        persen_mom: -12.59105098855359,
        yoy_tahun_ini: 9173,
        yoy_tahun_kemarin: 7701,
        persen_yoy: -19.11440072717829
      }
    ]
  }
})
</script>
