<template>
  <section class="section-list">
    <list-table-content
      :tableHeader="tableHeader"
      icon="draws"
      title="Katılım Listesi"
      listText="Katılımcı"
      :rowAction="OpenUser"
      :apiList="'Katilimci/ByCekilisId/' + piyangoStore.selectedLottery"
      v-model:pagination="paginationData"
      v-model:refresh="piyangoKatilimciStore.refreshPiyangoKatilimciList"
      isUseRoute>
      <template #extraButtons>
        <button
          class="button-c"
          @click="piyangoKatilimciService.CreateOnlineDraw"
          v-if="
            paginationData.totalRecords > 0 &&
            usersStore.isPanelUser &&
            !piyangoStore.lotteryDrawState &&
            piyangoStore.lotteryApprove === 4 &&
            piyangoStore.lotteryData.cekilisYontemiId === 2
          ">
          Online Çekiliş Düzenle
        </button>
        <a href="/data/ornek-katilimci-listesi.xlsx" target="_blank" class="button-c">
          Örnek Katılımcı Dosyası İndir
        </a>
        <button
          class="button-c"
          @click="AddNewDocument"
          v-if="!usersStore.isPanelUser && !piyangoStore.lotteryDrawState">
          Katılımcı Dosyası Yükle
        </button>
        <button
          class="button-c button-alert"
          @click="DeleteAllButton"
          v-if="
            paginationData.totalRecords > 0 &&
            usersStore.isPanelUser &&
            !piyangoStore.lotteryDrawState &&
            (piyangoStore.lotteryApprove === 7 || piyangoStore.lotteryApprove === 14)
          ">
          Tüm katılımcıları Sil
        </button>
        <button
          @click="SendChangeRequest"
          v-if="piyangoStore.lotteryApprove === 4 && !usersStore.isPanelUser">
          Katılım Listesi Değişiklik Talebi Gönder
        </button>
      </template>
    </list-table-content>
    <panel-wrapper
      wide
      v-if="piyangoKatilimciStore.katilimciFilePanel"
      v-model="piyangoKatilimciStore.katilimciFilePanel"
      panel-title="Katılımcı Dosyası Yükle">
      <template #panelContent>
        <div class="upload-panel-content">
          <div v-if="uploadProgressPanel" class="upload-progress-section">
            <h4 class="upload-progress-title">Aktif Yükleme</h4>
            <div class="upload-warning">
              İşlem sırasında tarayıcıyı veya bu sekmeyi kapatmayınız. Sayfa yenilerseniz bu paneli tekrar açarak takip edebilirsiniz.
            </div>
            <div class="progress-bar">
              <div
                class="progress-fill"
                :style="{ width: uploadProgressValue + '%' }"></div>
            </div>
            <div class="progress-text">
              <template v-if="uploadProgressValue === 0">
                Dosya içeriği okunuyor, yükleme başlatılıyor...
              </template>
              <template v-else>{{ uploadProgressValue }}%</template>
            </div>
          </div>
          <div v-if="uploadJobsLoading || uploadJobs.length > 0" class="upload-history-section">
            <h4 class="upload-history-title">Yükleme Geçmişi</h4>
            <div v-if="uploadJobsLoading" class="history-loading">Yükleniyor...</div>
            <div v-else-if="uploadJobs.length > 0" class="history-items">
              <div
                v-for="job in uploadJobs"
                :key="job.guid"
                :class="['history-item', job.status?.toLowerCase() === 'processing' ? 'processing' : '']"
                @click="OpenUploadDetail(job.guid)">
                <span class="history-file">{{ job.fileName }}</span>
                <span :class="['history-status', 'status-' + job.status?.toLowerCase()]">{{ statusText(job.status) }}</span>
                <span class="history-progress">{{ job.progress }}%</span>
                <span v-if="job.status?.toLowerCase() === 'completed'" class="history-stats">
                  +{{ job.insertedCount ?? 0 }}
                  <template v-if="(job.duplicateCount ?? 0) > 0"> / {{ job.duplicateCount }} dpl</template>
                </span>
                <span class="history-date">{{ formatDate(job.createdAt) }}</span>
              </div>
            </div>
          </div>
          <div class="upload-form-section">
            <h4 class="upload-form-title">Yeni Dosya Yükle</h4>
            <panel-katilimci-document />
          </div>
        </div>
      </template>
      <template #footerButton>
        <button
          class="button-c button-save"
          @click="FileUpload"
          :disabled="uploadProgressPanel">
          Yükle
        </button>
      </template>
    </panel-wrapper>
    <panel-wrapper
      wide
      v-if="piyangoKatilimciStore.katilimciUserPanel"
      v-model="piyangoKatilimciStore.katilimciUserPanel"
      :panel-title="
        piyangoKatilimciStore.isPiyangoKatilimciUserUpdate
          ? 'Katılımcı Düzenle'
          : 'Katılımcı Ekle'
      ">
      <template #panelContent>
        <panel-piyango-katilimci />
      </template>
      <template #footerButton v-if="!usersStore.isPanelUser">
        <button
          :disabled="!piyangoKatilimciValidationStore.userFormChanged"
          class="button-c button-save"
          @click="piyangoKatilimciService.SaveKatilimciUser">
          {{ piyangoKatilimciStore.isPiyangoKatilimciUserUpdate ? 'Kaydet' : 'Ekle' }}
        </button>
      </template>
    </panel-wrapper>
    <panel-wrapper
      wide
      v-if="uploadDetailPanel"
      v-model="uploadDetailPanel"
      panel-title="Yükleme Detayı">
      <template #panelContent>
        <panel-excel-upload-detail :jobGuid="selectedJobGuid" />
      </template>
    </panel-wrapper>
  </section>
