<template>
  <table class="table">
    <thead>
      <tr class="fs-14">
        <th>#</th>
        <th>Tên trường</th>
        <th>Tên cột</th>
        <th>...</th>
      </tr>
    </thead>
    <tbody>
      <tr class="fs-14" v-for="(v, i) in fields">
        <td>{{ i }}</td>
        <td>
          <a class="has-text-primary" @click="openField(v, i)">{{ v.name }}</a>
        </td>
        <td>{{ $stripHtml(v.label, 50) }}</td>
        <td>
          <a class="mr-4" @click="moveDown(v, i)">
            <SvgIcon v-bind="{ name: 'down1.png', type: 'dark', size: 18 }"></SvgIcon>
          </a>
          <a class="mr-4" @click="moveUp(v, i)">
            <SvgIcon v-bind="{ name: 'up.png', type: 'dark', size: 18 }"></SvgIcon>
          </a>
          <a @click="askConfirm(v, i)">
            <SvgIcon v-bind="{ name: 'bin1.svg', type: 'dark', size: 18 }"></SvgIcon>
          </a>
        </td>
      </tr>
    </tbody>
  </table>
  <Modal @close="showmodal = undefined" @update="update" @confirm="remove" v-bind="showmodal" v-if="showmodal"></Modal>
</template>
<script setup>
import { useStore } from "@/stores/index";
const emit = defineEmits(["close"]);
const { $stripHtml, $clone, $arrayMove, $remove } = useNuxtApp();
const store = useStore();
var props = defineProps({
  pagename: String,
});
var showmodal = ref();
var current;
var pagedata = store[props.pagename];
var fields = ref(pagedata.fields);
function openField(v, i) {
  current = { v: v, i: i };
  showmodal.value = {
    component: "datatable/FieldAttribute",
    title: `${v.name} / ${$stripHtml(v.label)}`,
    width: "50%",
    height: "400px",
    vbind: { field: v },
  };
}
function update(data) {
  fields.value[current.i] = data;
  let copy = $clone(pagedata);
  copy.fields = fields.value;
  copy.update = { fields: fields.value };
  store.commit(props.pagename, copy);
  showmodal.value = undefined;
  emit("close");
}
function updateField() {
  let copy = $clone(pagedata);
  copy.fields = fields.value;
  copy.update = { fields: fields.value };
  store.commit(props.pagename, copy);
}
function moveDown(v, i) {
  let idx = i === fields.value.length - 1 ? 0 : i + 1;
  fields.value = $arrayMove(fields.value, i, idx);
  updateField();
}
function moveUp(v, i) {
  let idx = i === 0 ? fields.value.length - 1 : i - 1;
  fields.value = $arrayMove(fields.value, i, idx);
  updateField();
}
function askConfirm(v, i) {
  current = { v: v, i: i };
  showmodal.value = {
    component: `dialog/Confirm`,
    vbind: { content: "Bạn có muốn xóa cột này không?", duration: 10 },
    title: "Xóa cột",
    width: "500px",
    height: "100px",
  };
}
function remove() {
  let arr = [current.v];
  arr.map((v) => {
    let idx = fields.value.findIndex((x) => x.name === v.name);
    $remove(fields.value, idx);
  });
  updateField();
}
</script>
