<template>
  <Filters @reset-form="data = []" @run-search="() => filterData(filters)" class="mb-4">
    <Type14 @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"
      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="onSelectionChanged"
      :column-width="100"
      @exporting="onExporting"
      :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) => data.findIndex((i) => i == item) + 1"
        data-type="number"
        caption="No"
        cell-template="formatNumber"
      />

      <DxColumn
        css-class="custom-table-column"
        :width="170"
        alignment="center"
        data-field="kode"
        caption="Kode Material"
        cell-template="formatText"
      />
      <DxColumn
        css-class="custom-table-column"
        :width="170"
        alignment="center"
        data-field="nama_material"
        caption="Nama Material"
        cell-template="formatText"
      />
      <DxColumn
        css-class="custom-table-column"
        :width="120"
        alignment="center"
        data-field="satuan"
        caption="Satuan"
        cell-template="formatText"
      />
      <DxColumn
        css-class="custom-table-column"
        :width="170"
        alignment="center"
        data-field="sumber_material"
        caption="Sumber Material"
        cell-template="formatText"
      />
      <DxColumn css-class="custom-table-column" alignment="center" caption="Tanggal">
        <DxColumn
          v-for="i in 31"
          :width="150"
          alignment="center"
          :data-field="`tgl${i}`"
          data-type="number"
          :caption="i"
          css-class="custom-table-column"
          cell-template="formatNumber"
        />
      </DxColumn>
      <DxColumn
        css-class="custom-table-column"
        :width="170"
        alignment="center"
        data-field="total"
        caption="Jumlah"
        cell-template="formatNumber"
      />

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

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

  <DetailDialog
    :open="dialogDetail"
    title="Detail Rekapitulasi Pemakaian Material"
    @on-close="closeDialog"
  >
    <div class="w-full 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-[170px] text-gray-800">Kode Material:</h3>
        <InputText :readonly="true" :value="dataSelected?.kode" class-name="flex-1" />
      </div>

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

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

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

      <div class="flex flex-row items-center justify-between w-full" v-for="i in 31">
        <h3 class="text-sm font-medium w-[170px] text-gray-800">Tgl {{ i }}:</h3>
        <InputText :readonly="true" :value="dataSelected[`tgl${i}`]" class-name="flex-1" />
      </div>

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

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

<script setup lang="ts">
import { ref } from 'vue'
import { DxDataGrid } from 'devextreme-vue'
import {
  DxColumn,
  DxExport,
  DxLoadPanel,
  DxPager,
  DxPaging,
  DxSearchPanel,
  DxSelection
} from 'devextreme-vue/data-grid'
import { Type14 } from '@/components/Form/FiltersType'
import Filters from '@/components/Form/Filters.vue'
import { useQuery } from '@vue/apollo-composable'
import gql from 'graphql-tag'
import { queries, requestGraphQl } from '@/utils/api/api.graphql'
import BufferDialog from '@/components/Dialogs/BufferDialog.vue'
import { formatNumber, formatPercentage, isNumber } from '@/utils/numbers'
import DetailDialog from '@/components/Dialogs/DetailDialog.vue'
import InputText from '@/components/InputText.vue'
import {
  exportToPDF,
  exportToXLSX,
  exportToDOCX
} from '@/report/Material/Rekapitulasi/Material_RPM'

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 loadingData = ref(false)
const reportMeta = ref({
  uid: {
    id: 0,
    name: 'Semua Distribusi/Wilayah'
  },
  up3: {
    id: 0,
    name: 'Semua Area'
  },
  posko: {
    id: 0,
    name: 'Semua Unit Layanan Pelanggan'
  },
  periode: ''
})

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

const filterData = async (params: any) => {
  resetData()
  const dateValue = params.periode.split(' s/d ')
  const { posko, uid, up3 } = params
  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),
    idUid: uid ? uid.id : 0,
    idUp3: up3 ? up3.id : 0,
    posko: posko ? posko.id : 0
  }

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

      reportMeta.value = filters.value
    })
    .catch((err) => {
      console.error(err)
    })
    .finally(() => {
      loadingData.value = false
    })
}

const dataGridRef = ref<DxDataGrid | null>(null)
const clearSelection = () => {
  const dataGrid = dataGridRef.value!.instance!
  dataGrid.clearSelection()
}
const showDetail = () => {
  clearSelection()
  dataSub.value = []
  dataSubSelected.value = null
  dialogDetail.value = true
}
const closeDialog = () => {
  dialogDetail.value = false
}

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

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

const filters = ref()
</script>
