<template>
  <section class="section-list">
    <div class="section-header">
      <i :class="'ico-c ico-section back-grad-' + iconBack">
        <svg height="20"><use :href="icourl + '#' + icon"></use></svg>
      </i>
      <h1>
        <span v-if="title !== undefined">{{ title }}</span>
        <span class="section-header-count">{{ totalData }} {{ listText }}</span>
      </h1>
      <div class="section-header-buttons-c">
        <icon-button
          @click="goToListWithFilter"
          icon="list"
          iconClass="ico-section ico-section-header-btn" />
      </div>
    </div>
    <div class="section-content">
      <div class="dashboard-list-C">
        <template v-for="row in tableData">
          <template v-if="lineRoute !== undefined">
            <router-link :to="lineRoute + row[lineRouteKey!]" class="dashboard-list-item">
              <div>
                <span>{{ row.baslik }}</span>
                <br />
                <span class="list-second-line" v-if="row[dateKey] !== null">
                  {{
                    dateStore.dateFormat({
                      date: row[dateKey],
                      pattern: 'yy-mm-dd-t'
                    })
                  }}
                </span>
              </div>
              <div>{{ DateCalculate(row[dateKey]) }}</div>
            </router-link>
          </template>
          <template v-else>
            <div class="dashboard-list-item clickable" @click="OnClick($event, row)">
              <div>
                <span>{{ row.baslik }}</span>
                <br />
                <span class="list-second-line" v-if="row[dateKey] !== null">
                  {{
                    dateStore.dateFormat({
                      date: row[dateKey],
                      pattern: 'yy-mm-dd-t'
                    })
                  }}
                </span>
              </div>
              <div>{{ DateCalculate(row[dateKey]) }}</div>
            </div>
          </template>
        </template>
      </div>
    </div>
  </section>
</template>
<script setup lang="ts">
  import { ref } from 'vue'
  import { useDateStore } from '@/stores/dateStore'
  import { useRouter } from 'vue-router'
  import icourl from '@/assets/images/icons.svg'

  const dateStore = useDateStore()
  const router = useRouter()

  const props = defineProps<{
    tableData: Record<string, any>[]
    lineFunction?: Function
    title?: string
    listText?: string
    icon?: string
    apiList?: string
    lineRoute?: string
    lineRouteKey?: string
    dateKey: string
    iconBack: string
    total: number
    filterParams?: Record<string, any>
  }>()
  const totalData = ref<number>(props.total)

  const emit = defineEmits(['click'])

  const DateCalculate = (date: string): string => {
    const today: Date = new Date()
    const dataDate: Date = new Date(date)
    const diffTime: number = Math.abs(today.getTime() - dataDate.getTime())
    const diffDays: number = Math.floor(diffTime / (1000 * 60 * 60 * 24))
    return String(diffDays) + ' Gün'
  }

  const OnClick = (e: Event, row: object) => {
    emit('click', row)
  }

  const goToListWithFilter = () => {
    try {
      const query: Record<string, any> = {}
      
      // Filtre parametrelerini query'ye ekle (Filters[...] formatına dönüştür)
      if (props.filterParams && typeof props.filterParams === 'object') {
        Object.keys(props.filterParams).forEach((key) => {
          const value = props.filterParams![key]
          if (value !== undefined && value !== null && value !== '') {
            // Değer zaten operatör içeriyorsa olduğu gibi kullan, yoksa '=' ekle
            let filterValue = String(value)
            // Eğer değer zaten operatör içermiyorsa '=' ekle
            if (!filterValue.match(/^[<>=]/)) {
              filterValue = '=' + filterValue
            }
            // Query parametresine string olarak ekle (Vue Router array'leri yanlış serialize ediyor)
            query[`Filters[${key}]`] = filterValue
          }
        })
      }
      
      router.push({
        path: '/piyangolar/piyango-listesi',
        query: query
      })
    } catch (error) {
      console.error('goToListWithFilter hatası:', error)
      // Hata durumunda filtre olmadan yönlendir
      router.push({
        path: '/piyangolar/piyango-listesi'
      })
    }
  }
</script>