</template>
<script setup lang="ts">
  import { ref, computed } from 'vue'
  import PanelWrapper from '@/components/PanelWrapper.vue'
  import PanelKatilimciDocument from '@/module/cekilisler/components/panel/PanelKatilimciDocument.vue'
  import PanelPiyangoKatilimci from '@/module/cekilisler/components/panel/PanelPiyangoKatilimci.vue'
  import PanelExcelUploadDetail from '@/module/cekilisler/components/panel/PanelExcelUploadDetail.vue'
  import { useDateStore } from '@/stores/dateStore'

  import { useUsersStore } from '@/stores/usersStore'
  const usersStore = useUsersStore()
  import { useDataStore } from '@/stores/dataStore'
  const dataStore = useDataStore()
  import { usePiyangoStore } from '../stores/piyangoStore'

  const piyangoStore = usePiyangoStore()
  import { usePiyangoKatilimciStore } from '../stores/piyangoKatilimciStore'

  const piyangoKatilimciStore = usePiyangoKatilimciStore()
  import { usePiyangoKatilimciValidationStore } from '../validation/piyangoKatilimciValidationStore'

  const piyangoKatilimciValidationStore = usePiyangoKatilimciValidationStore()
  import { usePiyangoKatilimciService } from '../service/piyangoKatilimciService'

  const piyangoKatilimciService = usePiyangoKatilimciService()
  import { useDialogStore } from '@/components/global/dialogStore'

  const dialogStore = useDialogStore()
  const toastStore = useToastStore()

  import { usePiyangoOnayStore } from '../stores/piyangoOnayStore'
  const piyangoOnayStore = usePiyangoOnayStore()
  import { usePiyangoOnayService } from '../service/piyangoOnayService'
  const piyangoOnayService = usePiyangoOnayService()

  import { onUnmounted } from 'vue'
  import { connectToHub, onProgress, onInsertProgress, onCompleted, onError, removeUploadHandlers } from '../service/signalrService'
  import { useToastStore } from '@/components/global/toastStore'

  const uploadProgressValue = ref(0)
  const uploadProgressPanel = ref(false)
  const uploadDetailPanel = ref(false)
  const uploadJobs = ref<Record<string, any>[]>([])
  const uploadJobsLoading = ref(false)
  const selectedJobGuid = ref('')
  const connectionId = ref('')
  const dateStore = useDateStore()
  let pollInterval: ReturnType<typeof setInterval> | null = null

  const tableHeader = ref<Record<string, any>[]>([
    {
      name: 'cekilisKatilimSiraNo',
      title: 'Çekiliş Katılım Sıra No',
      sort: true,
      style: { width: '20%' }
    },
    {
      name: 'cekilisHakkiAdedi',
      title: 'Çekiliş Hakkı Adedi',
      style: { width: '10%' }
    },
    {
      name: 'sifreCode',
      title: 'Şifre (Code)',
      sort: true,
      style: { width: '20%' }
    },
    {
      name: 'magazaKartNumarasi',
      title: '(Mağaza Kartı)  (Müşteri Kartı) Numarası',
      sort: true,
      style: { width: '20%' }
    },
    {
      name: 'isimSoyisim',
      title: 'Ad Soyad',
      sort: true,
      style: { width: '20%' }
    },

    {
      name: 'telefonNumarasi',
      title: 'Telefon',
      sort: true
    },
    {
      name: 'ilce',
      title: 'İlçe',
      sort: true
    },
    {
      name: 'il',
      title: 'İl',
      sort: true
    },
    {
      name: 'email',
      title: 'Email',
      sort: true,
      style: { width: '15%' }
    },

    {
      name: 'katilimTarihi',
      title: 'Katılım Tarihi',
      sort: true,
      style: { width: '15%' }
    },
    {
      name: 'fisFaturaTarihi',
      title: 'Fiş/Fatura Tarihi',
      sort: true,
      style: { width: '15%' }
    },
    {
      name: 'fisFaturaNo',
      title: 'Fiş/Fatura No',
      sort: true,
      style: { width: '15%' }
    },
    {
      name: 'kampanyaliUrunTutari',
      title: 'Fiş/Fatura (Kampanyalı Ürün Tutarı)',
      sort: true,
      style: { width: '15%' }
    },
    {
      name: 'toplamTutar',
      title: 'Fiş/Fatura  Toplam Tutarı',
      sort: true,
      style: { width: '15%' }
    },

    {
      name: 'magazaAdiYeri',
      title: 'Mağaza Adı/Yeri',
      sort: true,
      style: { width: '15%' }
    }
  ])

  const paginationData = ref<Record<string, any>>({})

  const KatilimciAddAction = computed(() => {
    if (
      !usersStore.isPanelUser &&
      piyangoStore.lotteryApprove === 4 &&
      !piyangoStore.lotteryDrawState
    )
      return AddNewKatilimci
    else return ''
  })

  const AddNewDocument = async () => {
    try {
      connectionId.value = await connectToHub()
    } catch {
      connectionId.value = ''
    }
    dataStore.panelData = { title: '', file: '' }
    piyangoKatilimciStore.katilimciFilePanel = true
    uploadJobsLoading.value = true
    const cekilisId = piyangoStore.selectedLottery
    uploadJobs.value = cekilisId !== null ? await piyangoKatilimciService.GetUploadJobs(cekilisId) : []
    uploadJobsLoading.value = false

    removeUploadHandlers()
    // İşleniyor durumundaki job varsa SignalR ile abone ol (gerçek zamanlı progress almak için)
    const processingJob = uploadJobs.value.find(
      (j: Record<string, any>) => j.status?.toLowerCase() === 'processing'
    )
    if (processingJob?.guid && connectionId.value) {
      const updateProgress = (data: any) => {
        const percent = data.Percent ?? 0
        uploadProgressValue.value = percent
        const idx = uploadJobs.value.findIndex((j: Record<string, any>) => j.guid === processingJob.guid)
        if (idx >= 0) {
          uploadJobs.value[idx] = {
            ...uploadJobs.value[idx],
            progress: percent,
            processedRows: data.Current ?? data.InsertedCount,
            totalRows: data.Total ?? data.TotalCount
          }
        }
      }
      onProgress(updateProgress)
      onInsertProgress(updateProgress)
      onCompleted(() => {
        stopPolling()
        uploadProgressPanel.value = false
        piyangoKatilimciStore.refreshPiyangoKatilimciList = true
        piyangoKatilimciStore.katilimciFilePanel = true
        refreshUploadJobsAndPollProcessing()
      })
      onError(() => {
        stopPolling()
        uploadProgressPanel.value = false
        refreshUploadJobsAndPollProcessing()
      })
      uploadProgressPanel.value = true
      uploadProgressValue.value = processingJob.progress ?? 0
      await piyangoKatilimciService.SubscribeToJob(processingJob.guid, connectionId.value)
    }

    startPollingForAnyProcessingJob()
  }

  const AddNewKatilimci = () => {
    piyangoKatilimciStore.isPiyangoKatilimciUserUpdate = false
    piyangoKatilimciValidationStore.userFormChanged = false
    piyangoKatilimciStore.RestoreUserFormData()
    piyangoKatilimciStore.isNewKatilimci = true
    piyangoKatilimciStore.katilimciUserPanel = true
  }

  const OpenUser = async (row: any) => {
    piyangoKatilimciStore.isPiyangoKatilimciUserUpdate = true
    piyangoKatilimciValidationStore.userFormChanged = false
    let data = await piyangoKatilimciService.KatilimciData(row.id)
    Object.assign(piyangoKatilimciStore.piyangoKatilimciUserFormData, data)
    piyangoKatilimciStore.isNewKatilimci = false
    piyangoKatilimciStore.katilimciUserPanel = true
  }
  const FileUpload = async () => {
    if (!piyangoKatilimciValidationStore.FileFormCheck()) {
      piyangoKatilimciValidationStore.isFileFormValid = true
      return
    }

    removeUploadHandlers()
    uploadProgressValue.value = 0
    uploadProgressPanel.value = true

    onProgress((data) => {
      uploadProgressValue.value = data.Percent
    })

    onCompleted(() => {
      stopPolling()
      uploadProgressPanel.value = false
      piyangoKatilimciStore.refreshPiyangoKatilimciList = true
      piyangoKatilimciStore.katilimciFilePanel = true
      refreshUploadJobsAndPollProcessing()
    })

    onError(() => {
      stopPolling()
      uploadProgressPanel.value = false
    })

    const formData = new FormData()
    formData.append('excelFile', piyangoKatilimciStore.piyangoKatilimciFileFormData.excelFile)

    const connId = connectionId.value || ''
    const response = await dataStore.dataPost(
      `Katilimci/ExcelleYukle/${piyangoStore.selectedLottery}?connectionId=${connId}`,
      {
        data: formData,
        headers: { 'Content-Type': 'multipart/form-data' },
        skipErrorForStatuses: [409]
      }
    )

    if (response?._error && response.status === 409) {
      uploadProgressPanel.value = false
      const msg = response.data?.message || 'Bu çekiliş için zaten devam eden bir Excel yükleme işlemi var.'
      toastStore.AddToast(msg, 'alert', 6000)
      if (response.data?.existingJobId) {
        refreshUploadJobsAndPollProcessing()
        OpenUploadDetail(response.data.existingJobId)
      }
      return
    }

    if (response !== 'errorfalse' && response?.jobId) {
      startPolling(response.jobId)
    } else {
      uploadProgressPanel.value = false
    }
  }
  const DeleteAllButton = () => {
    dialogStore.CreateDialog({
      title: 'Tüm Katılımcıları Sil',
      id: 'deletekatilimci',
      content:
        'Tüm katılımcıları silmek istediğinize emin misiniz? Bu işlem geri alınamaz.',
      closeText: 'Vazgeç',
      buttons: [
        {
          label: 'Tüm katılımcıları Sil',
          type: 'alert',
          function: () => DeleteAll()
        }
      ]
    })
  }
  const DeleteAll = async () => {
    var dt = await dataStore.dataDelete(
      'Katilimci/DeleteCekilisKatilimci/' + piyangoStore.selectedLottery
    )

    if (dt !== 'errorfalse') {
      piyangoKatilimciStore.refreshPiyangoKatilimciList = true
      dialogStore.CloseDialog('deletekatilimci')
    }
  }

  const SendChangeRequest = async () => {
    piyangoOnayStore.piyangoOnayForm.onayDurumuIslemTipiId = 14
    piyangoOnayStore.piyangoOnayForm.file = ''
    piyangoOnayStore.piyangoOnayForm.aciklama = ''
    await piyangoOnayService.SaveOnayDurum()
  }

  const statusText = (status: string) => {
    const map: Record<string, string> = {
      Pending: 'Bekliyor',
      Processing: 'İşleniyor',
      Completed: 'Tamamlandı',
      Failed: 'Başarısız'
    }
    return map[status] || status
  }

  const formatDate = (val: string | Date) => {
    if (!val) return '-'
    return dateStore.dateFormat({ date: new Date(val), pattern: 'dd.mm.yyyy HH:MM' })
  }

  const OpenUploadDetail = (guid: string) => {
    selectedJobGuid.value = guid
    uploadDetailPanel.value = true
  }

  const stopPolling = () => {
    if (pollInterval) {
      clearInterval(pollInterval)
      pollInterval = null
    }
  }

  const startPolling = (jobId: string) => {
    stopPolling()
    pollInterval = setInterval(async () => {
      const status = await piyangoKatilimciService.GetUploadJobStatus(jobId)
      if (status && (status.status === 'Completed' || status.status === 'Failed')) {
        stopPolling()
        uploadProgressValue.value = status.status === 'Completed' ? 100 : status.progress || 0
        uploadProgressPanel.value = false
        piyangoKatilimciStore.refreshPiyangoKatilimciList = true
        piyangoKatilimciStore.katilimciFilePanel = true
        refreshUploadJobsAndPollProcessing()
      } else if (status) {
        uploadProgressValue.value = status.progress || 0
      }
    }, 2000)
  }

  const startPollingForExistingJob = (jobGuid: string) => {
    stopPolling()
    pollInterval = setInterval(async () => {
      const status = await piyangoKatilimciService.GetUploadJobStatus(jobGuid)
      if (status) {
        const idx = uploadJobs.value.findIndex((j: Record<string, any>) => j.guid === jobGuid)
        if (idx >= 0) {
          uploadJobs.value[idx] = { ...uploadJobs.value[idx], ...status }
        }
        if (status.status === 'Completed' || status.status === 'Failed') {
          stopPolling()
          piyangoKatilimciStore.refreshPiyangoKatilimciList = true
          refreshUploadJobsAndPollProcessing()
        }
      }
    }, 2000)
  }

  const refreshUploadJobsAndPollProcessing = async () => {
    const cekilisId = piyangoStore.selectedLottery
    if (cekilisId !== null) {
      uploadJobs.value = await piyangoKatilimciService.GetUploadJobs(cekilisId)
      startPollingForAnyProcessingJob()
    }
  }

  const startPollingForAnyProcessingJob = () => {
    const processingJob = uploadJobs.value.find(
      (j: Record<string, any>) => j.status?.toLowerCase() === 'processing'
    )
    if (processingJob?.guid) {
      startPollingForExistingJob(processingJob.guid)
    }
  }

  onUnmounted(() => {
    stopPolling()
    removeUploadHandlers()
  })
