<template>
  <Filters
    @reset-form="data = []"
    :report-button="true"
    @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="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"
        name="namaUlp"
      /> -->
      <DxColumn
        alignment="center"
        :min-width="170"
        data-type="text"
        data-field="nama_ulp"
        caption="Nama Unit"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn
        alignment="center"
        caption="Jumlah Dispatching Time 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>
        <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>

      <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 {
  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 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 { onResult, onError, loading, refetch } = useQuery(
  queries.monalisa.gangguan.rekap.dispatchingTimeGangguan,
  {
    // 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.monalisaDispatchingTimeGangguan
    }
    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: 230,
        nama_uid: 'WILAYAH KALIMANTAN TIMUR',
        id_up3: 231,
        nama_up3: 'UP3 SAMARINDA',
        id_ulp: 23156,
        nama_ulp: 'ULP SAMARINDA ULU',
        mom_bulan_ini: -213179,
        mom_bulan_kemarin: 673,
        persen_mom: 31775.994473750405,
        yoy_tahun_ini: 2069,
        yoy_tahun_kemarin: 1841,
        persen_yoy: -12.38457360130364
      },
      {
        id: 1,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 183,
        nama_up3: 'UP3 TANJUNGPINANG',
        id_ulp: 18302,
        nama_ulp: 'ULP KIJANG',
        mom_bulan_ini: -114,
        mom_bulan_kemarin: 373,
        persen_mom: 130.77740603697222,
        yoy_tahun_ini: 1324,
        yoy_tahun_kemarin: 1931,
        persen_yoy: 31.434489901605385
      },
      {
        id: 2,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 182,
        nama_up3: 'UP3 DUMAI',
        id_ulp: 18240,
        nama_ulp: 'ULP SELATPANJANG',
        mom_bulan_ini: -869,
        mom_bulan_kemarin: 493,
        persen_mom: 276.27086351782094,
        yoy_tahun_ini: 1454,
        yoy_tahun_kemarin: 702,
        persen_yoy: -107.12250712250713
      },
      {
        id: 3,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 120,
        nama_uid: 'WILAYAH SUMATERA UTARA',
        id_up3: 12400,
        nama_up3: 'UP3 PADANG SIDIMPUAN',
        id_ulp: 12415,
        nama_ulp: 'ULP NATAL',
        mom_bulan_ini: -16,
        mom_bulan_kemarin: 184,
        persen_mom: 108.95582431788799,
        yoy_tahun_ini: 426,
        yoy_tahun_kemarin: 536,
        persen_yoy: 20.522388059701495
      },
      {
        id: 4,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 230,
        nama_uid: 'WILAYAH KALIMANTAN TIMUR',
        id_up3: 231,
        nama_up3: 'UP3 SAMARINDA',
        id_ulp: 23102,
        nama_ulp: 'ULP SAMARINDA SEBERANG',
        mom_bulan_ini: -295198,
        mom_bulan_kemarin: 1025,
        persen_mom: 28899.899321562316,
        yoy_tahun_ini: 3193,
        yoy_tahun_kemarin: 2649,
        persen_yoy: -20.53605134012835
      },
      {
        id: 5,
        nama_regional: 'REGIONAL SULMAPANA',
        id_uid: 32,
        nama_uid: 'WILAYAH SULAWESI SELATAN, TENGGARA DAN BARAT',
        id_up3: 32200,
        nama_up3: 'UP3 WATAMPONE',
        id_ulp: 32240,
        nama_ulp: 'ULP SENGKANG',
        mom_bulan_ini: -107,
        mom_bulan_kemarin: 606,
        persen_mom: 117.772648051322,
        yoy_tahun_ini: 2082,
        yoy_tahun_kemarin: 1190,
        persen_yoy: -74.95798319327731
      },
      {
        id: 6,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 181,
        nama_up3: 'UP3 PEKANBARU',
        id_ulp: 18150,
        nama_ulp: 'ULP PERAWANG',
        mom_bulan_ini: -407,
        mom_bulan_kemarin: 916,
        persen_mom: 144.4547767778033,
        yoy_tahun_ini: 2897,
        yoy_tahun_kemarin: 2706,
        persen_yoy: -7.058388765705839
      },
      {
        id: 7,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 183,
        nama_up3: 'UP3 TANJUNGPINANG',
        id_ulp: 18306,
        nama_ulp: 'ULP TANJUNG BATU',
        mom_bulan_ini: -539,
        mom_bulan_kemarin: 69,
        persen_mom: 882.5544353427151,
        yoy_tahun_ini: 252,
        yoy_tahun_kemarin: 322,
        persen_yoy: 21.73913043478261
      },
      {
        id: 8,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 184,
        nama_up3: 'UP3 RENGAT',
        id_ulp: 18430,
        nama_ulp: 'ULP KUALA ENOK',
        mom_bulan_ini: -169,
        mom_bulan_kemarin: 188,
        persen_mom: 190.35948625202792,
        yoy_tahun_ini: 591,
        yoy_tahun_kemarin: 2752,
        persen_yoy: 78.52470930232558
      },
      {
        id: 9,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 181,
        nama_up3: 'UP3 PEKANBARU',
        id_ulp: 18170,
        nama_ulp: 'ULP SIAK SRI INDRAPURA',
        mom_bulan_ini: -11,
        mom_bulan_kemarin: 391,
        persen_mom: 102.89304140589162,
        yoy_tahun_ini: 1163,
        yoy_tahun_kemarin: 2109,
        persen_yoy: 44.85538169748696
      },
      {
        id: 10,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 182,
        nama_up3: 'UP3 DUMAI',
        id_ulp: 18260,
        nama_ulp: 'ULP BAGAN BATU',
        mom_bulan_ini: -600,
        mom_bulan_kemarin: 964,
        persen_mom: 162.33329138602699,
        yoy_tahun_ini: 3581,
        yoy_tahun_kemarin: 2965,
        persen_yoy: -20.775716694772346
      },
      {
        id: 11,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 230,
        nama_uid: 'WILAYAH KALIMANTAN TIMUR',
        id_up3: 231,
        nama_up3: 'UP3 SAMARINDA',
        id_ulp: 23112,
        nama_ulp: 'ULP TENGGARONG',
        mom_bulan_ini: -4524,
        mom_bulan_kemarin: 981,
        persen_mom: 561.2414600051343,
        yoy_tahun_ini: 3234,
        yoy_tahun_kemarin: 3514,
        persen_yoy: 7.968127490039841
      },
      {
        id: 12,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 183,
        nama_up3: 'UP3 TANJUNGPINANG',
        id_ulp: 18303,
        nama_ulp: 'ULP TANJUNG UBAN',
        mom_bulan_ini: -186,
        mom_bulan_kemarin: 191,
        persen_mom: 197.5691701222732,
        yoy_tahun_ini: 615,
        yoy_tahun_kemarin: 1058,
        persen_yoy: 41.87145557655955
      },
      {
        id: 13,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 184,
        nama_up3: 'UP3 RENGAT',
        id_ulp: 18410,
        nama_ulp: 'ULP RENGAT KOTA',
        mom_bulan_ini: -476,
        mom_bulan_kemarin: 955,
        persen_mom: 149.94027462127963,
        yoy_tahun_ini: 2931,
        yoy_tahun_kemarin: 4545,
        persen_yoy: 35.51155115511551
      },
      {
        id: 14,
        nama_regional: 'REGIONAL JMB',
        id_uid: 101,
        nama_uid: 'DISTRIBUSI JAWA TENGAH & DIY',
        id_up3: 52200,
        nama_up3: 'UP3 PURWOKERTO',
        id_ulp: 52201,
        nama_ulp: 'ULP PURWOKERTO KOTA',
        mom_bulan_ini: -63,
        mom_bulan_kemarin: 3642,
        persen_mom: 101.7401502360751,
        yoy_tahun_ini: 11511,
        yoy_tahun_kemarin: 14451,
        persen_yoy: 20.344612829561967
      },
      {
        id: 15,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 180,
        nama_uid: 'WILAYAH RIAU DAN KEPULAUAN RIAU',
        id_up3: 181,
        nama_up3: 'UP3 PEKANBARU',
        id_ulp: 18111,
        nama_ulp: 'ULP PEKANBARU KOTA BARAT',
        mom_bulan_ini: -1097,
        mom_bulan_kemarin: 1964,
        persen_mom: 155.88116671737166,
        yoy_tahun_ini: 6506,
        yoy_tahun_kemarin: 5316,
        persen_yoy: -22.385252069224983
      }
    ]
  }
})
</script>
