<template>
  <Filters @reset-form="data = []" @run-search="() => filterData(filters)" class="mb-4">
    <Type3 @update:filters="(value) => (filters = value)" />
  </Filters>

  <div id="data">
    <DxDataGrid
      @cell-click="onCellClicked"
      ref="dataGridRef"
      :data-source="data"
      v-if="loadingData == false"
      :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"
      @exporting="onExporting"
      :allow-column-resizing="true"
      column-resizing-mode="widget"
      :word-wrap-enabled="true"
    >
      <DxGrouping :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"
        data-field="nama_ulp"
        caption="Nama Unit"
        css-class="custom-table-column"
        cell-template="formatText"
      />
      <DxColumn alignment="center" caption="Total WO" css-class="custom-table-column">
        <DxColumn alignment="center" caption="CC 123" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="wo_cc123"
            data-type="number"
            caption="a"
            css-class="custom-table-column"
            cell-template="formatNumberWoCC"
          />
        </DxColumn>
        <DxColumn alignment="center" caption="PLN Mobile" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="wo_pln_mobile"
            data-type="number"
            caption="b"
            css-class="custom-table-column"
            cell-template="formatNumberWoPLMMobile"
          />
        </DxColumn>
        <DxColumn alignment="center" caption="COMCEN" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="wo_comcen"
            data-type="number"
            caption="c"
            css-class="custom-table-column"
            cell-template="formatNumberWoComcen"
          />
        </DxColumn>
        <DxColumn alignment="center" caption="Total" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="wo_total"
            data-type="number"
            caption="d=a+b+c"
            css-class="custom-table-column"
            cell-template="formatNumberWoTotal"
          />
        </DxColumn>
      </DxColumn>
      <DxColumn alignment="center" caption="Rekomendasi sistem" css-class="custom-table-column">
        <DxColumn alignment="center" caption="Mendatangkan Petugas" css-class="custom-table-column">
          <DxColumn
            :width="150"
            alignment="center"
            data-field="rekomendasi_mendatangkan_petugas"
            data-type="number"
            caption="e"
            css-class="custom-table-column"
            cell-template="formatNumberRekomendasi1"
          />
        </DxColumn>
        <DxColumn
          alignment="center"
          caption="Diberikan ke Pelanggan"
          css-class="custom-table-column"
        >
          <DxColumn
            :width="150"
            alignment="center"
            data-field="rekomendasi_diberikan_ke_pelanggan"
            data-type="number"
            caption="f"
            css-class="custom-table-column"
            cell-template="formatNumberRekomendasi2"
          />
        </DxColumn>
      </DxColumn>
      <DxColumn alignment="center" caption="DLPD" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="dpld"
          data-type="number"
          caption="g"
          css-class="custom-table-column"
          cell-template="formatNumberDlpd"
        />
      </DxColumn>
      <DxColumn alignment="center" caption="Histori P2TL" css-class="custom-table-column">
        <DxColumn
          :width="150"
          alignment="center"
          data-field="history_p2lt"
          data-type="number"
          caption="h"
          css-class="custom-table-column"
          cell-template="formatNumberHistory"
        />
      </DxColumn>

      <template #formatText="{ data }">
        <p class="text-left cursor-pointer">
          {{ data.text }}
        </p>
      </template>

      <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 #formatNumberWoPLMMobile="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setRequirementData({
              woType: 2,
              rekomendasiSistem: 0,
              dlpd: 0,
              historyP2tl: 0
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatNumberWoCC="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setRequirementData({
              woType: 1,
              rekomendasiSistem: 0,
              dlpd: 0,
              historyP2tl: 0
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatNumberWoComcen="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setRequirementData({
              woType: 3,
              rekomendasiSistem: 0,
              dlpd: 0,
              historyP2tl: 0
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatNumberWoTotal="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setRequirementData({
              woType: 0,
              rekomendasiSistem: 0,
              dlpd: 0,
              historyP2tl: 0
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatNumberRekomendasi1="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setRequirementData({
              woType: 0,
              rekomendasiSistem: 1,
              dlpd: 0,
              historyP2tl: 0
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatNumberRekomendasi2="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setRequirementData({
              woType: 0,
              rekomendasiSistem: 2,
              dlpd: 0,
              historyP2tl: 0
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatNumberDlpd="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setRequirementData({
              woType: 0,
              rekomendasiSistem: 0,
              dlpd: 1,
              historyP2tl: 0
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <template #formatNumberHistory="{ data }">
        <p
          class="text-right cursor-pointer"
          @click="
            setRequirementData({
              woType: 0,
              rekomendasiSistem: 0,
              dlpd: 0,
              historyP2tl: 1
            })
          "
        >
          {{
            isNumber(data.text)
              ? data.column.caption == '%'
                ? formatPercentage(data.text)
                : formatNumber(data.text)
              : data.text
          }}
        </p>
      </template>

      <DxSummary :calculate-custom-summary="calculateCustomSummary">
        <DxGroupItem
          column="wo_cc123"
          name="wo_cc123"
          summaryType="custom"
          :customize-text="(e: any) => formatNumber(e.value)"
          :show-in-group-footer="false"
          :align-by-column="true"
          css-class="!text-right cursor-pointer"
        />
        <DxGroupItem
          column="wo_pln_mobile"
          name="wo_pln_mobile"
          summaryType="custom"
          :customize-text="(e: any) => formatNumber(e.value)"
          :show-in-group-footer="false"
          :align-by-column="true"
          css-class="!text-right cursor-pointer"
        />
        <DxGroupItem
          column="wo_comcen"
          name="wo_comcen"
          summaryType="custom"
          :customize-text="(e: any) => formatNumber(e.value)"
          :show-in-group-footer="false"
          :align-by-column="true"
          css-class="!text-right cursor-pointer"
        />
        <DxGroupItem
          column="wo_total"
          name="wo_total"
          summary-type="custom"
          :customize-text="(e: any) => formatNumber(e.value)"
          :show-in-group-footer="false"
          :align-by-column="true"
          css-class="!text-right cursor-pointer"
        />
        <DxGroupItem
          column="rekomendasi_mendatangkan_petugas"
          summaryType="sum"
          :customize-text="(e: any) => formatNumber(e.value)"
          :show-in-group-footer="false"
          :align-by-column="true"
          css-class="!text-right cursor-pointer"
        />
        <DxGroupItem
          column="rekomendasi_diberikan_ke_pelanggan"
          summaryType="sum"
          :customize-text="(e: any) => formatNumber(e.value)"
          :show-in-group-footer="false"
          :align-by-column="true"
          css-class="!text-right cursor-pointer"
        />
        <DxGroupItem
          column="dpld"
          summaryType="sum"
          :customize-text="(e: any) => formatNumber(e.value)"
          :show-in-group-footer="false"
          :align-by-column="true"
          css-class="!text-right cursor-pointer"
        />
        <DxGroupItem
          column="history_p2lt"
          summaryType="sum"
          :customize-text="(e: any) => formatNumber(e.value)"
          :show-in-group-footer="false"
          :align-by-column="true"
          css-class="!text-right cursor-pointer"
        />
      </DxSummary>
    </DxDataGrid>
  </div>

  <DetailDialog
    :open="dialogDetail"
    title="Detail CTT & KWH Periksa"
    @on-close="closedialogDetail"
    :full-width="true"
  >
    <div class="w-full mb-4 lg:w-[70%] lg:float-left">
      <div class="p-4 bg-white rounded-xl lg:mr-4">
        <DxDataGrid
          :allow-column-reordering="true"
          class="max-h-[calc(100vh-140px)]"
          :data-source="dataSub"
          :show-column-lines="true"
          :show-row-lines="false"
          :show-borders="true"
          :row-alternation-enabled="true"
          :hover-state-enabled="true"
          @selection-changed="onDataSubSelectionChanged"
          :column-width="100"
          @exporting="onExportingDetail"
          :allow-column-resizing="true"
          column-resizing-mode="widget"
        >
          <DxSelection mode="single" />
          <DxPaging :page-size="20" :enabled="true" />
          <DxPager
            :visible="true"
            :allowed-page-sizes="[20, 50, 100]"
            display-mode="full"
            :show-page-size-selector="true"
            :show-info="true"
            :show-navigation-buttons="true"
          />
          <!--  -->
          <DxSearchPanel :visible="true" :highlight-case-sensitive="true" />
          <DxExport
            :enabled="true"
            :formats="['pdf', 'xlsx', 'document']"
            :allow-export-selected-data="false"
          />

          <DxColumn
            css-class="custom-table-column"
            :width="50"
            alignment="center"
            :calculate-display-value="(item: any) => dataSub.findIndex((i: any) => i == item) + 1"
            data-type="number"
            caption="No"
            cell-template="formatNumber"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_uid"
            caption="UIW/D"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_up3"
            caption="UP3"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_ulp"
            caption="Rayon"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="id_pelanggan"
            caption="IDPEL"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nomormeter"
            caption="NOMETER"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="no_telp_pelapor"
            caption="No. Telpon"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="nama_pelapor"
            caption="Nama"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="alamat_pelapor"
            caption="Alamat"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="media"
            caption="Sumber Lapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="no_laporan"
            caption="No Laporan"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="r08"
            caption="08"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="r70"
            caption="70"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="r71"
            caption="71"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="r41"
            caption="41"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="r44"
            caption="44"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="r45"
            caption="45"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="r46"
            caption="46"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="r37"
            caption="37"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="r47"
            caption="47"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="jenis_dlpd"
            caption="Jenis DLPD"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="keterangan_dlpd"
            caption="Keterangan DLPD"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="blth_dlpd"
            caption="Bulan Tahun DLPD"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="no_agenda_p2tl"
            caption="No. Agenda P2TL"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="tgl_mohon_p2tl"
            caption="Tgl Mohon P2T"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="tgl_sah_p2tl"
            caption="Tgl Sah P2TL"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="rekomendasi_sistem"
            caption="Rekomendasi Sistem"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="waktu_lapor"
            caption="Tgl/Jam Lapor"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="petugas_regu"
            caption="Petugas Regu"
            css-class="custom-table-column"
            cell-template="formatText"
          />
          <DxColumn
            :width="150"
            alignment="center"
            data-field="user_vcc"
            caption="User VCC"
            css-class="custom-table-column"
            cell-template="formatText"
          />

          <template #formatText="{ data }">
            <p class="text-left cursor-pointer">
              {{ data.text }}
            </p>
          </template>

          <template #formatNumber="{ data }">
            <p class="text-right cursor-pointer">
              {{ data.text }}
            </p>
          </template>

          <template #formatTime="{ data }">
            <p>
              {{ parseInt(data.text) ? formatWaktu(data.text) : '-' }}
            </p>
          </template>
        </DxDataGrid>
      </div>
    </div>
    <div class="w-full mb-4 lg:w-[30%] lg:float-right">
      <div class="p-4 space-y-2 bg-white rounded-xl">
        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">UIW/D:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.nama_uid" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">UP3:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.nama_up3" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Rayon:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.nama_ulp" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">IDPEL:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.id_pelanggan" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">NOMETER:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.nomormeter" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">No. Telpon:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.no_telp_pelapor"
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Nama:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.nama_pelapor" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Alamat:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.alamat_pelapor"
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Sumber Lapor:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.media" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">No Laporan:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.no_laporan" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">08:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.r08" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">70:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.r70" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">71:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.r71" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">41:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.r41" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">44:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.r44" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">45:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.r45" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">46:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.r46" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">37:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.r37" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">47:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.r47" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Jenis DLPD:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.jenis_dlpd" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Keterangan DLPD:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.keterangan_dlpd"
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Bulan Tahun DLPD:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.blth_dlpd" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">No. Agenda P2TL:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.no_agenda_p2tl"
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Tgl Mohon P2T:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.tgl_mohon_p2tl"
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Tgl Sah P2TL:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.tgl_sah_p2tl" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Rekomendasi Sistem:</h3>
          <InputText
            :readonly="true"
            :value="dataSubSelected?.rekomendasi_sistem"
            class-name="flex-1"
          />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Tgl/Jam Lapor:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.waktu_lapor" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">Petugas Regu:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.petugas_regu" class-name="flex-1" />
        </div>

        <div class="flex flex-row items-center justify-between w-full">
          <h3 class="text-sm font-medium w-[135px] text-gray-800">User VCC:</h3>
          <InputText :readonly="true" :value="dataSubSelected?.user_vcc" class-name="flex-1" />
        </div>
      </div>
    </div>
  </DetailDialog>

  <BufferDialog v-if="loadingData || loadingSubData" />
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxColumnFixing,
  DxExport,
  DxGroupItem,
  DxGrouping,
  DxPager,
  DxPaging,
  DxScrolling,
  DxSearchPanel,
  DxSelection,
  DxSummary
} from 'devextreme-vue/data-grid'
import { Type3 } from '@/components/Form/FiltersType'
import Filters from '@/components/Form/Filters.vue'
import { apolloClient, queries, requestGraphQl } from '@/utils/api/api.graphql'
import { provideApolloClient } from '@vue/apollo-composable'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'
import BufferDialog from '@/components/Dialogs/BufferDialog.vue'
import DetailDialog from '@/components/Dialogs/DetailDialog.vue'
import { formatWaktu } from '@/components/Form/FiltersType/reference'
import InputText from '@/components/InputText.vue'
import {
  exportToPDF,
  exportToXLSX,
  exportDetailToPDF,
  exportDetailToXLSX,
  exportToDOCX,
  exportDetailToDOCX
} from '@/report/Ctt/CTT_LaporanCttKwhPeriksa'
import { getDataRowGroup } from '@/utils/helper'

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 isDialogEnabled = ref(false)
const requirementData = ref<any>({
  woType: 0,
  rekomendasiSistem: 0,
  dlpd: 0,
  historyP2tl: 0
})
const reportMeta = ref({
  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' },
  periode: ''
})
const groupDialog = ref(false)
const groupData = ref<any>(null)
const groupIndex = ref(0)

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

