<template>
  <div class="mt-4 lg:mt-6 max-w-7xl">
    <h1 class="text-xl font-medium md:text-2xl text-dark">Laporan Pengaduan Total</h1>
  </div>
  <DxDataGrid
    ref="dataGridRef"
    :allow-column-reordering="true"
    class="max-h-[calc(100vh-140px)] mb-10"
    :show-column-lines="true"
    :show-row-lines="false"
    :show-borders="true"
    :row-alternation-enabled="true"
    :hover-state-enabled="true"
    @selection-changed="onDataSelectionChanged"
    :column-width="100"
    @exporting="onExporting"
    :allow-column-resizing="true"
    column-resizing-mode="widget"
    :word-wrap-enabled="true"
    :data-source="data"
  >
    <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="170"
      alignment="center"
      data-field="nama_ulp"
      caption="Nama Unit"
      css-class="custom-table-column"
      cell-template="formatText"
    />
    <DxColumn
      alignment="center"
      :min-width="170"
      data-type="text"
      data-field=""
      caption="Semua Unit"
      css-class="custom-table-column"
      :group-index="0"
    />
    <DxColumn
      alignment="center"
      :min-width="170"
      data-type="text"
      data-field="id_uid"
      caption="UID"
      css-class="custom-table-column"
      :group-index="1"
      name="namaUID"
      :calculate-group-value="(rowData: any) => rowData.nama_uid"
    />
    <DxColumn
      alignment="center"
      :min-width="170"
      data-type="text"
      data-field="id_up3"
      caption="UP3"
      css-class="custom-table-column"
      :group-index="1"
      name="namaUID"
      :calculate-group-value="(rowData: any) => rowData.nama_up3"
    />
    <DxColumn alignment="center" caption="Total Petugas" css-class="custom-table-column">
      <DxColumn
        :width="170"
        alignment="center"
        data-field="total_petugas"
        caption="a"
        css-class="custom-table-column"
        cell-template="formatNumber"
      />
    </DxColumn>
    <DxColumn
      alignment="center"
      caption="Total Petugas Yang Pengaduan Diselesaikan Secara Anomali"
      css-class="custom-table-column"
    >
      <DxColumn alignment="center" caption="PLN Mobile" css-class="custom-table-column">
        <DxColumn alignment="center" caption="b" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="anomali_pln_mobile_marking"
            data-type="number"
            caption="Marking"
            css-class="custom-table-column"
            cell-template="formatNumberPLNMobileMarking"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="anomali_pln_mobile_non_marking"
            data-type="number"
            caption="Non Marking"
            css-class="custom-table-column"
            cell-template="formatNumberPLNMobileNonMarking"
          />
        </DxColumn>
      </DxColumn>
      <DxColumn alignment="center" caption="CC 123" css-class="custom-table-column">
        <DxColumn alignment="center" caption="c" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="anomali_cc123_marking"
            data-type="number"
            caption="Marking"
            css-class="custom-table-column"
            cell-template="formatNumberCCMarking"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="anomali_cc123_non_marking"
            data-type="number"
            caption="Non Marking"
            css-class="custom-table-column"
            cell-template="formatNumberCCNonMarking"
          />
        </DxColumn>
      </DxColumn>
      <DxColumn alignment="center" caption="Total" css-class="custom-table-column">
        <DxColumn alignment="center" caption="d=b+c" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="total_anomali_marking"
            data-type="number"
            caption="Marking"
            css-class="custom-table-column"
            cell-template="formatNumberTotalMarking"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="total_anomali_non_marking"
            data-type="number"
            caption="Non Marking"
            css-class="custom-table-column"
            cell-template="formatNumberTotalNonMarking"
          />
        </DxColumn>
      </DxColumn>
    </DxColumn>
    <DxColumn
      alignment="center"
      caption="% Petugas Yang Pengaduan Diselesaikan Secara Anomali"
      css-class="custom-table-column"
    >
      <DxColumn alignment="center" caption="PLN Mobile" css-class="custom-table-column">
        <DxColumn alignment="center" caption="e=b/a" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="persen_anomali_pln_mobile_marking"
            data-type="number"
            caption="Marking"
            css-class="custom-table-column"
            cell-template="formatPercentage"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="persen_anomali_pln_mobile_non_marking"
            data-type="number"
            caption="Non Marking"
            css-class="custom-table-column"
            cell-template="formatPercentage"
          />
        </DxColumn>
      </DxColumn>
      <DxColumn alignment="center" caption="CC 123" css-class="custom-table-column">
        <DxColumn alignment="center" caption="f=c/a" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="persen_anomali_cc123_marking"
            data-type="number"
            caption="Marking"
            css-class="custom-table-column"
            cell-template="formatPercentage"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="persen_anomali_cc123_non_marking"
            data-type="number"
            caption="Non Marking"
            css-class="custom-table-column"
            cell-template="formatPercentage"
          />
        </DxColumn>
      </DxColumn>
      <DxColumn alignment="center" caption="Total" css-class="custom-table-column">
        <DxColumn alignment="center" caption="g=e+f" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="persen_anomali_marking"
            data-type="number"
            caption="Marking"
            css-class="custom-table-column"
            cell-template="formatPercentage"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="persen_anomali_non_marking"
            data-type="number"
            caption="Non Marking"
            css-class="custom-table-column"
            cell-template="formatPercentage"
          />
        </DxColumn>
      </DxColumn>
    </DxColumn>

    <template #formatNumberPLNMobileMarking="{ data }">
      <p
        class="text-right cursor-pointer"
        @click="setParameterRequest({ media: 'PLN Mobile', marking: 1 })"
      >
        {{
          isNumber(data.text)
            ? data.column.caption == '%'
              ? formatPercentage(data.text)
              : formatNumber(data.text)
            : data.text
        }}
      </p>
    </template>

    <template #formatNumberPLNMobileNonMarking="{ data }">
      <p
        class="text-right cursor-pointer"
        @click="setParameterRequest({ media: 'PLN Mobile', marking: 2 })"
      >
        {{
          isNumber(data.text)
            ? data.column.caption == '%'
              ? formatPercentage(data.text)
              : formatNumber(data.text)
            : data.text
        }}
      </p>
    </template>

    <template #formatNumberCCMarking="{ data }">
      <p
        class="text-right cursor-pointer"
        @click="setParameterRequest({ media: 'Call PLN 123', marking: 1 })"
      >
        {{
          isNumber(data.text)
            ? data.column.caption == '%'
              ? formatPercentage(data.text)
              : formatNumber(data.text)
            : data.text
        }}
      </p>
    </template>

    <template #formatNumberCCNonMarking="{ data }">
      <p
        class="text-right cursor-pointer"
        @click="setParameterRequest({ media: 'Call PLN 123', marking: 2 })"
      >
        {{
          isNumber(data.text)
            ? data.column.caption == '%'
              ? formatPercentage(data.text)
              : formatNumber(data.text)
            : data.text
        }}
      </p>
    </template>

    <template #formatNumberTotalMarking="{ data }">
      <p class="text-right cursor-pointer" @click="setParameterRequest({ media: '', marking: 1 })">
        {{
          isNumber(data.text)
            ? data.column.caption == '%'
              ? formatPercentage(data.text)
              : formatNumber(data.text)
            : data.text
        }}
      </p>
    </template>

    <template #formatNumberTotalNonMarking="{ data }">
      <p class="text-right cursor-pointer" @click="setParameterRequest({ media: '', marking: 2 })">
        {{
          isNumber(data.text)
            ? data.column.caption == '%'
              ? formatPercentage(data.text)
              : formatNumber(data.text)
            : data.text
        }}
      </p>
    </template>

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

    <template #formatPercentage="{ data }">
      <p
        class="text-right cursor-pointer"
        @click="setParameterRequest({ media: null, marking: null })"
      >
        {{ isNumber(data.text) ? formatPercentage(data.text) : data.text }}
      </p>
    </template>

    <template #formatText="{ data }">
      <p
        class="text-left cursor-pointer"
        @click="setParameterRequest({ media: null, marking: null })"
      >
        {{ data.text }}
      </p>
    </template>

    <template #formatTime="{ data }">
      <p class="!text-right" @click="setParameterRequest({ media: null, marking: null })">
        {{ parseInt(data.text) ? formatWaktu(data.text) : '-' }}
      </p>
    </template>

    <DxSummary>
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="total_petugas"
        summary-type="sum"
        css-class="!text-right"
        :customize-text="(e: any) => formatNumber(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="anomali_pln_mobile_marking"
        summary-type="sum"
        css-class="!text-right"
        :customize-text="(e: any) => formatNumber(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="anomali_pln_mobile_non_marking"
        summary-type="sum"
        css-class="!text-right"
        :customize-text="(e: any) => formatNumber(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="anomali_cc123_marking"
        summary-type="sum"
        css-class="!text-right"
        :customize-text="(e: any) => formatNumber(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="anomali_cc123_non_marking"
        summary-type="sum"
        css-class="!text-right"
        :customize-text="(e: any) => formatNumber(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="total_anomali_marking"
        summary-type="sum"
        css-class="!text-right"
        :customize-text="(e: any) => formatNumber(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="total_anomali_non_marking"
        summary-type="sum"
        css-class="!text-right"
        :customize-text="(e: any) => formatNumber(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="persen_anomali_pln_mobile_marking"
        summary-type="avg"
        css-class="!text-right"
        :customize-text="(e: any) => formatPercentage(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="persen_anomali_pln_mobile_non_marking"
        summary-type="avg"
        css-class="!text-right"
        :customize-text="(e: any) => formatPercentage(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="persen_anomali_cc123_marking"
        summary-type="avg"
        css-class="!text-right"
        :customize-text="(e: any) => formatPercentage(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="persen_anomali_cc123_non_marking"
        summary-type="avg"
        css-class="!text-right"
        :customize-text="(e: any) => formatPercentage(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="persen_anomali_marking"
        summary-type="avg"
        css-class="!text-right"
        :customize-text="(e: any) => formatPercentage(e.value)"
      />
      <DxGroupItem
        :show-in-group-footer="false"
        :align-by-column="true"
        column="persen_anomali_non_marking"
        summary-type="avg"
        css-class="!text-right"
        :customize-text="(e: any) => formatPercentage(e.value)"
      />
    </DxSummary>
  </DxDataGrid>

  <div class="mt-4 lg:mt-6 max-w-7xl">
    <h1 class="text-xl font-medium md:text-2xl text-dark">
      Laporan Pengaduan {{ parameterRequest.media != null ? parameterRequest.media : '' }}
      {{
        parameterRequest.marking != null
          ? parameterRequest.marking == 1
            ? 'Marking'
            : 'Non Marking'
          : ''
      }}
    </h1>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxGroupItem,
  DxGrouping,
  DxLoadPanel,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection,
  DxSummary
} from 'devextreme-vue/data-grid'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'
import { formatWaktu } from '@/components/Form/FiltersType/reference'
import { queries, requestGraphQl } from '@/utils/api/api.graphql'
import { exportToPDF, exportToXLSX } from '@/report/Anomali/Gangguan/Anomali_LAPPGP_LPT'

