<template>
  <div class="tabs">
    <ul>
      <li :class="`${v.code === tab ? 'is-active has-text-weight-bold fs-18' : 'fs-18'}`" v-for="v in tabs">
        <a @click="changeTab(v)">{{ v.name }}</a>
      </li>
    </ul>
  </div>
  <template v-if="tab === 'datatype'">
    <Caption class="mb-3" v-bind="{ title: 'Kiểu dữ liệu (type)', type: 'has-text-warning' }"></Caption>
    <div class="py-1 border-bottom is-clickable" v-for="x in current.fields">
      {{ x.name }}
      <span class="ml-6 has-text-grey">{{ x.type }}</span>
      <a class="ml-6 has-text-primary" v-if="x.model" @click="openModel(x)">{{ x.model }}</a>
    </div>
  </template>
  <template v-else>
    <div class="columns mx-0 mb-0 pb-0">
      <div class="column is-7">
        <Caption class="mb-2" v-bind="{ title: 'Values', type: 'has-text-warning' }"></Caption>
        <input class="input" rows="1" v-model="values" />
      </div>
      <div class="column is-4s">
        <Caption class="mb-2" v-bind="{ title: 'Filter', type: 'has-text-warning' }"></Caption>
        <input class="input" rows="1" v-model="filter" />
      </div>
      <div class="column is-1">
        <Caption class="mb-2" v-bind="{ title: 'Load', type: 'has-text-warning' }"></Caption>
        <div>
          <button class="button is-primary has-text-white" @click="loadData()">Load</button>
        </div>
      </div>
    </div>
    <Caption class="mb-2" v-bind="{ title: 'Query', type: 'has-text-warning' }"></Caption>
    <div class="mb-4">
      {{ query }}
      <a class="has-text-primary ml-5" @click="copy()">copy</a>
      <p>
        {{ apiUrl }}
        <a class="has-text-primary ml-5" @click="$copyToClipboard(apiUrl)">copy</a>
        <a class="has-text-primary ml-5" target="_blank" :href="apiUrl">open</a>
      </p>
    </div>
    <div>
      <Caption class="mb-2" v-bind="{ title: 'Data', type: 'has-text-warning' }"></Caption>
      <DataTable v-bind="{ pagename: pagename }" v-if="pagedata" />
    </div>
  </template>
  <Modal @close="showmodal = undefined" v-bind="showmodal" v-if="showmodal"></Modal>
</template>
<script setup>
import { useStore } from '@/stores/index';
var props = defineProps({
  data: Array,
  info: Object,
});
const { $getdata, $getapi, $createField, $clone, $getpage, $empty, $copyToClipboard, $find, $path } = useNuxtApp();
const store = useStore();
var pagename = 'pagedata99';
var pagedata = ref();
pagedata.value = $getpage();
store.commit(pagename, pagedata);
let list = ['LogEntry', 'Permission', 'ContentType', 'Session', 'Group'];
var current = ref({ fields: [] });
var tabs = [
  { code: 'datatype', name: 'Kiểu dữ liệu' },
  { code: 'table', name: 'Dữ liệu' },
];
var tab = ref('datatype');
var datatable = ref();
var query = ref();
var values, filter;
var apiUrl = ref();
var showmodal = ref();
var data = props.data;
current.value = props.info;
function changeMenu(v) {
  values = undefined;
  filter = undefined;
  current.value = v;
  if (tab.value === 'table') loadData();
}
async function changeTab(v) {
  tab.value = v.code;
  if (v.code === 'table') loadData();
}
async function loadData() {
  let vfilter = filter ? filter.trim() : undefined;
  if (vfilter) {
    try {
      vfilter = JSON.parse(vfilter);
    } catch (error) {
      alert('Cấu trúc filter có lỗi');
      vfilter = undefined;
    }
  }
  let params = { values: values ? values.trim() : undefined, filter: filter };
  let modelName = current.value.model;
  let found = {
    name: modelName.toLowerCase().replace('_', ''),
    url: `data/${modelName}/`,
    url_detail: `data-detail/${modelName}/`,
    params: params,
  };
  query.value = $clone(found);
  let rs = await $getapi([found]);
  if (rs === 'error') return alert('Đã xảy ra lỗi, hãy xem lại câu lệnh.');
  datatable.value = rs[0].data.rows;
  showData();

  // api query
  const baseUrl = $path + `${query.value.url}`;
  apiUrl.value = baseUrl;
  let vparams = !$empty(values) ? { values: values } : null;
  if (!$empty(filter)) {
    vparams = vparams ? { values: values, filter: filter } : { filter: filter };
  }
  if (vparams) {
    let url = new URL(baseUrl);
    let searchParams = new URLSearchParams(vparams);
    url.search = searchParams.toString();
    apiUrl.value = baseUrl + url.search;
  }
}
function showData() {
  let arr = [];
  if (!$empty(values)) {
    let arr1 = values.trim().split(',');
    arr1.map((v) => {
      let val = v.trim();
      let field = $createField(val, val, 'string', true);
      arr.push(field);
    });
  } else {
    current.value.fields.map((v) => {
      let field = $createField(v.name, v.name, 'string', true);
      arr.push(field);
    });
  }
  let clone = $clone(pagedata.value);
  clone.fields = arr;
  clone.data = datatable.value;
  pagedata.value = undefined;
  setTimeout(() => (pagedata.value = clone));
}
function copy() {
  $copyToClipboard(JSON.stringify(query.value));
}
function openModel(x) {
  showmodal.value = {
    component: 'datatable/ModelInfo',
    title: x.model,
    width: '70%',
    height: '600px',
    vbind: { data: data, info: $find(data, { model: x.model }) },
  };
}
</script>
s
