<!--
Page 'Mon abonnement'

@see https://ressources.opentalent.fr/display/SPEC/Mon+abonnement
-->
<template>
  <LayoutContainer>
      <v-expansion-panels v-model="openedPanels" :multiple="true">
        <UiExpansionPanel :title="$t('subscription_page')" icon="fas fa-info">
          <v-container fluid class="container">
            <v-row>
              <v-col cols="12" lg="6" sm="12">
                {{ $t('version') }} : <strong>{{ dolibarrAccount ? $t(dolibarrAccount.product) : '-' }}</strong>
                <span v-if="organizationProfile.isTrialActive"> - En cours d'essai: <strong>{{$t('PRODUCT_ARTIST_PREMIUM')}} - J-{{organizationProfile.trialCountDown}}</strong></span>
              </v-col>
              <v-col cols="12" lg="6" sm="12">
                {{ $t('client_id') }} : {{ dolibarrAccount ? dolibarrAccount.clientNumber : '-' }}
              </v-col>
            </v-row>
          </v-container>
        </UiExpansionPanel>

        <UiExpansionPanel :title="$t('service_detail')" icon="fas fa-info"
                          v-if="dolibarrAccount && dolibarrAccount.contract"
        >
          <v-container fluid class="container">
            <v-row>
              <v-col cols="12"
                     lg="12"
                     v-for="line in dolibarrAccount.contract.lines"
                     :key="line.id"
              >
                <strong>{{ line.serviceLabel }}</strong> - {{ $t('until') }} : {{ $d(line.dateEnd) }}
              </v-col>

              <v-col cols="12" lg="12" v-if="ability.can('manage', 'texto')">
                <strong>{{ $t('remaining_sms_credit') }}</strong> -
                <span v-if="!mobytPending && mobytStatus !== null && mobytStatus.active">
                        {{
                    mobytStatus.money.toLocaleString($i18n.locale, {
                      style: 'currency',
                      currency: 'EUR',
                    })
                  }}
                        {{
                    i18n.t('convert_price_to_sms', {
                      nb_sms: mobytStatus.amount,
                    })
                  }}
                </span>
              </v-col>
            </v-row>
          </v-container>
        </UiExpansionPanel>

        <UiExpansionPanel
          v-if="showDolibarrPanel"
          title="bills"
          icon="fas fa-file"
        >
          <v-container :fluid="true" class="container">
            <v-row>
              <v-table v-if="dolibarrAccount !== null">
                <thead>
                  <tr>
                    <th>{{ $t('reference') }}</th>
                    <th>{{ $t('date') }}</th>
                    <th>{{ $t('taxExcludedAmount') }}</th>
                    <th>{{ $t('status') }}</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="bill in dolibarrAccount.bills" :key="bill.id">
                    <td>{{ bill.ref }}</td>
                    <td>{{ $d(bill.date) }}</td>
                    <td>
                      {{
                        bill.taxExcludedAmount.toLocaleString($i18n.locale, {
                          style: 'currency',
                          currency: 'EUR',
                        })
                      }}
                    </td>
                    <td>
                      {{ bill.paid === true ? $t('paid') : $t('unpaid') }}
                    </td>
                    <td>
                      <a @click="downloadDolibarrBill(bill.ref)" class="clickable">
                        {{ $t('download') }}
                      </a>
                    </td>
                  </tr>
                </tbody>
              </v-table>
            </v-row>
          </v-container>
        </UiExpansionPanel>

        <UiExpansionPanel :title="$t('opentalent_offer')" icon="fas fa-plus" v-if="!organizationProfile.isManagerProduct">
          <v-container fluid class="container">
            <v-row class="offer_title" v-if="!md && mdAndUp && !organizationProfile.isSchool">
              <v-col cols="12" :lg="organizationProfile.isArtistPremiumProduct ? 3 : 6" sm="12">
                <span class="theme-artist">Pour les orchestres, chorales, compagnies et troupes artistiques</span>
              </v-col>
              <v-col cols="12" :lg="organizationProfile.isArtistPremiumProduct ? 3 : 5" sm="12" :offset="organizationProfile.isArtistPremiumProduct ? 0 : 1">
                <span class="theme-school">Pour les établissements d'enseignements artistiques*</span>
              </v-col>
            </v-row>

            <v-row class="card-container">
              <v-col lg="3" sm="12" md="6" v-if="organizationProfile.isArtistProduct">
                <PagesSubscriptionCard
                class="artistCard"
                title="Logiciel Artist Standard"
                :extraHeader="organizationProfile.isArtistProduct ? 'Votre version' : false"
                color="artist"
                :list="listCheck.artist"
              >
                <template #card.subTitle>
                  <div class="priceBlock">
                    <span class="price">{{formatCurrency(11, 'EUR')}}</span> TTC/mois
                  </div>
                </template>
                <template #card.action>
                  <v-btn
                    v-if="!organizationProfile.isArtistProduct"
                    class="theme-artist btn"
                    href="https://logiciels.opentalent.fr/opentalent-artist"
                    target="_blank"
                  >
                    En savoir plus <i class="fa-solid fa-greater-than small"></i>
                  </v-btn>
                </template>
              </PagesSubscriptionCard>
              </v-col>

              <v-col lg="3" sm="12" md="6" v-if="organizationProfile.isArtist">
                <PagesSubscriptionCard
                  class="artistCard"
                  title="Logiciel Artist Premium*"
                  :extraHeader="organizationProfile.isArtistPremiumProduct ? 'Votre version' : '1 mois d\'essai offert'"
                  color="artist"
                  :list="listCheck.artistPremium"
                >
                  <template #card.subTitle>
                    <div class="priceBlock">
                      <span class="price">{{organizationProfile.isCmf ? formatCurrency(7.5, 'EUR') : formatCurrency(18.0, 'EUR')}}</span> TTC/mois
                    </div>
                  </template>
                  <template #card.action>
                    <v-row >
                      <v-col cols="12" v-if="!organizationProfile.isArtistPremiumProduct && (accessProfileStore.isAdmin || accessProfileStore.isCaMember)">
                        <v-btn
                          class="btn trialBtn"
                          @click="startTrial"
                        >
                          Essayer la version premium <i class="fa-solid fa-greater-than small"></i>
                        </v-btn>
                      </v-col>
                      <v-col cols="12" v-if="(!organizationProfile.isArtistPremiumProduct || organizationProfile.isTrialActive) && (accessProfileStore.isAdmin || accessProfileStore.isCaMember)">
                        <v-btn
                          class="theme-artist btn"
                          @click="subscription"
                        >
                          Souscrire à l'offre <i class="fa-solid fa-greater-than small"></i>
                        </v-btn>
                      </v-col>
                      <v-col cols="12" v-if="!organizationProfile.isArtistPremiumProduct" >
                        <v-btn
                          class="theme-artist btn"
                          href="https://logiciels.opentalent.fr/opentalent-artist"
                          target="_blank"
                        >
                          En savoir plus <i class="fa-solid fa-greater-than small"></i>
                        </v-btn>
                      </v-col>
                      <v-col cols="12" v-if="organizationProfile.isTrialActive && (accessProfileStore.isAdmin || accessProfileStore.isCaMember)">
                        <v-btn
                          class="stop_btn"
                          @click="showStopTrialDialog"
                        >
                          Arrêter l'essai
                        </v-btn>
                      </v-col>
                      <v-col cols="12">
                          <span class="special_conditions">
                          *Convient aux petites écoles sans besoins spécifiques de gestion pédagogique, de facturation, etc.
                          Pour une solution complète optez pour Opentalent School
                        </span>
                      </v-col>
                    </v-row>
                  </template>
                </PagesSubscriptionCard>
              </v-col>

              <v-col lg="3" sm="12" md="6" :offset="!md && mdAndUp ? (organizationProfile.isSchool ? 4 : (organizationProfile.isArtistPremiumProduct ? 0 : 2)) : 0">
                <PagesSubscriptionCard
                  class="schoolCard"
                  :title="!organizationProfile.isSchool ? 'Logiciel School Standard / Premium' : (
                    organizationProfile.isSchoolPremiumProduct ? 'Logiciel School Premium' : 'Logiciel School Standard'
                  )"
                  :subTitle="!organizationProfile.isSchool ? 'Sur devis' : ''"
                  :extraHeader="organizationProfile.isSchool ? 'Votre version' : false"
                  color="school"
                  :list="listCheck.school"
                >
                  <template #card.action>
                    <v-row>
                      <v-col cols="12">
                        <v-btn
                          v-if="!organizationProfile.isSchool"
                          class="theme-school btn"
                          href="https://logiciels.opentalent.fr/opentalent-school"
                          target="_blank"
                        >
                          En savoir plus <i class="fa-solid fa-greater-than small"></i>
                        </v-btn>
                      </v-col>
                      <v-col cols="12">
                          <span class="special_conditions">
                          *Extranet disponible uniquement dans la version Opentalent School Premium
                        </span>
                      </v-col>
                    </v-row>
                  </template>
                </PagesSubscriptionCard>
              </v-col>
            </v-row>
          </v-container>
        </UiExpansionPanel>

        <UiExpansionPanel :title="$t('opentalent_options')" icon="fas fa-plus">
          <v-container fluid class="container card-container">
            <v-row cols="12" >
              <v-col lg="3" sm="12" md="6">
                <PagesSubscriptionCard
                  class="optionsCard"
                  title="SMS"
                  sub-title="Option payante"
                  color="primary"
                  :list="listCheck.sms"
                >
                  <template #card.action>
                    <v-btn
                      class="theme-primary btn"
                      :href="
                          runtimeConfig.public.fileStorageBaseUrl +
                          (organizationProfile.isCmf ? '/Bon_de_commande/Achat_SMS_CMF.pdf' : '/Bon_de_commande/Achat_SMS_Public.pdf')
                        "
                      target="_blank"
                    >
                      acheter des credits SMS <i class="fa-solid fa-greater-than small"></i>
                    </v-btn>
                  </template>
                </PagesSubscriptionCard>
              </v-col>

              <v-col lg="3" sm="12" md="6">
                <PagesSubscriptionCard
                  class="optionsCard"
                  title="Nom de domaine"
                  sub-title="Option payante"
                  color="primary"
                  :list="listCheck.domain"
                >
                  <template #card.action>
                    <v-btn
                      class="theme-primary btn"
                      :href="
                          runtimeConfig.public.fileStorageBaseUrl +
                          '/Bon_de_commande/Nom_de_domaine.pdf'
                        "
                      target="_blank"
                    >
                      souscrire à l'option <i class="fa-solid fa-greater-than small"></i>
                    </v-btn>
                  </template>
                </PagesSubscriptionCard>
              </v-col>
            </v-row>
          </v-container>
        </UiExpansionPanel>

      </v-expansion-panels>

  </LayoutContainer>

  <DialogTrialAllReadyDid
    :show="showDialogTrialAllReadyDid"
    @closeDialog = "showDialogTrialAllReadyDid = false"
  />

  <DialogTrialStopConfirmation
    :show="showDialogTrialStopConfirmation"
    @closeDialog = "showDialogTrialStopConfirmation = false"
    @stopTrial = "stopTrial"
  />