</script>
<style scoped>
  .progress-bar {
    width: 90%;
    max-width: 400px;
    height: 30px;
    background: #f0f0f0;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.15);
  }

  .progress-fill {
    height: 100%;
    background-color: #42b983;
    transition: width 0.3s ease;
  }

  .progress-text {
    margin-top: 12px;
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }

  .upload-warning {
    background: #fff8db;
    color: #856404;
    border: 1px solid #ffeeba;
    padding: 10px 14px;
    border-radius: 6px;
    margin-bottom: 16px;
    font-size: 14px;
    text-align: center;
  }

  .upload-panel-content {
    display: flex;
    flex-direction: column;
    gap: 32px;
    padding: 24px 24px 24px 24px;
  }

  .upload-progress-section {
    background: #f0f9ff;
    border: 1px solid #b6d4fe;
    border-radius: 8px;
    padding: 16px 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .upload-progress-title {
    margin: 0 0 12px;
    font-size: 15px;
    font-weight: 600;
    color: #1a1a2e;
    align-self: flex-start;
  }

  .upload-progress-section .upload-warning {
    margin-bottom: 16px;
    width: 100%;
  }

  .upload-progress-section .progress-bar {
    width: 100%;
    max-width: 100%;
  }

  .upload-progress-section .progress-text {
    margin-top: 12px;
    color: #1a1a2e;
  }

  .upload-history-section {
    padding-bottom: 20px;
    border-bottom: 1px solid #e8eaed;
  }

  .upload-history-title,
  .upload-form-title {
    margin: 0 0 14px;
    font-size: 15px;
    font-weight: 600;
    color: #1a1a2e;
    letter-spacing: 0.02em;
  }

  .upload-form-section {
    padding-top: 4px;
  }

  .upload-form-section :deep(.panel-documents-item) {
    margin-bottom: 0;
  }

  .upload-form-section :deep(.form-item-description) {
    margin-top: 8px;
    font-size: 13px;
    color: #5f6368;
    line-height: 1.4;
  }

  .history-loading {
    text-align: center;
    padding: 20px;
    color: #5f6368;
    font-size: 14px;
  }

  .history-items {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .history-item {
    display: grid;
    grid-template-columns: 1fr auto auto auto;
    align-items: center;
    gap: 16px;
    padding: 12px 16px;
    border: 1px solid #e8eaed;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
    background: #fafbfc;
  }

  .history-item:hover {
    background: #f1f3f5;
    border-color: #d0d5dd;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
  }

  .history-file {
    font-weight: 500;
    font-size: 14px;
    color: #1a1a2e;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .history-status {
    font-size: 12px;
    font-weight: 600;
    padding: 4px 10px;
    border-radius: 6px;
    white-space: nowrap;
  }

  .history-status.status-completed {
    color: #0d6832;
    background: #d4edda;
  }

  .history-status.status-failed {
    color: #721c24;
    background: #f8d7da;
  }

  .history-status.status-processing {
    color: #004085;
    background: #cce5ff;
  }

  .history-status.status-pending {
    color: #856404;
    background: #fff3cd;
  }

  .history-progress {
    font-size: 13px;
    font-weight: 500;
    color: #5f6368;
    min-width: 36px;
    text-align: right;
  }

  .history-date {
    font-size: 12px;
    color: #80868b;
    min-width: 100px;
    text-align: right;
  }

  /* İşleniyor durumunda progress bar */
  .history-item.processing .history-progress {
    font-weight: 600;
    color: #007bff;
  }
</style>