const setRequirementData = (data: any) => (requirementData.value = data)

const onCellClicked = (e: any) => {
  if (e.rowType == 'group' || e.rowType == 'data') {
    if (e.rowType == 'group') {
      groupDialog.value = true
      groupIndex.value = e.row.groupIndex
    }
    isDialogEnabled.value = true

    if (e.column.dataField == 'wo_cc123') {
      setRequirementData({
        woType: 1,
        rekomendasiSistem: 0,
        dlpd: 0,
        historyP2tl: 0
      })
    } else if (e.column.dataField == 'wo_pln_mobile') {
      setRequirementData({
        woType: 2,
        rekomendasiSistem: 0,
        dlpd: 0,
        historyP2tl: 0
      })
    } else if (e.column.dataField == 'wo_comcen') {
      setRequirementData({
        woType: 3,
        rekomendasiSistem: 0,
        dlpd: 0,
        historyP2tl: 0
      })
    } else if (e.column.dataField == 'wo_total') {
      setRequirementData({
        woType: 0,
        rekomendasiSistem: 0,
        dlpd: 0,
        historyP2tl: 0
      })
    } else if (e.column.dataField == 'rekomendasi_mendatangkan_petugas') {
      setRequirementData({
        woType: 0,
        rekomendasiSistem: 1,
        dlpd: 0,
        historyP2tl: 0
      })
    } else if (e.column.dataField == 'rekomendasi_diberikan_ke_pelanggan') {
      setRequirementData({
        woType: 0,
        rekomendasiSistem: 2,
        dlpd: 0,
        historyP2tl: 0
      })
    } else if (e.column.dataField == 'dpld') {
      setRequirementData({
        woType: 0,
        rekomendasiSistem: 0,
        dlpd: 1,
        historyP2tl: 0
      })
    } else if (e.column.dataField == 'history_p2lt') {
      setRequirementData({
        woType: 0,
        rekomendasiSistem: 0,
        dlpd: 0,
        historyP2tl: 1
      })
    } else {
      isDialogEnabled.value = false
    }

    if (e.rowType == 'group') {
      groupData.value = getDataRowGroup(e.data)
      showDetail()
    }
  } else {
    groupDialog.value = false
  }
}

