<template>
  <div class="form-part form-title" v-if="isNew">
    <div class="form-title-buttons">
      <div class="button-c button-save" @click="SaveData">Kaydet</div>
      <router-link class="button-c button-cancel" to="/kullanicilar/kullanici-liste">
        Vazgeç
      </router-link>
    </div>
  </div>
  <div :class="['form-part', formChanged && !isNew ? 'changed' : '']">
    <div class="form-part-title">
      <h4>Kullanıcı Bilgileri</h4>
      <div class="form-part-title-buttons"></div>
    </div>
    <div class="form-part-content" v-if="loaded">
      <form-input
        required
        half
        modelKey="gercekAdi"
        v-model="formData.gercekAdi"
        :invalidText="invalidTexts.gercekAdi"
        label="Adı"
        @keyup="OnKeyup" />
      <form-input
        required
        half
        modelKey="gercekSoyadi"
        v-model="formData.gercekSoyadi"
        :invalidText="invalidTexts.gercekSoyadi"
        label="Soyadı"
        @keyup="OnKeyup" />
      <form-select
        required
        v-model="formData.kullaniciGoreviId"
        :listData="appUserRoleStore.appUserRoles"
        listVal="id"
        listText="gorevAdi"
        modelKey="kullaniciGoreviId"
        label="Kullanıcının Görevi"
        :invalidText="invalidTexts.kullaniciGoreviId"
        @change="OnKeyup" />
      <form-select
        required
        v-model="formData.birimId"
        :listData="appUserUnitStore.appUserUnits"
        listVal="id"
        listText="birimAdi"
        modelKey="birimId"
        label="Kullanıcının Birimi"
        :invalidText="invalidTexts.birimId"
        @change="OnKeyup" />
      <form-input
        required
        half
        modelKey="telefonNumarasi"
        v-model="formData.telefonNumarasi"
        :invalidText="invalidTexts.telefonNumarasi"
        label="Telefon"
        placeholder="5554443322"
        maxlength="10"
        minlength="10"
        @keyup="OnKeyup" />
      <form-input
        required
        half
        modelKey="email"
        v-model="formData.email"
        :invalidText="invalidTexts.email"
        label="Mail"
        placeholder="eposta@alanadi.com"
        type="email" />
      <div class="form-item" v-if="formChanged && !isNew">
        <button class="button-c button-save" @click="SaveData">Kaydet</button>
        <button class="button-c button-cancel" @click="CancelSave">Vazgeç</button>
      </div>
    </div>
  </div>
  <div class="form-part form-title" v-if="isNew">
    <div class="form-title-buttons">
      <div class="button-c button-save" @click="SaveData">Kaydet</div>
      <router-link class="button-c button-cancel" to="/kullanicilar/kullanici-liste">
        Vazgeç
      </router-link>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive, onBeforeMount } from 'vue'
  import { useRoute } from 'vue-router'
  import { useDataStore } from '@/stores/dataStore'
  const dataStore = useDataStore()
  import { useGlobalStore } from '@/stores/globalStore'
  const globalStore = useGlobalStore()
  import { useValidationStore } from '@/stores/validationStore'
  const validationStore = useValidationStore()

  import { useAppUserUnitStore } from '../../stores/appUserUnitStore'
  const appUserUnitStore = useAppUserUnitStore()
  import { useAppUserRoleStore } from '../../stores/appUserRoleStore'
  const appUserRoleStore = useAppUserRoleStore()
  import { useAppUserUnitService } from '../../service/appUserUnitService'
  const appUserUnitService = useAppUserUnitService()
  import { useAppUserRoleService } from '../../service/appUserRoleService'
  const appUserRoleService = useAppUserRoleService()
  import { useToastStore } from '@/components/global/toastStore'
  const toastStore = useToastStore()

  import router from '@/router/'

  const route = useRoute()
  const isNew = ref<boolean>(true)
  if (route.name === 'KullaniciDetay') isNew.value = false

  const loaded = ref<boolean>(false)
  const formChanged = ref<boolean>(false)

  const formData = reactive<Record<string, any>>({
    gercekAdi: '',
    gercekSoyadi: '',
    telefonNumarasi: '',
    email: '',
    kullaniciGoreviId: '',
    birimId: '',
    basvuruTipId: 24,
    kvkk: true,
    uyelikSozlesmesi: true
  })
  const isFormValid = ref<boolean>(true)
  const startData = reactive<Record<string, any>>(Object.assign({}, formData))
  const invalidTexts = ref<Record<string, any>>({})
  const safeData = reactive<Record<string, any>>({})

  const OnKeyup = () => {
    formChanged.value = true
  }

  const IsFieldEmpty = (field: string, text: string) => {
    if (validationStore.checkEmpty(formData[field]) || formData[field] === 0) {
      invalidTexts.value[field] = text
      isFormValid.value = false
    } else {
      delete invalidTexts.value[field]
    }
  }

  const FormCheck = (): boolean => {
    IsFieldEmpty('gercekAdi', 'Kullanıcının adı boş bırakılamaz.')
    IsFieldEmpty('gercekSoyadi', 'Kullanıcının soyadı boş bırakılamaz.')
    IsFieldEmpty('telefonNumarasi', 'Kullanıcının telefonunu yazmalısınız')
    IsFieldEmpty('email', 'Kullanıcının mail adresini yazmalısınız')
    IsFieldEmpty('kullaniciGoreviId', 'Kullanıcının görevini seçmelisiniz')
    IsFieldEmpty('birimId', 'Kullanıcının birimini seçmelisiniz')
    return isFormValid.value
  }

  const GetData = async () => {
    let data = await dataStore.dataGet('Auth/userbyuserid/' + globalStore.selUser)
    if (data !== 'errorfalse') {
      Object.assign(formData, data)
      Object.assign(safeData, data)
      setTimeout(() => {
        loaded.value = true
      }, 30)
    }
  }
  const SaveData = async () => {
    if (FormCheck()) {
      let res: any
      formData.basvuruTipId = formData.kullaniciGoreviId === 1 ? 19:24

      if (isNew.value) {
        res = await dataStore.dataPost('Auth/register/', {
          data: formData
        })
      } else {
        const inData: Record<string, any> = {}
        const startProps = Object.keys(startData)
        Object.keys(formData).forEach((key, i) => {
          for (let i = 0; i <= startProps.length; i++) {
            if (key === startProps[i]) inData[key] = formData[key]
          }
        })
        inData.id = formData.id
        inData.basvuruTipId = inData.kullaniciGoreviId === 1 ? 19:24
        
        res = await dataStore.dataPut('Auth/Guncelleme/' + formData.id, {
          data: inData
        })
      }

      if (res !== 'errorfalse') {
        if (isNew.value) toastStore.AddToast('Kullanıcı başarıyla kaydedildi', 'success', 5000)
        else toastStore.AddToast('Başarıyla kaydedildi', 'success', 5000)
        formChanged.value = false
        loaded.value = false
        globalStore.selUser = res.user.id
        if (isNew.value) router.push('/kullanicilar/kullanici-liste')
        else GetData()
        isNew.value = false
      }
    } else {
      isFormValid.value = true
    }
  }
  const CancelSave = () => {
    Object.assign(formData, safeData)
    formChanged.value = false
  }

  onBeforeMount(async () => {
    await appUserUnitService.GetAppUserUnitList()
    await appUserRoleService.GetAppUserRoleList()

    if (!isNew.value) await GetData()
    else loaded.value = true
  })
</script>
