<template>
  <div class="q-pa-md">
    <div class="q-gutter-sm row items-start">
        <q-breadcrumbs>
          <q-breadcrumbs-el icon="widgets" label="アプリ" to="/app" />
          <q-breadcrumbs-el>
          <template v-slot>
            <a class="full-width" :href="app?.url" target="_blank" title="Kiontoneへ">
              {{ app?.name }}
              <q-icon
                class="q-ma-xs"
                name="open_in_new"
                color="grey-9"
              />
            </a>
          </template>
        </q-breadcrumbs-el>
      </q-breadcrumbs>
    </div>

    <q-table  :rows="rows" title="バージョン履歴" :columns="columns" :loading="versionLoading" :pagination="pagination" :filter="filter" >
      <template v-slot:top-right>
        <q-input borderless dense filled clearable debounce="300" v-model="filter" placeholder="検索">
          <template v-slot:append>
            <q-icon name="search"/>
          </template>
        </q-input>
      </template>

      <template v-slot:body-cell-id="p">
        <q-td :props="p">
          <div class="">
            <span>{{ p.row.id }}</span>
            <span class="q-ml-md" v-if="p.row.id === app.version">
              <q-badge color="primary">適用中</q-badge>
              <q-badge class="q-ml-xs" v-if="isVersionEditing()" color="orange-7">変更あり</q-badge>
            </span>
          </div>
        </q-td>
      </template>
      <template v-slot:body-cell-comment="p">
        <q-td :props="p">
          <q-scroll-area class="multiline-cell">
            <div v-html="p.row['comment']"></div>
          </q-scroll-area>
        </q-td>
      </template>
      <template v-slot:body-cell-creator="p">
        <q-td auto-width :props="p">
          <q-badge v-if="p.row.creator.id == Number(authStore.userId)" color="purple">自分</q-badge>
          <span v-else>{{ p.row.creator.fullName }}</span>
        </q-td>
      </template>
      <template v-slot:body-cell-actions="p">
        <q-td :props="p">
          <table-action-menu :row="p.row" minWidth="140px" :actions="actionList" />
        </q-td>
      </template>
    </q-table>

    <q-dialog v-model="confirmDialog" persistent>
      <q-card>
        <q-card-section class="q-pb-none">
          <q-list>
            <q-item class="q-px-none">
              <q-item-section avatar class="items-center">
                <q-icon name="warning" color="warning" size="2em" />
              </q-item-section>
              <q-item-section>
                <div>現在のバージョンは未保存です。</div>
                <div>プルすると、上書されますので、よろしいでしょうか？</div>
              </q-item-section>
            </q-item>
          </q-list>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn flat label="キャンセル" color="primary" v-close-popup />
          <q-btn flat label="上書きする" color="primary" :loading="deleteUserLoading" @click="doChangeVersion()" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup lang="ts">
import { useQuasar } from 'quasar';
import { ref, onMounted } from 'vue';
import { useAppStore } from 'stores/useAppStore';
import { useAuthStore } from 'stores/useAuthStore';
import { router } from 'src/router';
import { useRoute } from 'vue-router';
import { IAppDisplay, IAppVersionDisplay } from 'src/types/AppTypes';
import TableActionMenu from 'components/TableActionMenu.vue';

const authStore = useAuthStore();
const appStore = useAppStore();
const route = useRoute()

const $q = useQuasar();

const app = ref<IAppDisplay>({} as IAppDisplay);

const rows = ref<IAppVersionDisplay[]>([]);
const columns = [
      { name: 'id', label: 'バージョン番号', field: 'version', align: 'left', sortable: true },
      { name: 'name', label: 'バージョン名', field: 'name', align: 'left', sortable: true },
      { name: 'comment', label: 'コメント', field: 'comment', align: 'left', sortable: true },
      { name: 'creator', label: '作成者', field: '', align: 'left', sortable: true },
      { name: 'createTime', label: '作成日時', field: 'createTime', align: 'left', sortable: true },
      // { name: 'updater', label: '更新者', field: (row: IVersionDisplay) => row.updater.fullName, align: 'left', sortable: true },
      // { name: 'updateTime', label: '更新日時', field: 'updateTime', align: 'left', sortable: true },
      { name: 'actions', label: '', field: 'actions' }
    ];

const pagination = ref({ sortBy: 'id', descending: true, rowsPerPage: 20 });
const filter = ref('');
const versionLoading = ref(false);

const target = ref<IAppVersionDisplay>();
const confirmDialog = ref(false);
const deleteUserLoading = ref(false);

const actionList =  ref([
  { label: '回復する', icon: 'flag', action: changeVersion },
  // { label: 'プレビュー', icon: 'visibility', action: toVersionHistoryPage },
  // { separator: true },
  // { label: '削除', icon: 'delete_outline', class: 'text-red', action: removeRow },
]);

const getApps = async () => {
  await appStore.loadApps();
}

const getAppById = () => {
  let res = appStore.getAppById(route.params.id as string);
  if (res != null) {
    app.value = res;
    return true;
  }
  return false;
}

const getVersions = async () => {
  versionLoading.value = true;
  rows.value = await appStore.getVersionsByAppId(app.value);
  versionLoading.value = false;
}

function isVersionEditing() {
  return !!app.value.versionChanged;
};

onMounted(async () => {
  versionLoading.value = true;
  let isSuccess = getAppById();
  if (!isSuccess) {
    await getApps();
    isSuccess = getAppById();
    if (!isSuccess) {
      $q.notify({
          icon: 'error',
          color: 'negative',
          message: 'バージョン一覧の読み込みに失敗しました'
        })
      await router.push('/app');
    }
  }
  await getVersions();
});

async function changeVersion(version: IAppVersionDisplay) {
  target.value = version;
  if (!isVersionEditing()) {
    await doChangeVersion(version);
  } else {
    confirmDialog.value = true;
  }
}

async function doChangeVersion(version?: IAppVersionDisplay) {
  if (!version) {
    version = target.value as IAppVersionDisplay;
  }
  confirmDialog.value = false;
  versionLoading.value = true;
  await appStore.changeVersion(app.value, version);
  await getApps();
  getAppById();
  versionLoading.value = false;
}

</script>

<style lang="scss">
.multiline-cell {
  height: 45px;
  min-width: 300px;
  max-height: 45px;
  white-space: break-spaces;

  .q-scrollarea__content {
    display: flex;
    align-items: center;
  }
}
</style>