<template>
  <div :class="['form-part']" id="display-bilgi">
    <div class="form-part-title">
      <h4>Piyango Bilgileri</h4>
      <div class="form-part-title-buttons" v-if="!isPreview && loaded">
        <button
          @click="BasvuruBedeliDialog"
          v-if="
            (piyangoStore.lotteryApprove === 1 || piyangoStore.lotteryApprove === 4) &&
            (!piyangoStore.lotteryBasvuruBedeliStatus ||
              piyangoStore.lotteryBasvuruBedeliStatus === null)
          "
          class="button-save">
          Başvuru Bedelini Muhasebeleştir
        </button>
        <button
          @click="OpenIzinBedeliModal"
          v-if="
            piyangoStore.lotteryApprove === 4 &&
            piyangoStore.lotteryData.amacpiyangoId !== 3 &&
            (!piyangoStore.lotteryIzinBedeliStatus ||
              piyangoStore.lotteryIzinBedeliStatus === null)
          "
          class="button-save">
          İzin Bedelini Muhasebeleştir
        </button>
        <router-link
          :to="'/piyangolar/detay/' + route.params.piyangoId + '/piyango-bilgileri'"
          class="button-c">
          Piyango Detayına Git
        </router-link>
      </div>
    </div>
    <div class="form-inner-comment waiting-d" v-if="!loaded">Yükleniyor, lütfen bekleyiniz...</div>
    <piyango-bilgileri-display-content v-if="loaded" :isPreview="isPreview" />

    <!-- İzin Bedeli Modal -->
    <teleport to="body">
      <div v-if="showIzinBedeliModal" class="modal-overlay" @click="CloseIzinBedeliModal">
        <div class="modal-content" @click.stop>
          <div class="modal-header">
            <h3>İzin Bedeli Muhasebeleştir</h3>
            <button class="modal-close" @click="CloseIzinBedeliModal">×</button>
          </div>
          <div class="modal-body">
            <div class="form-group">
              <label>Oran Seçiniz:</label>
              <select @change="OnOranChange" class="form-select">
                <option value="">Lütfen bir oran seçiniz</option>
                <option v-for="oran in izinBedelOranlari" :key="oran.id" :value="oran.id">
                  {{ oran.oran }}% - {{ oran.adi }}
                </option>
              </select>
            </div>
            <div class="">
              <table class="table-bordered">
                <tbody>
                  <tr>
                    <td>Toplam İkramiye Bedeli:</td>
                    <td>
                      {{
                        globalStore.toTrLocale(
                          Number(piyangoIkramiyeStore.totalIkramiyeValue)
                        )
                      }}
                    </td>
                  </tr>
                  <tr>
                    <td>İzin Bedeli Oran Tutarı:</td>
                    <td>
                      {{ globalStore.toTrLocale(calculatedOran) }}
                    </td>
                  </tr>
                  <tr>
                    <td>KDV:</td>
                    <td>
                      {{ globalStore.toTrLocale(calculatedKdv) }}
                    </td>
                  </tr>
                  <tr>
                    <td>Toplam Bedel:</td>
                    <td>
                      {{
                        globalStore.toTrLocale(
                          Number(calculatedOran) + Number(calculatedKdv)
                        )
                      }}
                    </td>
                  </tr>

                  <tr v-if="piyangoStore.lotteryData.izinTarihi !== undefined">
                    <td>İzin Tarihi:</td>
                    <td>
                      {{
                        dateStore.dateFormat({
                          date: piyangoStore.lotteryData.izinTarihi,
                          pattern: 'dd-mm-yy',
                          splitDate: '/'
                        })
                      }}
                    </td>
                  </tr>
                  <tr v-if="piyangoStore.lotteryData.izinSayisi !== undefined">
                    <td>İzin Sayısı:</td>
                    <td>
                      {{ piyangoStore.lotteryData.izinSayisi }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          <div class="modal-footer">
            <button class="button-c button-cancel" @click="CloseIzinBedeliModal">
              İptal
            </button>
            <button class="button-c button-save" @click="IzinBedeliMuhasebelestir">
              Muhasebeleştir
            </button>
          </div>
        </div>
      </div>
    </teleport>
  </div>
</template>
<script setup lang="ts">
  import { ref, onBeforeMount, computed } from 'vue'

  import { useToastStore } from '@/components/global/toastStore'
  const toastStore = useToastStore()
  import { usePiyangoIkramiyeStore } from '@/module/cekilisler/stores/piyangoIkramiyeStore'
  const piyangoIkramiyeStore = usePiyangoIkramiyeStore()
  import { useGlobalStore } from '@/stores/globalStore'
  const globalStore = useGlobalStore()
  import { useDialogStore } from '@/components/global/dialogStore'
  const dialogStore = useDialogStore()
  import { useDateStore } from '@/stores/dateStore'
  const dateStore = useDateStore()

  export interface Props {
    isPreview?: boolean
  }

  const props = withDefaults(defineProps<Props>(), { isPreview: false })

  import PiyangoBilgileriDisplayContent from '@/module/cekilisler/components/content/PiyangoBilgileriDisplayContent.vue'

  import { useRoute } from 'vue-router'
  const route = useRoute()

  import { useDataStore } from '@/stores/dataStore'
  const dataStore = useDataStore()
  import { usePiyangoStore } from '@/module/cekilisler/stores/piyangoStore'
  const piyangoStore = usePiyangoStore()
  import { useMuhasebeSettingsStore } from '@/module/muhasebe/store/muhasebeSettingsStore'
  const muhasebeSettingsStore = useMuhasebeSettingsStore()

  const loaded = ref<boolean>(false)
  const showIzinBedeliModal = ref<boolean>(false)
  const selectedOran = ref<number | null>(null)
  const izinBedelOranlari = ref<Record<string, any>[]>([])
  const selectedOranId = ref<number | null>(null)
  const calculatedKdv = ref<number>(0)
  const calculatedOran = ref<number>(0)

  const calculatedBasvuruKdv = computed<number>(() =>
    muhasebeSettingsStore.muhasebeSettingsForm.basvuruBedeli !== undefined &&
    muhasebeSettingsStore.muhasebeSettingsForm.basvuruBedeliKdvOrani !== undefined
      ? (Number(muhasebeSettingsStore.muhasebeSettingsForm.basvuruBedeli) *
          Number(muhasebeSettingsStore.muhasebeSettingsForm.basvuruBedeliKdvOrani)) /
        100
      : 0
  )

  const GetData = async () => {
    let data = await dataStore.dataGet(
      'CekilisBilgi/Cekilis/' + piyangoStore.selectedLottery
    )

    if (data !== 'errorfalse') {
      Object.assign(piyangoStore.lotteryData, data)
      piyangoStore.lotterySelectedProvience =
        piyangoStore.lotteryData.kampsamIlStrList.join(', ')

      GetDuzenleyen()

      if (piyangoStore.lotteryData.baglisirketId !== null) GetAraciUye()

      loaded.value = true
    }
  }

  const GetDuzenleyen = async () => {
    let data = await dataStore.dataGet(
      'Auth/userbyuserid/' + piyangoStore.lotteryData.duzenleyenId
    )

    if (data !== 'errorfalse') {
      Object.assign(piyangoStore.duzenleyenData, data)
      piyangoStore.customerApproved = data.islemTipi === 4
    }
  }

  const GetAraciUye = async () => {
    let data = await dataStore.dataGet(
      'Auth/userbyuserid/' + piyangoStore.lotteryData.baglisirketId
    )
    if (data !== 'errorfalse') {
      Object.assign(piyangoStore.araciUyeData, data)
    }
  }

  const GetIzinBedelOranlari = async () => {
    let data = await dataStore.dataGet('IzinBedelOrani/aktif')
    if (data !== 'errorfalse') {
      izinBedelOranlari.value = data
    }
  }
  const GetIkramiyeTotalValues = async () => {
    let data = await dataStore.dataGet('Ikramiye/Cekilis/' + piyangoStore.selectedLottery +'?pageNumber=0')
    //todo:page 0
    if (data !== 'errorfalse') {
      piyangoIkramiyeStore.totalIkramiyeValue = data.toplamdeger
    }
  }
  const BasvuruBedeliDialog = () => {
    dialogStore.CreateDialog({
      title: 'Başvuru Bedelini Muhasebeleştir',
      id: 'basvurubedelimuhasebelestir',
      contentHtml: `<table class='table-bordered'>
                <tbody>
                  <tr>
                    <td>Başvuru Bedeli:</td>
                    <td>${
                      muhasebeSettingsStore.muhasebeSettingsForm.basvuruBedeli !==
                      undefined
                        ? globalStore.toTrLocale(
                            muhasebeSettingsStore.muhasebeSettingsForm.basvuruBedeli
                          )
                        : 0
                    } ₺</td>
                  </tr>
                  <tr>
                    <td>KDV (%${
                      muhasebeSettingsStore.muhasebeSettingsForm.basvuruBedeliKdvOrani
                    }):</td>
                    <td>
                      ${
                        calculatedBasvuruKdv.value !== undefined
                          ? globalStore.toTrLocale(calculatedBasvuruKdv.value)
                          : 0
                      }
                    </td>
                  </tr>
                  <tr>
                    <td>Toplam Bedel:</td>
                    <td>
                      ${
                        muhasebeSettingsStore.muhasebeSettingsForm.basvuruBedeli !==
                        undefined
                          ? globalStore.toTrLocale(
                              Number(
                                muhasebeSettingsStore.muhasebeSettingsForm.basvuruBedeli
                              ) + calculatedBasvuruKdv.value
                            )
                          : 0
                      }
                    </td>
                  </tr>
                </tbody>
              </table>`,
      closeText: 'Vazgeç',
      buttons: [
        {
          label: 'Başvuru Bedelini Muhasebeleştir',
          type: 'alert',
          function: () => BasvuruBedeliMuhasebelestir()
        }
      ]
    })
  }
  const BasvuruBedeliMuhasebelestir = async () => {
    let data = await dataStore.dataGet(
      'MuhasebeSettings/BasvuruBedeli/' + piyangoStore.selectedLottery
    )
    if (data !== 'errorfalse') {
      toastStore.AddToast(
        'Başvuru bedeli başarıyla muhasebeleştirildi. Fatura No: ' + data.belgeNo,
        'success',
        30000
      )
      dialogStore.CloseDialog('basvurubedelimuhasebelestir')
      loaded.value = false
      await GetData()
      piyangoStore.lotteryBasvuruBedeliStatus = true

      setTimeout(() => {
        loaded.value = true
      }, 30)
    }
  }

  const OpenIzinBedeliModal = async () => {
    await GetIzinBedelOranlari()
    await GetIkramiyeTotalValues()
    showIzinBedeliModal.value = true
    selectedOran.value = null
    selectedOranId.value = null
  }

  const CloseIzinBedeliModal = () => {
    showIzinBedeliModal.value = false
    selectedOran.value = null
    selectedOranId.value = null
  }

  const OnOranChange = (event: Event) => {
    const target = event.target as HTMLSelectElement
    const selectedId = parseInt(target.value)
    const selectedOranData = izinBedelOranlari.value.find(
      (item) => item.id === selectedId
    )

    if (selectedOranData) {
      selectedOranId.value = selectedOranData.id
      selectedOran.value = selectedOranData.oran
    } else {
      selectedOranId.value = null
      selectedOran.value = null
    }

    calculatedOran.value =
      (Number(piyangoIkramiyeStore.totalIkramiyeValue) * Number(selectedOran.value)) / 100

    calculatedKdv.value =
      (calculatedOran.value *
        Number(muhasebeSettingsStore.muhasebeSettingsForm.basvuruBedeliKdvOrani)) /
      100
  }

  const IzinBedeliMuhasebelestir = async () => {
    if (selectedOranId.value === null) {
      toastStore.AddToast('Lütfen bir oran seçiniz', 'error', 5000)
      return
    }

    let data = await dataStore.dataGet(
      'MuhasebeSettings/IzinBasvuruBedeli/' +
        piyangoStore.selectedLottery +
        '/' +
        selectedOranId.value
    )
    if (data !== 'errorfalse') {
      toastStore.AddToast(
        'İzin bedeli başarıyla muhasebeleştirildi. Fatura No: ' + data.izinBelgeNo,
        'success',
        30000
      )
      loaded.value = false
      await GetData()
      piyangoStore.lotteryIzinBedeliStatus = true
      showIzinBedeliModal.value = false
      selectedOran.value = null
      selectedOranId.value = null
      setTimeout(() => {
        loaded.value = true
      }, 30)
    }
  }

  onBeforeMount(async () => {
    await dataStore.GetIlList()
    await GetData()
  })
</script>

<style scoped>
  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  }

  .modal-content {
    background: white;
    border-radius: 8px;
    padding: 0;
    max-width: 500px;
    width: 90%;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  }

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #e5e7eb;
  }

  .modal-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #1f2937;
  }

  .modal-close {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #6b7280;
    padding: 0;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    transition: background-color 0.2s;
  }

  .modal-close:hover {
    background-color: #f3f4f6;
  }

  .modal-body {
    padding: 24px;
  }

  .form-group {
    margin-bottom: 16px;
  }

  .form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #374151;
  }

  .form-select {
    width: 100%;
    padding: 12px;
    border: 1px solid #d1d5db;
    border-radius: 6px;
    font-size: 14px;
    background-color: white;
    transition: border-color 0.2s;
  }

  .form-select:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  }

  .modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 20px 24px;
    border-top: 1px solid #e5e7eb;
    background-color: #f9fafb;
    border-radius: 0 0 8px 8px;
  }

  .button-c {
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
  }

  .button-cancel {
    background-color: #6b7280;
    color: white;
  }

  .button-cancel:hover {
    background-color: #4b5563;
  }

  .button-save {
    background-color: #3b82f6;
    color: white;
  }

  .button-save:hover {
    background-color: #2563eb;
  }
  .table-bordered {
    width: 100%;
  }
  .table-bordered tr td {
    border-bottom: 1px solid #d8d8d8;
    padding: 8px;
  }
</style>
