<template>
  <q-page v-if="canReadOrder" class="pch-page">
    <div class="sticky-stack pch-sticky-stack">
      <div class="ol-filter-bar filter-bar pch-filter-bar">
        <div class="row items-center q-col-gutter-md">
          <div class="col-12 col-md-4">
            <q-input
              :model-value="productCode || '-'"
              label="Urun Kodu"
              dense
              filled
              readonly
            />
          </div>
          <div class="col-12 col-md-8">
            <q-input
              :model-value="rows.length"
              label="Toplam Maliyet Kaydi"
              dense
              filled
              readonly
            />
          </div>
        </div>
      </div>

      <div class="save-toolbar pch-save-toolbar">
        <div class="text-subtitle2 text-weight-bold">Secili Urunun Tum Maliyetleri</div>
        <div class="row items-center q-gutter-sm">
          <q-btn
            icon="arrow_back"
            label="Geri"
            flat
            color="grey-8"
            @click="goBack"
          />
          <q-btn
            label="Yenile"
            icon="refresh"
            color="primary"
            :loading="loading"
            @click="fetchRows"
          />
        </div>
      </div>
    </div>

    <q-table
      title=""
      class="ol-table pch-table"
      flat
      bordered
      dense
      separator="cell"
      row-key="__rowKey"
      :rows="rows"
      :columns="columns"
      :loading="loading"
      no-data-label="Kayit bulunamadi"
      :rows-per-page-options="[0]"
      hide-bottom
    >
      <template #body-cell="props">
        <q-td v-if="props.col.name === 'open'" :props="props" class="text-center">
          <q-btn
            icon="open_in_new"
            color="primary"
            flat
            round
            dense
            @click="openRow(props.row)"
          >
            <q-tooltip>Ac</q-tooltip>
          </q-btn>
        </q-td>
        <q-td v-else :props="props" class="pch-wrap-col">
          <div class="pch-wrap-2" :title="String(props.value ?? '')">{{ props.value }}</div>
        </q-td>
      </template>
    </q-table>

    <q-banner v-if="error" class="bg-red text-white q-mt-sm">
      Hata: {{ error }}
    </q-banner>
  </q-page>

  <q-page v-else class="q-pa-md flex flex-center">
    <div class="text-negative text-subtitle1">
      Bu module erisim yetkiniz yok.
    </div>
  </q-page>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { usePermission } from 'src/composables/usePermission'
import { get, extractApiErrorDetail } from 'src/services/api'

const route = useRoute()
const router = useRouter()
const { canRead } = usePermission()
const canReadOrder = canRead('order')

const loading = ref(false)
const error = ref('')
const allRows = ref([])

const productCode = computed(() => String(route.query?.urun_kodu || '').trim())

const columns = [
  { name: 'open', label: '', field: 'open', align: 'center', sortable: false, style: 'width:3%', headerStyle: 'width:3%' },
  { name: 'nOnMLNo', label: 'nOnMLNo', field: 'nOnMLNo', align: 'left', sortable: true, style: 'width:7%', headerStyle: 'width:7%' },
  { name: 'UrunKodu', label: 'UrunKodu', field: 'UrunKodu', align: 'left', sortable: true, style: 'width:8%', headerStyle: 'width:8%' },
  { name: 'UrunAdi', label: 'UrunAdi', field: 'UrunAdi', align: 'left', sortable: true, style: 'width:12%', headerStyle: 'width:12%' },
  { name: 'Tarihi', label: 'Tarihi', field: 'Tarihi', align: 'center', sortable: true, format: val => formatDateTR(val), style: 'width:8%', headerStyle: 'width:8%' },
  { name: 'sKullaniciAdi', label: 'sKullaniciAdi', field: 'sKullaniciAdi', align: 'left', sortable: true, style: 'width:8%', headerStyle: 'width:8%' },
  { name: 'lTutarUSD', label: 'lTutarUSD', field: 'lTutarUSD', align: 'right', sortable: true, format: val => formatMoney(val), style: 'width:7%', headerStyle: 'width:7%' },
  { name: 'lTutarTL', label: 'lTutarTL', field: 'lTutarTL', align: 'right', sortable: true, format: val => formatMoney(val), style: 'width:7%', headerStyle: 'width:7%' },
  { name: 'lTutarEURO', label: 'lTutarEURO', field: 'lTutarEURO', align: 'right', sortable: true, format: val => formatMoney(val), style: 'width:7%', headerStyle: 'width:7%' },
  { name: 'sDovizCinsi', label: 'sDovizCinsi', field: 'sDovizCinsi', align: 'left', sortable: true, style: 'width:7%', headerStyle: 'width:7%' },
  { name: 'lTutarDoviz', label: 'lTutarDoviz', field: 'lTutarDoviz', align: 'right', sortable: true, format: val => formatMoney(val), style: 'width:7%', headerStyle: 'width:7%' },
  { name: 'dteGuncellemeTarihi', label: 'dteGuncellemeTarihi', field: 'dteGuncellemeTarihi', align: 'center', sortable: true, format: val => formatDateTR(val), style: 'width:9%', headerStyle: 'width:9%' },
  { name: 'sGuncellemeKullaniciAdi', label: 'sGuncellemeKullaniciAdi', field: 'sGuncellemeKullaniciAdi', align: 'left', sortable: true, style: 'width:9%', headerStyle: 'width:9%' },
  { name: 'nUrtReceteID', label: 'nUrtReceteID', field: 'nUrtReceteID', align: 'left', sortable: true, style: 'width:7%', headerStyle: 'width:7%' },
  { name: 'sAciklama', label: 'sAciklama', field: 'sAciklama', align: 'left', sortable: true, style: 'width:10%', headerStyle: 'width:10%' }
]

