<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>
    <DxDataGrid
      ref="dataGridRef"
      :allow-column-reordering="true"
      class="max-h-[calc(100vh-140px)] mb-10"
      :data-source="data"
      v-if="loadingData == false"
      :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
        :width="200"
        alignment="center"
        data-field="nama_ulp"
        caption="Nama Unit"
        css-class="custom-table-column"
        cell-template="formatText"
      />

      <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"
        caption="Jumlah dan Durasi RPT & RCT Gangguan"
        css-class="custom-table-column"
      >
        <DxColumn
          alignment="center"
          :caption="`${getMonthName(currentMonth)} ${currentYear}`"
          css-class="custom-table-column"
        >
          <DxColumn alignment="center" caption="Total RPT" css-class="custom-table-column">
            <DxColumn
              :width="150"
              alignment="center"
              caption="a"
              data-type="number"
              data-field="total_durasi_response_time_bulan_ini"
              css-class="custom-table-column"
              cell-template="formatNumber"
            />
          </DxColumn>
          <DxColumn alignment="center" caption="Jumlah Gangguan" css-class="custom-table-column">
            <DxColumn
              :width="150"
              alignment="center"
              caption="b"
              data-type="number"
              data-field="count_durasi_response_time_bulan_ini"
              css-class="custom-table-column"
              cell-template="formatNumber"
            />
          </DxColumn>
          <DxColumn alignment="center" caption="RPT Gangguan" css-class="custom-table-column">
            <DxColumn
              :width="150"
              alignment="center"
              caption="c=a/b"
              data-type="number"
              data-field="avg_durasi_response_time_bulan_ini"
              css-class="custom-table-column"
              cell-template="formatNumber"
            />
          </DxColumn>
          <DxColumn alignment="center" caption="Total RCT" css-class="custom-table-column">
            <DxColumn
              :width="150"
              alignment="center"
              caption="d"
              data-type="number"
              data-field="total_durasi_recovery_time_bulan_ini"
              css-class="custom-table-column"
              cell-template="formatNumber"
            />
          </DxColumn>
          <DxColumn alignment="center" caption="Jumlah Gangguan" css-class="custom-table-column">
            <DxColumn
              :width="150"
              alignment="center"
              caption="e"
              data-type="number"
              data-field="count_durasi_recovery_time_bulan_ini"
              css-class="custom-table-column"
              cell-template="formatNumber"
            />
          </DxColumn>
          <DxColumn alignment="center" caption="RCT Gangguan" css-class="custom-table-column">
            <DxColumn
              :width="150"
              alignment="center"
              caption="f=d/e"
              data-type="number"
              data-field="avg_durasi_recovery_time_bulan_ini"
              css-class="custom-table-column"
              cell-template="formatNumber"
            />
          </DxColumn>
        </DxColumn>
        <DxColumn
          alignment="center"
          :caption="`s.d ${getMonthName(currentMonth)} ${currentYear} `"
          css-class="custom-table-column"
        >
          <DxColumn alignment="center" caption="Total RPT" css-class="custom-table-column">
            <DxColumn
              :width="150"
              alignment="center"
              caption="a"
              data-type="number"
              data-field="total_durasi_response_time_tahun_ini"
              css-class="custom-table-column"
              cell-template="formatNumber"
            />
          </DxColumn>
          <DxColumn alignment="center" caption="Jumlah Gangguan" css-class="custom-table-column">
            <DxColumn
              :width="150"
              alignment="center"
              caption="b"
              data-type="number"
              data-field="count_durasi_response_time_tahun_ini"
              css-class="custom-table-column"
              cell-template="formatNumber"
            />
          </DxColumn>
          <DxColumn alignment="center" caption="RPT Gangguan" css-class="custom-table-column">
            <DxColumn
              :width="150"
              alignment="center"
              caption="c=a/b"
              data-type="number"
              data-field="avg_durasi_response_time_tahun_ini"
              css-class="custom-table-column"
              cell-template="formatNumber"
            />
          </DxColumn>
          <DxColumn alignment="center" caption="Total RCT" css-class="custom-table-column">
            <DxColumn
              :width="150"
              alignment="center"
              caption="d"
              data-type="number"
              data-field="total_durasi_recovery_time_tahun_ini"
              css-class="custom-table-column"
              cell-template="formatNumber"
            />
          </DxColumn>
          <DxColumn alignment="center" caption="Jumlah Gangguan" css-class="custom-table-column">
            <DxColumn
              :width="150"
              alignment="center"
              caption="e"
              data-type="number"
              data-field="count_durasi_recovery_time_tahun_ini"
              css-class="custom-table-column"
              cell-template="formatNumber"
            />
          </DxColumn>
          <DxColumn alignment="center" caption="RCT Gangguan" css-class="custom-table-column">
            <DxColumn
              :width="150"
              alignment="center"
              caption="f=d/e"
              data-type="number"
              data-field="avg_durasi_recovery_time_tahun_ini"
              css-class="custom-table-column"
              cell-template="formatNumber"
            />
          </DxColumn>
        </DxColumn>
      </DxColumn>

      <DxSummary :calculate-custom-summary="calculateCustomSummary">
        <DxGroupItem
          :show-in-group-footer="false"
          :align-by-column="true"
          summary-type="custom"
          show-in-column="total_durasi_response_time_bulan_ini"
          name="total_durasi_response_time_bulan_ini"
          column="total_durasi_response_time_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_durasi_response_time_bulan_ini"
          name="count_durasi_response_time_bulan_ini"
          column="count_durasi_response_time_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="avg_durasi_response_time_bulan_ini"
          name="avg_durasi_response_time_bulan_ini"
          column="avg_durasi_response_time_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="total_durasi_recovery_time_bulan_ini"
          name="total_durasi_recovery_time_bulan_ini"
          column="total_durasi_recovery_time_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_durasi_recovery_time_bulan_ini"
          name="count_durasi_recovery_time_bulan_ini"
          column="count_durasi_recovery_time_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="avg_durasi_recovery_time_bulan_ini"
          name="avg_durasi_recovery_time_bulan_ini"
          column="avg_durasi_recovery_time_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="total_durasi_response_time_tahun_ini"
          name="total_durasi_response_time_tahun_ini"
          column="total_durasi_response_time_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_durasi_response_time_tahun_ini"
          name="count_durasi_response_time_tahun_ini"
          column="count_durasi_response_time_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="avg_durasi_response_time_tahun_ini"
          name="avg_durasi_response_time_tahun_ini"
          column="avg_durasi_response_time_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="total_durasi_recovery_time_tahun_ini"
          name="total_durasi_recovery_time_tahun_ini"
          column="total_durasi_recovery_time_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_durasi_recovery_time_tahun_ini"
          name="count_durasi_recovery_time_tahun_ini"
          column="count_durasi_recovery_time_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="avg_durasi_recovery_time_tahun_ini"
          name="avg_durasi_recovery_time_tahun_ini"
          column="avg_durasi_recovery_time_tahun_ini"
          css-class="!text-right"
          :customize-text="(e: any) => formatNumber(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,
  DxGroupItem,
  DxGrouping,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection,
  DxSummary
} from 'devextreme-vue/data-grid'
import { getMonthName } from '@/utils/texts'
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_JumlahDDRPTRCTGangguan'