const position = { of: '#data' }
const showIndicator = ref(true)
const shading = ref(true)
const showPane = ref(true)
const props = defineProps({
  data: Array as () => any[],
  filters: Object as () => any
})
const emit = defineEmits(['update:dataSub', 'update:loadingSubData', 'update:marking'])
const filters = ref<any>(computed(() => props.filters))
const data = computed(() => props.data)
const dataSub = ref<any[]>([])
const dataSelected = ref<any>(null)
const dataSubSelected = ref<any>(null)
const dialogDetail = ref(false)
const loadingSubData = ref(false)
const agreeToShowDialog = ref(false)
const reportMeta = ref<any>(computed(() => props.filters))
const parameterRequest = ref<any>({
  media: null,
  marking: null
})

const setParameterRequest = (data: any) => {
  parameterRequest.value = data
  const parameter = parameterRequest.value
  if (parameter.media != null && parameter.marking != null) {
    emit('update:marking', parameter.marking)
    agreeToShowDialog.value = true
  } else {
    agreeToShowDialog.value = false
  }
}

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

const getDetail = async () => {
  resetData()
  const { jenisLaporan } = filters.value

  const selected = dataSelected.value
  const query = {
    idUlp: selected?.id_ulp ? selected?.id_ulp : 0,
    idUid: selected?.id_uid ? selected?.id_uid : 0,
    idUp3: selected?.id_up3 ? selected?.id_up3 : 0,
    namaRegional: selected?.nama_regional ? selected?.nama_regional : '',
    media: parameterRequest.value?.media,
    isMarking: parameterRequest.value?.marking
  }

  loadingSubData.value = true
  emit('update:loadingSubData', loadingSubData.value)
  await requestGraphQl(
    jenisLaporan.name == 'Laporan Berulang Unit'
      ? queries.anomali.gangguan.petugasBerulangDetail
      : jenisLaporan.name == 'Laporan Rating Negatif'
        ? queries.anomali.gangguan.petugasRatingNegatifDetail
        : queries.anomali.gangguan.petugasSkipStepDetail,
    query
  )
    .then((result) => {
      if (result.data.data != undefined) {
        if (jenisLaporan.name == 'Laporan Berulang Unit') {
          dataSub.value = result.data.data.detailAnomaliPenangananPengaduanGangguanPetugasBerulang
        } else if (jenisLaporan.name == 'Laporan Rating Negatif') {
          dataSub.value =
            result.data.data.detailAnomaliPenangananPengaduanGangguanPetugasRatingNegatif
        } else {
          dataSub.value = result.data.data.detailAnomaliPenangananPengaduanGangguanPetugasSkipStep
        }
      } else {
        dataSub.value = []
      }
      emit('update:dataSub', dataSub.value)
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingSubData.value = false
      dialogDetail.value = true
      emit('update:loadingSubData', loadingSubData.value)
    })
}

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

const showDetail = () => {
  clearSelection()
  dataSub.value = []
  dataSubSelected.value = null
  if (agreeToShowDialog.value) {
    getDetail()
  }
}

const onExporting = (e: any) => {
  if (e.format === 'pdf') {
    exportToPDF(reportMeta.value, data.value)
  } else if (e.format === 'xlsx') {
    exportToXLSX(reportMeta.value, e)
  } else {
  }
}

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