</template>

<script setup lang="ts">
import {useAbility} from '@casl/vue'
import type {Ref} from 'vue'
import {useDisplay} from 'vuetify'
import type {AsyncData} from '#app'
import {useOrganizationProfileStore} from '~/stores/organizationProfile'
import {useEntityFetch} from '~/composables/data/useEntityFetch'
import DolibarrAccount from '~/models/Organization/DolibarrAccount'
import MobytUserStatus from '~/models/Organization/MobytUserStatus'
import UrlUtils from '~/services/utils/urlUtils';
import {useDownloadFromRoute} from '~/composables/utils/useDownloadFromRoute';
import {useApiLegacyRequestService} from "~/composables/data/useApiLegacyRequestService";
import {usePageStore} from "~/stores/page";

//meta
definePageMeta({
  name: 'subscription_page',
})

//Get composables
const ability = useAbility()
const runtimeConfig = useRuntimeConfig()
const {mdAndUp, md} = useDisplay()
const {fetch} = useEntityFetch()
const i18n = useI18n()
const { apiRequestService } = useApiLegacyRequestService()

//Init ref
const showDialogTrialAllReadyDid: Ref<boolean> = ref(false)
const showDialogTrialStopConfirmation: Ref<boolean> = ref(false)
const openedPanels: Ref<Array<string>> = initPanel()
const organizationProfile = getOrganizationProfile()
const accessProfileStore = useAccessProfileStore()
const {mobytStatus, mobytPending}: Record<Ref<MobytUserStatus | null>, Ref<boolean>> = getMobytInformations()