const rows = computed(() => allRows.value)

function formatDateTR (value) {
  const s = String(value || '').trim()
  if (!s) return ''
  const m = /^(\d{4})-(\d{2})-(\d{2})(?:\s+(\d{2}):(\d{2}))?/.exec(s)
  if (!m) return s
  const datePart = `${m[3]}.${m[2]}.${m[1]}`
  if (m[4] && m[5]) return `${datePart} ${m[4]}:${m[5]}`
  return datePart
}

function formatMoney (value) {
  return Number(value || 0).toLocaleString('tr-TR', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 4
  })
}

async function fetchRows () {
  const urunKodu = productCode.value
  if (!urunKodu) {
    error.value = 'Urun kodu bulunamadi'
    allRows.value = []
    return
  }

  loading.value = true
  error.value = ''
  try {
    const data = await get('/pricing/production-product-costing/has-cost-history', {
      urun_kodu: urunKodu
    })

    const list = Array.isArray(data) ? data : []
    allRows.value = list.map((x, i) => ({
      __rowKey: `${x?.nOnMLNo || ''}-${x?.UrunKodu || ''}-${i}`,
      ...x
    }))
  } catch (err) {
    error.value = await extractApiErrorDetail(err)
    allRows.value = []
  } finally {
    loading.value = false
  }
}

function goBack () {
  router.push({ name: 'production-product-costing-has-cost' })
}

function openRow (row) {
  const onMLNo = String(row?.nOnMLNo || '').trim()
  if (!onMLNo) return

  router.push({
    name: 'production-product-costing-has-cost-detail',
    query: {
      n_onml_no: onMLNo,
      urun_kodu: productCode.value || String(row?.UrunKodu || '').trim()
    }
  })
}

watch(
  () => productCode.value,
  () => {
    fetchRows()
  }
)

onMounted(() => {
  if (!canReadOrder.value) return
  fetchRows()
})
</script>

<style scoped>
.pch-page {
  padding: 10px;
}

.pch-sticky-stack {
  margin-bottom: 8px;
}

.pch-filter-bar {
  min-height: auto !important;
  padding-top: 8px !important;
  padding-bottom: 8px !important;
}

.pch-save-toolbar {
  border-top: 0;
}

.pch-table :deep(.q-table thead th) {
  font-size: 11px;
  padding: 3px 4px;
  white-space: normal !important;
  vertical-align: top !important;
  line-height: 1.15;
}

.pch-table :deep(.q-table tbody td) {
  font-size: 11px;
  padding: 2px 4px;
  white-space: normal !important;
  vertical-align: top !important;
  line-height: 1.15;
}

.pch-table :deep(.q-table) {
  width: 100%;
  table-layout: fixed;
}

.pch-wrap-col {
  white-space: normal !important;
}

.pch-wrap-2 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  line-height: 1.15;
  white-space: normal;
  word-break: break-word;
}
</style>
