<template>
  <Filters
    @reset-form="data = []"
    @run-search="() => filterData(filters)"
    :report-button="true"
    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="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"
        data-field="nama_ulp"
        caption="Nama Unit"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn alignment="center" caption="ENS 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>
      <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>

      <DxSummary>
        <DxTotalItem
          summary-type="sum"
          display-format="Total"
          show-in-column="nama_ulp"
          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>
    </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 {
  DxColumn,
  DxColumnFixing,
  DxExport,
  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 { getMonthName } from '@/utils/texts'
import { queries } from '@/utils/api/api.graphql'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'

const currentYear = ref(new Date().getFullYear())
const currentMonth = ref(new Date().getMonth())
const lastYear = ref(currentYear.value - 1)
const position = { of: '#data' }
const showIndicator = ref(true)
const shading = ref(true)
const showPane = ref(true)
const data = ref<any[]>([])
const dataDetail = ref<any>()
const showDetail = ref(false)

const { onResult, onError, loading, refetch } = useQuery(
  queries.monalisa.gangguan.rekap.rekapitulasiEnsGangguan,
  {
    bulan: 10,
    tahun: 2023,
    regional: '',
    idUlp: 0,
    idUid: 0,
    idUp3: 0
  }
)
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,
    idUlp: ulp ? ulp.id : 0,
    idUid: uid ? uid.id : 0,
    idUp3: up3 ? up3.id : 0,
    bulan: bulan ? bulan.id : 10,
    tahun: bulan ? tahun.id : 2023
  })
  onResult((queryResult) => {
    if (queryResult.data != undefined) {
      data.value = queryResult.data.monalisaRekapitulasiEnsGangguan
    }
    console.log(queryResult.data)
    console.log(queryResult.loading)
    console.log(queryResult.networkStatus)
  })
  onError((error) => {
    console.log(error)
  })
}
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 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: null,
        id_uid: 0,
        nama_uid: '',
        id_up3: 0,
        nama_up3: '',
        id_ulp: 0,
        nama_ulp: '',
        mom_bulan_ini: 11020739,
        mom_bulan_kemarin: 6831980,
        persen_mom: -61.31105477475051,
        yoy_tahun_ini: 139773892,
        yoy_tahun_kemarin: 168209007,
        persen_yoy: 16.904632817908496
      },
      {
        id: 1,
        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: 14813,
        mom_bulan_kemarin: 47696,
        persen_mom: 68.94288829251929,
        yoy_tahun_ini: 354676,
        yoy_tahun_kemarin: 624303,
        persen_yoy: 43.18848379713056
      },
      {
        id: 2,
        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: 462651,
        mom_bulan_kemarin: 6730,
        persen_mom: -6774.45765230312,
        yoy_tahun_ini: 1643180,
        yoy_tahun_kemarin: 492691,
        persen_yoy: -233.51126771140534
      },
      {
        id: 3,
        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: 855320,
        mom_bulan_kemarin: 837741,
        persen_mom: -2.0983812419351566,
        yoy_tahun_ini: 8072389,
        yoy_tahun_kemarin: 11055796,
        persen_yoy: 26.985004064836215
      },
      {
        id: 4,
        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: 56259,
        mom_bulan_kemarin: 76807,
        persen_mom: 26.752769929824105,
        yoy_tahun_ini: 1098120,
        yoy_tahun_kemarin: 2481724,
        persen_yoy: 55.751727428191046
      },
      {
        id: 5,
        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: 478439,
        mom_bulan_kemarin: 1078502,
        persen_mom: 55.6385616345635,
        yoy_tahun_ini: 6845897,
        yoy_tahun_kemarin: 7566389,
        persen_yoy: 9.522270134406254
      },
      {
        id: 6,
        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: 559072,
        mom_bulan_kemarin: 182563,
        persen_mom: -206.23510788056728,
        yoy_tahun_ini: 7747710,
        yoy_tahun_kemarin: 7916066,
        persen_yoy: 2.12676347064312
      },
      {
        id: 7,
        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: 643731,
        mom_bulan_kemarin: 578381,
        persen_mom: -11.298780561602127,
        yoy_tahun_ini: 7155021,
        yoy_tahun_kemarin: 5869321,
        persen_yoy: -21.905429946666743
      },
      {
        id: 8,
        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: 289082,
        mom_bulan_kemarin: 416662,
        persen_mom: 30.61954293888092,
        yoy_tahun_ini: 1509396,
        yoy_tahun_kemarin: 3844624,
        persen_yoy: 60.740087977393884
      },
      {
        id: 9,
        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: 183310,
        mom_bulan_kemarin: 356299,
        persen_mom: 48.55163780981703,
        yoy_tahun_ini: 2039104,
        yoy_tahun_kemarin: 5170462,
        persen_yoy: 60.56244103524985
      },
      {
        id: 10,
        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: 86982,
        mom_bulan_kemarin: 39871,
        persen_mom: -118.15856136038725,
        yoy_tahun_ini: 1111887,
        yoy_tahun_kemarin: 2440181,
        persen_yoy: 54.4342407386993
      },
      {
        id: 11,
        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: 1042643,
        mom_bulan_kemarin: 2168988,
        persen_mom: 51.92951736016981,
        yoy_tahun_ini: 8579030,
        yoy_tahun_kemarin: 16227325,
        persen_yoy: 47.13219831364689
      },
      {
        id: 12,
        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: 469350,
        mom_bulan_kemarin: 575194,
        persen_mom: 18.401443686825665,
        yoy_tahun_ini: 4905051,
        yoy_tahun_kemarin: 4976204,
        persen_yoy: 1.4298650135725948
      },
      {
        id: 13,
        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: 163662,
        mom_bulan_kemarin: 83017,
        persen_mom: -97.14275389378079,
        yoy_tahun_ini: 1842074,
        yoy_tahun_kemarin: 686794,
        persen_yoy: -168.21346721142
      },
      {
        id: 14,
        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: 549380,
        mom_bulan_kemarin: 802333,
        persen_mom: 31.527183850097156,
        yoy_tahun_ini: 5168384,
        yoy_tahun_kemarin: 8611936,
        persen_yoy: 39.98580574681465
      }
    ]
  }
})
</script>