const {data: dolibarrAccount, pending: dolibarrPending} = fetch(
  DolibarrAccount,
  organizationProfile.id,
)

const showDolibarrPanel = computed(
  () =>
    !dolibarrPending.value &&
    dolibarrAccount.value &&
    dolibarrAccount.value.bills.length > 0,
)
const formatCurrency = (value: number, currency: string): string => {
  return value.toLocaleString(i18n.locale.value, {
    style: 'currency',
    currency,
  })
}

const listCheck: Record<string, Array<string>> = {
  'artist' : [
    '100 Mo de stockage',
    '75 comptes utilisateurs',
    'Gestion de la structure',
    'Site internet restreint',
    'Options disponibles',
  ],
  'artistPremium' : [
    '1Go de stockage',
    '150 comptes utilisateurs',
    'Gestion de la structure',
    'Site internet illimité',
    'Options disponibles',
  ],
  'school' : [
    '500 Mo ou 1Go de stockage',
    '3 comptes administrateurs',
    'Extranet élèves, tuteurs, professeurs*',
    'Gestion de la structure',
    'Suivi pédagogique, facturation, ...',
    'Site internet complet',
    'Options adaptées à chaque structure',
  ],
  'sms': [
    'Envoyez des SMS depuis votre logiciel',
    'Choisissez le nombre de crédits'
  ],
  'domain':[
    'Bénéficiez de votre propre nom de domaine',
    'Et d\'une adresse mail personnalisée'
  ]
}