let cc123 = 0
let plnMobile = 0
let comcen = 0
const calculateCustomSummary = (options: any) => {
  if (options.name === 'wo_cc123') {
    if (options.summaryProcess === 'calculate') {
      cc123 += options.value
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = cc123
    }
  }

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

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

  if (options.name === 'wo_total') {
    if (options.summaryProcess === 'start') {
      plnMobile = 0
      cc123 = 0
      comcen = 0
    } else if (options.summaryProcess === 'calculate') {
    } else if (options.summaryProcess === 'finalize') {
      options.totalValue = plnMobile + cc123 + comcen
    }
  }
}

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 onExportingDetail = (e: any) => {
  if (e.format === 'pdf') {
    exportDetailToPDF(reportMeta.value, dataSub.value)
  } else if (e.format === 'xlsx') {
    exportDetailToXLSX(reportMeta.value, e)
  } else {
    exportDetailToDOCX(reportMeta.value, dataSub.value)
  }
}

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

const filterData = async (params: any) => {
  resetData()
  const { posko, uid, up3, ulp } = params
  const dateValue = params.periode.split(' s/d ')

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

  if (uid?.id != 0) {
    groupList.forEach((item, index) => {
      if (item.caption == 'Semua Unit') {
        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 = {
    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),
    posko: posko ? posko.id : '',
    idUid: uid ? uid.id : 0,
    idUp3: up3 ? up3.id : 0,
    idUlp: ulp ? ulp.id : 0,
    namaRegional: ''
  }

  loadingData.value = true
  await requestGraphQl(queries.cttKwhPeriksa.laporanCttKwhPeriksa, query)
    .then((result) => {
      if (result.data.data != undefined) {
        data.value = result.data.data.laporanCttKwhPeriksa
      } else {
        data.value = []
      }

      reportMeta.value = filters.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

  var 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: 0,
    idUid: 0,
    idUp3: 0,
    namaRegional: '',
    tipeWo: requirementData.value?.woType ? requirementData.value?.woType : 0,
    rekomendasiSistem: requirementData.value?.rekomendasiSistem
      ? requirementData.value?.rekomendasiSistem == 1
        ? 'Mendatangkan Petugas'
        : 'Diberikan ke Pelanggan'
      : '',
    isDlpd: requirementData.value?.dlpd ? requirementData.value?.dlpd : 0,
    isHistoriP2tl: requirementData.value?.historyP2tl ? requirementData.value?.historyP2tl : 0
  }

  if (groupDialog.value) {
    if (grouping.value[groupIndex.value].data == 'nama_uid') {
      query = {
        ...query,
        idUid: groupData.value?.id_uid ? groupData.value?.id_uid : 0,
        namaRegional: groupData.value?.nama_regional ? groupData.value?.nama_regional : ''
      }
    } else if (grouping.value[groupIndex.value].data == 'nama_up3') {
      query = {
        ...query,
        idUid: groupData.value?.id_uid ? groupData.value?.id_uid : 0,
        idUp3: groupData.value?.id_up3 ? groupData.value?.id_up3 : 0,
        namaRegional: groupData.value?.nama_regional ? groupData.value?.nama_regional : ''
      }
    }
  } else {
    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,
      namaRegional: selected?.nama_regional ? selected?.nama_regional : '',
      tipeWo: requirementData.value?.woType ? requirementData.value?.woType : 0,
      rekomendasiSistem: requirementData.value?.rekomendasiSistem
        ? requirementData.value?.rekomendasiSistem == 1
          ? 'Mendatangkan Petugas'
          : 'Diberikan ke Pelanggan'
        : '',
      isDlpd: requirementData.value?.dlpd ? requirementData.value?.dlpd : 0,
      isHistoriP2tl: requirementData.value?.historyP2tl ? requirementData.value?.historyP2tl : 0
    }
  }

  loadingSubData.value = true
  await requestGraphQl(queries.cttKwhPeriksa.laporanCttKwhPeriksaDetail, query)
    .then((result) => {
      if (result.data.data != undefined) {
        dataSub.value = result.data.data.detailLaporanCttKwhPeriksa
      } 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()
  dataSub.value = []
  dataSubSelected.value = null
  if (isDialogEnabled.value) {
    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,
        id_uid: 120,
        nama_uid: 'WILAYAH SUMATERA UTARA',
        id_up3: 12100,
        nama_up3: 'UP3 PEMATANG SIANTAR',
        id_ulp: 12102,
        nama_ulp: 'ULP LIMA PULUH',
        wo_cc123: 14390,
        wo_pln_mobile: 28344,
        wo_comcen: 28344,
        wo_total: 42734,
        rekomendasi_mendatangkan_petugas: 21,
        rekomendasi_diberikan_ke_pelanggan: 13,
        dpld: 43,
        history_p2lt: 5
      },
      {
        id: 1,
        id_uid: 41,
        nama_uid: 'WILAYAH MALUKU DAN MALUKU UTARA',
        id_up3: 412,
        nama_up3: 'UP3 TERNATE',
        id_ulp: 41230,
        nama_ulp: 'ULP BACAN',
        wo_cc123: 14390,
        wo_pln_mobile: 28344,
        wo_comcen: 28344,
        wo_total: 42734,
        rekomendasi_mendatangkan_petugas: 21,
        rekomendasi_diberikan_ke_pelanggan: 13,
        dpld: 43,
        history_p2lt: 5
      },
      {
        id: 2,
        id_uid: 101,
        nama_uid: 'DISTRIBUSI JAWA TENGAH & DIY',
        id_up3: 52150,
        nama_up3: 'UP3 MAGELANG',
        id_ulp: 52156,
        nama_ulp: 'ULP PARAKAN',
        wo_cc123: 14390,
        wo_pln_mobile: 28344,
        wo_comcen: 28344,
        wo_total: 42734,
        rekomendasi_mendatangkan_petugas: 21,
        rekomendasi_diberikan_ke_pelanggan: 13,
        dpld: 43,
        history_p2lt: 5
      },
      {
        id: 3,
        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',
        wo_cc123: 14390,
        wo_pln_mobile: 28344,
        wo_comcen: 28344,
        wo_total: 42734,
        rekomendasi_mendatangkan_petugas: 21,
        rekomendasi_diberikan_ke_pelanggan: 13,
        dpld: 43,
        history_p2lt: 5
      }
    ]
  }
})
</script>
