<template>
  <Filters
    @run-report="() => exportToPDF(reportMeta, data, true)"
    @reset-form="data = []"
    @run-search="() => filterData(filters)"
    :report-button="true"
    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
        v-if="grouping.length > 0"
        v-for="(group, index) in grouping"
        :width="150"
        alignment="center"
        :data-field="group.data"
        :caption="group.caption"
        css-class="custom-table-column"
        cell-template="formatText"
        :group-index="index"
      />
      <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"
        caption="Jumlah RPT Kali Keluhan"
        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
            :visible="false"
            :width="150"
            alignment="center"
            data-field="count_mom_bulan_kemarin"
            data-type="number"
            :caption="`Count ${getMonthName(lastMonth)} ${lastYearMoM}`"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :visible="false"
            :width="150"
            alignment="center"
            data-field="cal_mom_bulan_kemarin"
            :caption="`Cal ${getMonthName(lastMonth)} ${lastYearMoM}`"
            data-type="number"
            css-class="custom-table-column"
            cell-template="formatNumber"
            :calculate-cell-value="
              (rowData: any) => rowData.count_mom_bulan_kemarin * rowData.mom_bulan_kemarin
            "
          />
          <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
            :visible="false"
            :width="150"
            alignment="center"
            data-field="count_mom_bulan_ini"
            data-type="number"
            :caption="`Count ${getMonthName(currentMonth)} ${currentYear}`"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :visible="false"
            :width="150"
            alignment="center"
            data-field="cal_mom_bulan_ini"
            data-type="number"
            css-class="custom-table-column"
            cell-template="formatNumber"
            :calculate-cell-value="
              (rowData: any) => rowData.count_mom_bulan_ini * rowData.mom_bulan_ini
            "
          />
          <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
            :visible="false"
            :width="150"
            alignment="center"
            data-field="count_yoy_tahun_kemarin"
            data-type="number"
            :caption="`Count ${getMonthName(currentMonth)} ${lastYear}`"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :visible="false"
            :width="150"
            alignment="center"
            data-field="cal_yoy_tahun_kemarin"
            data-type="number"
            css-class="custom-table-column"
            cell-template="formatNumber"
            :calculate-cell-value="
              (rowData: any) => rowData.count_yoy_tahun_kemarin * rowData.yoy_tahun_kemarin
            "
          />
          <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
            :visible="false"
            :width="150"
            alignment="center"
            data-field="count_yoy_tahun_ini"
            data-type="number"
            :caption="`Count ${getMonthName(currentMonth)} ${currentYear}`"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
          <DxColumn
            :visible="false"
            :width="150"
            alignment="center"
            data-field="cal_yoy_tahun_ini"
            data-type="number"
            css-class="custom-table-column"
            cell-template="formatNumber"
            :calculate-cell-value="
              (rowData: any) => rowData.count_yoy_tahun_ini * rowData.yoy_tahun_ini
            "
          />
          <DxColumn
            :width="70"
            alignment="center"
            data-field="persen_yoy"
            data-type="number"
            caption="%"
            css-class="custom-table-column"
            cell-template="formatNumber"
          />
        </DxColumn>
      </DxColumn>

      <DxSummary :calculate-custom-summary="calculateCustomSummary">
        <DxTotalItem
          :display-format="`RATA-RATA`"
          show-in-column="nama_ulp"
          css-class="text-white !text-left"
        />
        <DxTotalItem
          column="mom_bulan_kemarin"
          name="mom_bulan_kemarin"
          summary-type="custom"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="count_mom_bulan_kemarin"
          name="count_mom_bulan_kemarin"
          summary-type="custom"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="cal_mom_bulan_kemarin"
          name="cal_mom_bulan_kemarin"
          summary-type="custom"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="mom_bulan_ini"
          name="mom_bulan_ini"
          summary-type="custom"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="cal_mom_bulan_ini"
          name="cal_mom_bulan_ini"
          summary-type="custom"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="count_mom_bulan_ini"
          name="count_mom_bulan_ini"
          summary-type="custom"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="persen_mom"
          name="persen_mom"
          summary-type="custom"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
        <DxTotalItem
          column="yoy_tahun_kemarin"
          name="yoy_tahun_kemarin"
          summary-type="custom"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="cal_yoy_tahun_kemarin"
          name="cal_yoy_tahun_kemarin"
          summary-type="custom"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="count_yoy_tahun_kemarin"
          name="count_yoy_tahun_kemarin"
          summary-type="custom"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="yoy_tahun_ini"
          name="yoy_tahun_ini"
          summary-type="custom"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="cal_yoy_tahun_ini"
          name="cal_yoy_tahun_ini"
          summary-type="custom"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="count_yoy_tahun_ini"
          name="count_yoy_tahun_ini"
          summary-type="custom"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxTotalItem
          column="persen_yoy"
          name="persen_yoy"
          summary-type="custom"
          display-format="{0}"
          css-class="text-white !text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />

        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          display-format="{0}"
          show-in-column="mom_bulan_kemarin"
          name="mom_bulan_kemarin"
          column="mom_bulan_kemarin"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          display-format="{0}"
          show-in-column="cal_mom_bulan_kemarin"
          name="cal_mom_bulan_kemarin"
          column="cal_mom_bulan_kemarin"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          display-format="{0}"
          show-in-column="count_mom_bulan_kemarin"
          name="count_mom_bulan_kemarin"
          column="count_mom_bulan_kemarin"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          show-in-column="mom_bulan_ini"
          name="mom_bulan_ini"
          column="mom_bulan_ini"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          show-in-column="cal_mom_bulan_ini"
          name="cal_mom_bulan_ini"
          column="cal_mom_bulan_ini"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          show-in-column="count_mom_bulan_ini"
          name="count_mom_bulan_ini"
          column="count_mom_bulan_ini"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          show-in-column="persen_mom"
          name="persen_mom"
          column="persen_mom"
          css-class="!text-right"
          :customize-text="(e: any) => formatPercentage(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          show-in-column="yoy_tahun_kemarin"
          name="yoy_tahun_kemarin"
          column="yoy_tahun_kemarin"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          show-in-column="cal_yoy_tahun_kemarin"
          name="cal_yoy_tahun_kemarin"
          column="cal_yoy_tahun_kemarin"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          show-in-column="count_yoy_tahun_kemarin"
          name="count_yoy_tahun_kemarin"
          column="count_yoy_tahun_kemarin"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          show-in-column="yoy_tahun_ini"
          name="yoy_tahun_ini"
          column="yoy_tahun_ini"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          show-in-column="cal_yoy_tahun_ini"
          name="cal_yoy_tahun_ini"
          column="cal_yoy_tahun_ini"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          show-in-column="count_yoy_tahun_ini"
          name="count_yoy_tahun_ini"
          column="count_yoy_tahun_ini"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(e.value)"
        />
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          show-in-column="persen_yoy"
          name="persen_yoy"
          column="persen_yoy"
          css-class="!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 } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection,
  DxSummary,
  DxGroupItem,
  DxTotalItem,
  DxGrouping
} from 'devextreme-vue/data-grid'
import { getMonthName } from '@/utils/texts'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'
import { queries, requestGraphQl } from '@/utils/api/api.graphql'
import BufferDialog from '@/components/Dialogs/BufferDialog.vue'
import {
  exportToPDF,
  exportToXLSX,
  exportToDOCX
} from '@/report/Monalisa/Keluhan/Rekap/MonalisaKR_ResponseTimeKeluhan'

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 grouping = ref<any[]>([
  {
    data: 'nama_regional',
    caption: 'Regional'
  },
  {
    data: 'nama_uid',
    caption: 'UID'
  },
  {
    data: 'nama_up3',
    caption: 'UP3'
  }
])