/**
 * Initialisation des panels ouverts
 */
function initPanel(): Ref<Array<string>> {
  // On déplie les expansion panels dans le onMounted en attendant la résolution du bug : https://github.com/vuetifyjs/vuetify/issues/16427#issuecomment-1380927133
  // TODO: quand le bug ci dessus est résolu, remplacer par `const openedPanels: Ref<Array<string>> = ref(['informations', 'bills', 'more_features'])`
  const openedPanels: Ref<Array<string>> = ref([])
  onMounted(() => {
    openedPanels.value = [i18n.t('subscription_page'), i18n.t('opentalent_offer'), i18n.t('opentalent_options')]
  })
  return openedPanels
}

/**
 * Récupération de l'organization profile
 */
function getOrganizationProfile() {
  const organizationProfile = useOrganizationProfileStore()
  if (organizationProfile.id === null) {
    throw new Error("Missing organization's id")
  }
  return organizationProfile
}

/**
 * Récupération des informations Mobyt
 */
function getMobytInformations(): Record<Ref<MobytUserStatus | null>, Ref<boolean>> {
  let mobytStatus: Ref<MobytUserStatus | null> = ref(null)
  let mobytPending: Ref<boolean> = ref(false)

  if (ability.can('manage', 'texto')) {
    const {data, pending} = fetch(
      MobytUserStatus,
      organizationProfile!.id!,
    ) as AsyncData<MobytUserStatus | null, Error | null>
    mobytStatus = data
    mobytPending = pending
  }
  return {mobytStatus, mobytPending}
}


/**
 * Action lorsque l'on souhaite démarrer l'essai
 */
async function startTrial(){
  try{
    await apiRequestService.get('/trial/is_available')
    const v1BaseURL = runtimeConfig.baseUrlAdminLegacy || runtimeConfig.public.baseUrlAdminLegacy
    await navigateTo(UrlUtils.join(v1BaseURL, '#', 'trial'), {
      external: true
    })
  }catch(error){
    showDialogTrialAllReadyDid.value = true
  }
}

/**
 * Action lorsque l'on souhaite souscrire à artist premium
 */
async function subscription(){
  const v1BaseURL = runtimeConfig.baseUrlAdminLegacy || runtimeConfig.public.baseUrlAdminLegacy
  await navigateTo(UrlUtils.join(v1BaseURL, '#', 'subscribe'), {
    external: true
  })
}

/**
 * Action lorsque l'on souhaite afficher la modal de confirmation pour stopper
 */
function showStopTrialDialog(){
  showDialogTrialStopConfirmation.value = true
}

/**
 * Action lorsque l'on souhaite stopper l'essai
 */
async function stopTrial() {
  usePageStore().loading = true
  await apiRequestService.post('/trial/stop')
  const v1BaseURL = runtimeConfig.baseUrlAdminLegacy || runtimeConfig.public.baseUrlAdminLegacy
  await navigateTo(UrlUtils.join(v1BaseURL, '#', 'dashboard'), {
    external: true
  })
}


const downloadDolibarrBill = (ref: string): void => {
  const route = UrlUtils.join('api/dolibarr/download/invoice', ref)

  useDownloadFromRoute(route, `${ref}.pdf`)
}
</script>


<style scoped lang="scss">
.clickable {
  cursor: pointer;
  text-decoration: underline;
}

.offer_title{
  span{
    border-radius: 5px;
    display: block;
    font-weight: bold;
    text-align: center;
    padding: 5px;
  }
}

.card-container{
  .v-row {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display:  flex;
    flex-wrap: wrap;
  }
  .v-row > [class*='v-col-'] {
    display: flex;
    flex-direction: column;
  }
  .small{
    font-size:6px;
    padding-top: 5px;
    padding-left: 5px;
  }
  .priceBlock{
    text-align: center;
    font-size: 15px;
    font-weight: normal;
    .price{
      font-size: 30px;
      font-weight: bold;
    }
  }
}

.artistCard{
  :deep(.v-card-title){
    text-align: center;
  }
}

.special_conditions{
  font-size: 10px;
}

.trialBtn{
  color: #000;
  border: 1px solid rgb(var(--v-theme-artist));
}

.optionsCard{
  :deep(.margin-sup){
    margin-top: 0px;
  }
}

.stop_btn{
  color: rgb(var(--v-theme-danger));
}
</style>
