<template>
  <div class="q-pa-md row items-start q-gutter-md">
    <q-card class="app-card">
      <q-card-section class="bg-primary text-white">
        {{ appinfo?.name }}
      </q-card-section>
      <q-separator inset />
      <q-card-section>
        <q-field  stack-label full-width  label="アプリ名">
          <template v-slot:append>
            <a :href="link" target="_blank" title="Kiontoneへ" @click="linkClick">
              <q-icon name="link" />
            </a>
          </template>
          <template v-slot:control>
            <div class="self-center full-width no-outline" tabindex="0">
              {{ appinfo?.name }}
            </div>
            <div class="self-center full-width no-outline" tabindex="0">
              {{ appinfo?.code }}
            </div>
          </template>
        </q-field>
        <q-field  stack-label full-width  label="アプリ説明">
          <template v-slot:control>
            <div class="self-center full-width no-outline" tabindex="0">
              {{ appinfo?.description }}
            </div>
          </template>
        </q-field>
      </q-card-section>
    </q-card>
  </div>
</template>
<script lang="ts" >
import { AppInfo, AppSeed } from './models';
import { ref,  defineComponent, watch, onMounted , toRefs } from 'vue';
import { api } from 'boot/axios';
import { useAuthStore } from 'src/stores/useAuthStore';

export default defineComponent({
  props: {
    app: String
  },
  setup(props) {
    const { app } = toRefs(props);
    const authStore = useAuthStore();
    const appinfo = ref<AppInfo>({
      appId: "",
      name: "",
      description: ""
    });
    const link= ref(`${authStore.currentDomain.kintoneUrl}/k/${app.value}`);
    const getAppInfo = async (appId:string|undefined) => {
      if(!appId){
        return;
      }

      let result : any ={appId:"",name:""};
      let retry =0;
      while(retry<=3 && result && result.appId!==appId){
          await new Promise(resolve => setTimeout(resolve, 1000));
           const response = await api.get('api/v1/app', {
              params:{
                app: appId
              }
          });
          console.log(response.data);
          result = response.data;
          retry++;
      }
      return result;
    }

    watch(app, async (newApp) => {
      appinfo.value = await getAppInfo(newApp);
      link.value = `${authStore.currentDomain.kintoneUrl}/k/${newApp}`;
    }, { immediate: true });

    const linkClick=(ev : MouseEvent)=>{
      ev.stopPropagation();
      return false;
    };
    onMounted(async ()=>{
      appinfo.value = await getAppInfo(app.value);
      link.value = `${authStore.currentDomain.kintoneUrl}/k/${app.value}`;
    });

    return {
      link,
      appinfo,
      linkClick
    }
  }
});
</script>
<style lang="scss">
.app-card {
  max-width: 600px;
  width: 100%;
}
</style>
