<template>
  <Filters @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"
        data-field="nama_uid"
        caption="UID"
        css-class="custom-table-column"
        cell-template="formatText"
        :group-index="0"
      />
      <DxColumn alignment="center" caption="Lapor Ulang 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"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="sum"
          show-in-column="mom_bulan_kemarin"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(parseFloat(e.value.toString()))"
        />
        <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()))"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="sum"
          show-in-column="mom_bulan_ini"
          css-class="!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()))"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="sum"
          show-in-column="persen_mom"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(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()))"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="sum"
          show-in-column="yoy_tahun_kemarin"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(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()))"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="sum"
          show-in-column="yoy_tahun_ini"
          css-class="!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()))"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="sum"
          show-in-column="persen_yoy"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(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,
  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 { 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.laporUlangGangguan,
  {
    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.monalisaRekapitulasiLaporUlangGangguan
    }
    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: 14,
        mom_bulan_kemarin: 35,
        persen_mom: 60,
        yoy_tahun_ini: 254,
        yoy_tahun_kemarin: 344,
        persen_yoy: 26.16279069767442
      },
      {
        id: 1,
        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: 1,
        mom_bulan_kemarin: 5,
        persen_mom: 80,
        yoy_tahun_ini: 4,
        yoy_tahun_kemarin: 16,
        persen_yoy: 75
      },
      {
        id: 2,
        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: 1,
        mom_bulan_kemarin: 2,
        persen_mom: 50,
        yoy_tahun_ini: 7,
        yoy_tahun_kemarin: 22,
        persen_yoy: 68.18181818181817
      },
      {
        id: 3,
        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: 1,
        mom_bulan_kemarin: 1,
        persen_mom: 0,
        yoy_tahun_ini: 1,
        yoy_tahun_kemarin: 4,
        persen_yoy: 75
      },
      {
        id: 4,
        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: 5,
        mom_bulan_kemarin: 12,
        persen_mom: 58.333333333333336,
        yoy_tahun_ini: 22,
        yoy_tahun_kemarin: 57,
        persen_yoy: 61.40350877192983
      },
      {
        id: 5,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 171,
        nama_uid: 'DISTRIBUSI LAMPUNG',
        id_up3: 17171,
        nama_up3: 'UP3 TANJUNGKARANG',
        id_ulp: 17180,
        nama_ulp: 'ULP TELUK BETUNG',
        mom_bulan_ini: 1,
        mom_bulan_kemarin: 5,
        persen_mom: 80,
        yoy_tahun_ini: 32,
        yoy_tahun_kemarin: 106,
        persen_yoy: 69.81132075471697
      },
      {
        id: 6,
        nama_regional: 'REGIONAL JMB',
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 146,
        nama_up3: 'UP3 KEDIRI',
        id_ulp: 51409,
        nama_ulp: 'ULP SUTOJAYAN',
        mom_bulan_ini: 1,
        mom_bulan_kemarin: 1,
        persen_mom: 0,
        yoy_tahun_ini: 1,
        yoy_tahun_kemarin: 20,
        persen_yoy: 95
      },
      {
        id: 7,
        nama_regional: 'REGIONAL JMB',
        id_uid: 427,
        nama_uid: 'DISTRIBUSI JAWA BARAT',
        id_up3: 531,
        nama_up3: 'UP3 BOGOR',
        id_ulp: 53821,
        nama_ulp: 'ULP BOGOR TIMUR',
        mom_bulan_ini: 8,
        mom_bulan_kemarin: 6,
        persen_mom: -33.33333333333333,
        yoy_tahun_ini: 69,
        yoy_tahun_kemarin: 102,
        persen_yoy: 32.35294117647059
      },
      {
        id: 8,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 140,
        nama_uid: 'WILAYAH SUMATERA SELATAN, JAMBI & BENGKULU (S2JB)',
        id_up3: 1406,
        nama_up3: 'UP3 OGAN ILIR',
        id_ulp: 14910,
        nama_ulp: 'ULP KAYU AGUNG',
        mom_bulan_ini: 1,
        mom_bulan_kemarin: 6,
        persen_mom: 83.33333333333334,
        yoy_tahun_ini: 4,
        yoy_tahun_kemarin: 22,
        persen_yoy: 81.81818181818183
      },
      {
        id: 9,
        nama_regional: 'REGIONAL JMB',
        id_uid: 427,
        nama_uid: 'DISTRIBUSI JAWA BARAT',
        id_up3: 547,
        nama_up3: 'UP3 CIKARANG',
        id_ulp: 53701,
        nama_ulp: 'ULP TAMBUN',
        mom_bulan_ini: 4,
        mom_bulan_kemarin: 1,
        persen_mom: -300,
        yoy_tahun_ini: 14,
        yoy_tahun_kemarin: 8,
        persen_yoy: -75
      },
      {
        id: 10,
        nama_regional: 'REGIONAL JMB',
        id_uid: 427,
        nama_uid: 'DISTRIBUSI JAWA BARAT',
        id_up3: 539,
        nama_up3: 'UP3 GUNUNG PUTRI',
        id_ulp: 53865,
        nama_ulp: 'ULP CILEUNGSI',
        mom_bulan_ini: 8,
        mom_bulan_kemarin: 8,
        persen_mom: 0,
        yoy_tahun_ini: 60,
        yoy_tahun_kemarin: 75,
        persen_yoy: 20
      },
      {
        id: 11,
        nama_regional: 'REGIONAL SULMAPANA',
        id_uid: 44,
        nama_uid: 'WILAYAH NUSA TENGGARA BARAT',
        id_up3: 441,
        nama_up3: 'UP3 MATARAM',
        id_ulp: 44140,
        nama_ulp: 'ULP PRAYA',
        mom_bulan_ini: 4,
        mom_bulan_kemarin: 50,
        persen_mom: 92,
        yoy_tahun_ini: 30,
        yoy_tahun_kemarin: 263,
        persen_yoy: 88.59315589353612
      },
      {
        id: 12,
        nama_regional: 'REGIONAL JMB',
        id_uid: 103,
        nama_uid: 'DISTRIBUSI JAWA TIMUR',
        id_up3: 151,
        nama_up3: 'UP3 PASURUAN',
        id_ulp: 51356,
        nama_ulp: 'ULP PROBOLINGGO',
        mom_bulan_ini: 17,
        mom_bulan_kemarin: 48,
        persen_mom: 64.58333333333334,
        yoy_tahun_ini: 53,
        yoy_tahun_kemarin: 156,
        persen_yoy: 66.02564102564102
      },
      {
        id: 13,
        nama_regional: 'REGIONAL JMB',
        id_uid: 427,
        nama_uid: 'DISTRIBUSI JAWA BARAT',
        id_up3: 538,
        nama_up3: 'UP3 DEPOK',
        id_ulp: 53872,
        nama_ulp: 'ULP CIBINONG',
        mom_bulan_ini: 1,
        mom_bulan_kemarin: 3,
        persen_mom: 66.66666666666666,
        yoy_tahun_ini: 29,
        yoy_tahun_kemarin: 38,
        persen_yoy: 23.684210526315788
      },
      {
        id: 14,
        nama_regional: 'REGIONAL SUMKAL',
        id_uid: 120,
        nama_uid: 'WILAYAH SUMATERA UTARA',
        id_up3: 12128,
        nama_up3: 'UP3 MEDAN UTARA',
        id_ulp: 12801,
        nama_ulp: 'ULP MEDAN TIMUR',
        mom_bulan_ini: 3,
        mom_bulan_kemarin: 5,
        persen_mom: 40,
        yoy_tahun_ini: 13,
        yoy_tahun_kemarin: 119,
        persen_yoy: 89.07563025210085
      }
    ]
  }
})
</script>