const client = apolloClient()
provideApolloClient(client)
const currentYear = ref(new Date().getFullYear())
const currentMonth = ref(new Date().getMonth())
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: '',
  currentMonth: currentMonth.value,
  currentYear: currentYear.value
})

const grouping = ref<any[]>([
  {
    data: '',
    caption: 'NASIONAL'
  },
  {
    data: 'nama_regional',
    caption: 'Regional'
  },
  {
    data: 'nama_uid',
    caption: 'UID'
  },
  {
    data: 'nama_up3',
    caption: 'UP3'
  }
])

let total_durasi_response_time_bulan_ini = 0
let count_durasi_response_time_bulan_ini = 0
let total_durasi_recovery_time_bulan_ini = 0
let count_durasi_recovery_time_bulan_ini = 0
let total_durasi_response_time_tahun_ini = 0
let count_durasi_response_time_tahun_ini = 0
let total_durasi_recovery_time_tahun_ini = 0
let count_durasi_recovery_time_tahun_ini = 0
const calculateCustomSummary = (options: any) => {
  if (options.name === 'total_durasi_response_time_bulan_ini') {
    if (options.summaryProcess === 'calculate') {
      total_durasi_response_time_bulan_ini += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = total_durasi_response_time_bulan_ini
    }
  }

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

  if (options.name === 'avg_durasi_response_time_bulan_ini') {
    if (options.summaryProcess === 'start') {
      total_durasi_response_time_bulan_ini = 0
      count_durasi_response_time_bulan_ini = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue =
        total_durasi_response_time_bulan_ini / count_durasi_response_time_bulan_ini
    }
  }

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

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

  if (options.name === 'avg_durasi_recovery_time_bulan_ini') {
    if (options.summaryProcess === 'start') {
      total_durasi_recovery_time_bulan_ini = 0
      count_durasi_recovery_time_bulan_ini = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue =
        total_durasi_recovery_time_bulan_ini / count_durasi_recovery_time_bulan_ini
    }
  }

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

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

  if (options.name === 'avg_durasi_response_time_tahun_ini') {
    if (options.summaryProcess === 'start') {
      total_durasi_response_time_tahun_ini = 0
      count_durasi_response_time_tahun_ini = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue =
        total_durasi_response_time_tahun_ini / count_durasi_response_time_tahun_ini
    }
  }

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

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

  if (options.name === 'avg_durasi_recovery_time_tahun_ini') {
    if (options.summaryProcess === 'start') {
      total_durasi_recovery_time_tahun_ini = 0
      count_durasi_recovery_time_tahun_ini = 0
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue =
        total_durasi_recovery_time_tahun_ini / count_durasi_recovery_time_tahun_ini
    }
  }
}

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

const filterData = async (params: any) => {
  resetData()
  const { regional, ulp, uid, up3, bulan, tahun } = params

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

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

    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 : 10,
    tahun: bulan ? tahun.id : 2023
  }
  loadingData.value = true
  await requestGraphQl(queries.monalisa.gangguan.rekap.jumlahDurasiRptRctGangguan, query)
    .then((result) => {
      if (result.data.data != undefined) {
        data.value = result.data.data.monalisaJumlahDurasiRptRctGangguan
      } else {
        data.value = []
      }

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

  currentMonth.value = bulan.id
  currentYear.value = tahun.id
}

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 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<any>({
  regional: '',
  uid: 0,
  up3: 0,
  bulan: 2,
  tahun: 2024
})

onMounted(() => {
  getMonthName(filters.value.bulan.id)
})
</script>
