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

  <div id="data">
    <DxDataGrid
      ref="dataGridRef"
      :allow-column-reordering="true"
      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="onDataSelectionChanged"
      @exporting="onExporting"
      :allow-column-resizing="true"
      column-resizing-mode="widget"
      :word-wrap-enabled="true"
    >
      <DxGrouping expand-mode="rowClick" :auto-expand-all="false" />
      <DxSelection mode="single" />
      <DxPaging :enabled="false" />
      <DxScrolling column-rendering-mode="virtual" mode="virtual" />

      <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_regional"
        caption="Regional"
        css-class="custom-table-column"
        :group-index="0"
      />
      <DxColumn
        alignment="center"
        :min-width="170"
        data-type="text"
        data-field="nama_uid"
        caption="UID"
        css-class="custom-table-column"
        :group-index="1"
      />
      <DxColumn
        alignment="center"
        :min-width="170"
        data-type="text"
        data-field="nama_up3"
        caption="UP3"
        css-class="custom-table-column"
        :group-index="2"
      />
      <!-- <DxColumn
        alignment="center"
        :min-width="170"
        data-type="text"
        data-field="nama_ulp"
        caption="Nama ULP"
        css-class="custom-table-column"
        :group-index="3"
      /> -->
      <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(lastMonth)} ${lastYearMoM}`"
            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(e.value)"
        />
        <DxGroupItem
          :align-by-column="true"
          column="mom_bulan_ini"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :align-by-column="true"
          column="persen_mom"
          summary-type="avg"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
        <DxGroupItem
          :align-by-column="true"
          column="yoy_tahun_kemarin"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :align-by-column="true"
          column="yoy_tahun_ini"
          summary-type="sum"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :align-by-column="true"
          column="persen_yoy"
          summary-type="avg"
          display-format="{0}"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />

        <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(e.value)"
        />
        <DxTotalItem
          column="mom_bulan_ini"
          summary-type="sum"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="persen_mom"
          summary-type="avg"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
        <DxTotalItem
          column="yoy_tahun_kemarin"
          summary-type="sum"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="yoy_tahun_ini"
          summary-type="sum"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="persen_yoy"
          summary-type="avg"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
      </DxSummary>

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

      <template #formatText="{ data }">
        <p class="!text-left cursor-pointer">
          {{ data.text }}
        </p>
      </template>
    </DxDataGrid>
  </div>
  <BufferDialog v-if="loadingData || loadingSubData" />
</template>

<script setup lang="ts">
import Filters from '@/components/Form/Filters.vue'
import Type2 from '@/components/Form/FiltersType/Type2.vue'
import { onMounted, ref, watch } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import { getMonthName } from '@/utils/texts'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxGroupItem,
  DxGrouping,
  DxLoadPanel,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection,
  DxSummary,
  DxTotalItem
} from 'devextreme-vue/data-grid'
import { queries, requestGraphQl } from '@/utils/api/api.graphql'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'
import { apolloClient } from '@/utils/api/api.graphql'
import { provideApolloClient } from '@vue/apollo-composable'
import BufferDialog from '@/components/Dialogs/BufferDialog.vue'
import {
  exportToPDF,
  exportToXLSX,
  exportToDOCX

} from '@/report/Monalisa/Gangguan/Rekap/MonalisaGR_JumlahKaliGangguan'

const client = apolloClient()
provideApolloClient(client)
const position = { of: '#data' }
const showIndicator = ref(true)
const shading = ref(true)
const showPane = ref(true)
const data = ref<any[]>([])
const dataSub = ref<any[]>([])
const dataSelected = ref<any>()
const dataSubSelected = ref<any>()
const dialogDetail = ref(false)
const closedialogDetail = () => (dialogDetail.value = false)
const loadingData = ref(false)
const loadingSubData = ref(false)
const reportMeta = ref({
  regional: { id: 0, name: 'Semua Regional' },
  uid: { id: 0, name: 'Semua Unit Induk Distribusi/Wilayah' },
  up3: { id: 0, name: 'Semua Unit Pelaksanaan Pelayanan Pelanggan' },
  ulp: { id: 0, name: 'Semua Unit Layanan Pelanggan' },
  bulan: { id: new Date().getMonth(), name: getMonthName(new Date().getMonth()) },
  tahun: { id: new Date().getFullYear(), name: new Date().getFullYear().toString() },
  periode: '',
  lastMonth: new Date().getMonth() == 1 ? 12 : new Date().getMonth() - 1,
  lastYearMoM: new Date().getMonth() == 1 ? new Date().getFullYear() - 1 : new Date().getFullYear(),
  currentMonth: new Date().getMonth(),
  currentYear: new Date().getFullYear(),
  lastYear: new Date().getFullYear() - 1
})

const onExporting = (e: any) => {
  if (e.format === 'pdf') {
    exportToPDF(reportMeta.value, data.value)
  } else if (e.format === 'xlsx') {
    exportToXLSX(reportMeta.value, e)
  } else {
    exportToDOCX(reportMeta.value, data.value)
  }
}
const lastMonth = ref(new Date().getMonth() == 1 ? 12 : new Date().getMonth() - 1)
const lastYearMoM = ref(
  new Date().getMonth() == 1 ? new Date().getFullYear() - 1 : new Date().getFullYear()
)
const currentYear = ref(new Date().getFullYear())
const currentMonth = ref(new Date().getMonth())
const lastYear = ref(currentYear.value - 1)

const resetData = () => {
  data.value = []
  dataSub.value = []
}

const filterData = async (params: any) => {
  resetData()
  const { regional, ulp, uid, up3, bulan, tahun } = params
  lastMonth.value = bulan.id == 1 ? 12 : bulan.id - 1
  lastYearMoM.value = bulan.id == 1 ? tahun.id - 1 : tahun.id
  currentMonth.value = bulan.id
  currentYear.value = tahun.id
  lastYear.value = tahun.id - 1

  const query = {
    namaRegional: regional.name == 'Semua Regional' ? '' : regional.name,
    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
  }

  loadingData.value = true
  await requestGraphQl(queries.monalisa.gangguan.rekap.jumlahKaliGangguan, query)
    .then((result) => {
      if (result.data.data != undefined) {
        data.value = result.data.data.monalisaJumlahKaliGangguan
      } else {
        data.value = []
      }

      reportMeta.value = {
        regional: regional,
        uid: uid,
        up3: up3,
        ulp: ulp,
        bulan: bulan,
        tahun: tahun,
        periode: `${bulan.name} ${tahun.name}`,
        lastMonth: lastMonth.value,
        lastYearMoM: lastYearMoM.value,
        currentMonth: currentMonth.value,
        currentYear: currentYear.value,
        lastYear: lastYear.value
      }
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingData.value = false
    })
}

const getDetail = async () => {
  const dateValue = filters.value.periode.split(' s/d ')
  const selected = dataSelected.value

  const query = {
    dateFrom: dateValue[0]
      ? dateValue[0].split('-').reverse().join('-')
      : new Date().toISOString().slice(0, 10),
    dateTo: dateValue[1]
      ? dateValue[1].split('-').reverse().join('-')
      : new Date().toISOString().slice(0, 10),
    idUlp: selected?.id_ulp ? selected?.id_ulp : 0,
    idUid: selected?.id_uid ? selected?.id_uid : 0,
    idUp3: selected?.id_up3 ? selected?.id_up3 : 0
  }

  loadingSubData.value = true
  await requestGraphQl(queries.keluhan.rekap.rekapKeluhanAllDetail, query)
    .then((result) => {
      if (result.data.data != undefined) {
        dataSub.value = result.data.data.detailKeluhanAll
      } else {
        dataSub.value = []
      }
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingSubData.value = false
      dialogDetail.value = true
    })
}

const dataGridRef = ref<DxDataGrid | null>(null)
const clearSelection = () => {
  const dataGrid = dataGridRef.value!.instance!
  dataGrid.clearSelection()
}
const showDetail = () => {
  clearSelection()
  dataSubSelected.value = null
  getDetail()
}

const onDataSelectionChanged = ({ selectedRowsData }: any) => {
  if (selectedRowsData[0] != undefined) {
    dataSelected.value = selectedRowsData[0]
    showDetail()
  }
}

const onDataSubSelectionChanged = ({ selectedRowsData }: any) => {
  const data = selectedRowsData[0]
  dataSubSelected.value = 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>
