<template>
  <DataTable v-bind="{pagename: pagename}" @updatesetting="updateSetting" v-if="docid"  />
  <div class="mt-6">
    <Caption v-bind="{title: 'Nhập tên trong trường hợp tạo mới'}"></Caption>
    <div>
      <input class="input" type="text" v-model="name">
    </div>
  </div>
  <div class="mt-6">
    <button class="button is-primary has-text-white" @click="save()">Cập nhật</button>
    <button class="button is-dark ml-4" @click="save(true)">Tạo mới</button>
    <button class="button is-dark ml-4" @click="copy()">Copy fields</button>
    <button class="button is-dark ml-4" @click="paste()">Paste fields</button>
    <button class="button is-danger has-text-white ml-4" @click="remove()">Xóa</button>
  </div>
</template>
<script setup>
import DataTable from '~/components/datatable/DataTable'
import { useStore } from '~/stores/index'
const store = useStore()
const { $id, $clone, $updateapi, $insertapi, $findpage, $getpage, $getdata, $setpage, $deleterow, $snackbar, $copyToClipboard } = useNuxtApp()
var props = defineProps({
  setting: Object,
  masterpage: String
})
var api = 'usersetting'
var  pagename = $findpage()
var  name = undefined
var vsetting = undefined
var pagedata = undefined
var docid = ref(null)
async function initData() {
  pagedata = $getpage()
  store.commit(pagename, pagedata)
  vsetting = await $getdata(api, {id: props.setting.id}, null, true)
  pagedata = $setpage(pagename, vsetting)
  docid.value = $id()
}
  async function paste() {
    const text = await navigator.clipboard.readText()
    try {
      let copy = $clone(pagedata)
      copy.fields = JSON.parse(text)
      copy.update = {fields: JSON.parse(text)}
      store.commit(pagename, copy)
    }
    catch(err) {
      $snackbar('Đã xảy lỗi. Hãy thử lại.')
    }
  }
  function copy() {
    $copyToClipboard(JSON.stringify(pagedata.fields))
    $snackbar('Copy thành công')
  }
  function updateSetting(data) {
    let rows = store[masterpage].data
    let idx = $findIndex(rows, {id: data.id})
    rows[idx] = data
    //$store.commit("updateState", {name: masterpage, key: "update", data: {data: rows}})
  }
  async function save(isNew) {
    let detail = pagename? {fields: store[pagename].fields} : {}
    let element = pagedata.tablesetting || tablesetting
    detail.tablesetting = element
    if (pagedata.filters? pagedata.filters.length > 0 : false) {
      detail.filters = pagedata.filters;
    }
    let copy = await $getdata(api, undefined, {filter: {id: props.setting.id}}, true)
    copy.detail = detail
    copy.update_time = new Date()
    if(isNew) {
      copy.id = undefined
      copy.name = name
    }
    isNew? await $insertapi(api, copy, undefined, true) : await $updateapi(api, copy, undefined, true)
  }
  async function remove() {
    await $deleterow(api, props.setting.id, undefined, pagename)
  }
  // main
  initData()
</script>