let mom_bulan_kemarin = 0
let count_mom_bulan_kemarin = 0
let cal_mom_bulan_kemarin = 0

let mom_bulan_ini = 0
let count_mom_bulan_ini = 0
let cal_mom_bulan_ini = 0

let yoy_tahun_kemarin = 0
let count_yoy_tahun_kemarin = 0
let cal_yoy_tahun_kemarin = 0

let yoy_tahun_ini = 0
let count_yoy_tahun_ini = 0
let cal_yoy_tahun_ini = 0
const calculateCustomSummary = (options: any) => {
  if (options.name === 'count_mom_bulan_kemarin') {
    if (options.summaryProcess === 'calculate') {
      count_mom_bulan_kemarin += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = count_mom_bulan_kemarin
    }
  }

  if (options.name === 'cal_mom_bulan_kemarin') {
    if (options.summaryProcess === 'calculate') {
      cal_mom_bulan_kemarin += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = cal_mom_bulan_kemarin
    }
  }

  if (options.name === 'mom_bulan_kemarin') {
    if (options.summaryProcess === 'start') {
      cal_mom_bulan_kemarin = 0
      count_mom_bulan_kemarin = 0
    } else if (options.summaryProcess === 'calculate') {
      mom_bulan_kemarin += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = cal_mom_bulan_kemarin / count_mom_bulan_kemarin
    }
  }

  if (options.name === 'count_mom_bulan_ini') {
    if (options.summaryProcess === 'calculate') {
      count_mom_bulan_ini += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = count_mom_bulan_ini
    }
  }

  if (options.name === 'cal_mom_bulan_ini') {
    if (options.summaryProcess === 'calculate') {
      cal_mom_bulan_ini += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = cal_mom_bulan_ini
    }
  }

  if (options.name === 'mom_bulan_ini') {
    if (options.summaryProcess === 'start') {
      cal_mom_bulan_ini = 0
      count_mom_bulan_ini = 0
    } else if (options.summaryProcess === 'calculate') {
      mom_bulan_ini += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = cal_mom_bulan_ini / count_mom_bulan_ini
    }
  }

  if (options.name === 'persen_mom') {
    if (options.summaryProcess === 'start') {
      mom_bulan_kemarin = 0
      mom_bulan_ini = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue =
        mom_bulan_kemarin == 0 ? 0 : ((mom_bulan_kemarin - mom_bulan_ini) / mom_bulan_kemarin) * 100
    }
  }

  if (options.name === 'count_yoy_tahun_kemarin') {
    if (options.summaryProcess === 'calculate') {
      count_yoy_tahun_kemarin += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = count_yoy_tahun_kemarin
    }
  }

  if (options.name === 'cal_yoy_tahun_kemarin') {
    if (options.summaryProcess === 'calculate') {
      cal_yoy_tahun_kemarin += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = cal_yoy_tahun_kemarin
    }
  }

  if (options.name === 'yoy_tahun_kemarin') {
    if (options.summaryProcess === 'start') {
      cal_yoy_tahun_kemarin = 0
      count_yoy_tahun_kemarin = 0
    } else if (options.summaryProcess === 'calculate') {
      yoy_tahun_kemarin += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = cal_yoy_tahun_kemarin / count_yoy_tahun_kemarin
    }
  }

  if (options.name === 'count_yoy_tahun_ini') {
    if (options.summaryProcess === 'calculate') {
      count_yoy_tahun_ini += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = count_yoy_tahun_ini
    }
  }

  if (options.name === 'cal_yoy_tahun_ini') {
    if (options.summaryProcess === 'calculate') {
      cal_yoy_tahun_ini += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = cal_yoy_tahun_ini
    }
  }

  if (options.name === 'yoy_tahun_ini') {
    if (options.summaryProcess === 'start') {
      cal_yoy_tahun_ini = 0
      count_yoy_tahun_ini = 0
    } else if (options.summaryProcess === 'calculate') {
      yoy_tahun_ini += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = cal_yoy_tahun_ini / count_yoy_tahun_ini
    }
  }

  if (options.name === 'persen_yoy') {
    if (options.summaryProcess === 'start') {
      yoy_tahun_kemarin = 0
      yoy_tahun_ini = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue =
        yoy_tahun_kemarin == 0 ? 0 : ((yoy_tahun_kemarin - yoy_tahun_ini) / yoy_tahun_kemarin) * 100
    }
  }
}

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 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 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

  var groupList: any[] = [
    {
      data: 'nama_regional',
      caption: 'Regional'
    },
    {
      data: 'nama_uid',
      caption: 'UID'
    },
    {
      data: 'nama_up3',
      caption: 'UP3'
    }
  ]

  if (uid?.id != 0) {
    groupList.forEach((item, index) => {
      if (item.caption == 'Regional') {
        groupList.splice(index, 1)
      }
    })

    if (up3?.id != 0) {
      groupList.forEach((item, index) => {
        if (item.caption == 'UID') {
          groupList.splice(index, 1)
        }
      })

      if (ulp?.id != 0) {
        groupList.forEach((item, index) => {
          if (item.caption == 'UP3') {
            groupList.splice(index, 1)
          }
        })
      }
    }
  }
  grouping.value = groupList

  const query = {
    namaRegional: regional.name == 'Semua Regional' ? '' : regional.name,
    idUlp: ulp ? ulp.id : 0,
    idUid: uid ? uid.id : 0,
    idUp3: up3 ? up3.id : 0,
    bulan: bulan ? bulan.id : currentMonth.value,
    tahun: bulan ? tahun.id : currentYear.value
  }

  loadingData.value = true
  await requestGraphQl(queries.monalisa.keluhan.rekap.responseTimeKeluhan, query)
    .then((result) => {
      if (result.data.data != undefined) {
        data.value = result.data.data.monalisaResponseTimeKeluhan
      } 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 = [
      {
        nama_regional: 'REGIONAL JMB',
        id_uid: 427,
        nama_uid: 'DISTRIBUSI JAWA BARAT',
        id_up3: 542,
        nama_up3: 'UP3 MAJALAYA',
        id_ulp: 53536,
        nama_ulp: 'ULP PRIMA MAJALAYA (TT/TM)',
        mom_bulan_ini: 4726,
        mom_bulan_kemarin: 943,
        persen_mom: -401.1664899257688,
        yoy_tahun_ini: 26445,
        yoy_tahun_kemarin: 19634,
        persen_yoy: -34.68982377508404
      }
    ]
  }
})
</script>
