<template>
  <div class="mb-4" v-if="currentsetting ? currentsetting.user === login.id : false">
    <p class="fs-16 has-text-findata">
      Đang mở: <b>{{ $stripHtml(currentsetting.name, 40) }}</b>
    </p>
  </div>
  <div class="field">
    <label class="label fs-14">Chọn chế độ lưu <span class="has-text-danger"> * </span></label>
    <div class="control is-expanded fs-14">
      <a class="mr-5" v-if="isOverwrite()" @click="changeType('overwrite')">
        <span class="icon-text">
          <SvgIcon
            v-bind="{
              name: radioSave === 'overwrite' ? 'radio-checked.svg' : 'radio-unchecked.svg',
              type: 'gray',
              size: 22,
            }"
          ></SvgIcon>
          Ghi đè
        </span>
      </a>
      <a @click="changeType('new')">
        <span class="icon-text">
          <SvgIcon
            v-bind="{ name: radioSave === 'new' ? 'radio-checked.svg' : 'radio-unchecked.svg', type: 'gray', size: 22 }"
          ></SvgIcon>
          Tạo mới
        </span>
      </a>
    </div>
  </div>
  <template v-if="radioSave === 'new'">
    <div class="field mt-4 px-0 mx-0">
      <label class="label fs-14">Tên thiết lập <span class="has-text-danger"> * </span></label>
      <div class="control">
        <input class="input" type="text" placeholder="" v-model="name" ref="name" v-on:keyup.enter="saveSetting" />
      </div>
      <div class="help has-text-danger" v-if="errors.find((v) => v.name === 'name')">
        {{ errors.find((v) => v.name === "name").msg }}
      </div>
    </div>
    <div class="field mt-4 px-0 mx-0">
      <label class="label fs-14"> Mô tả </label>
      <p class="control is-expanded">
        <textarea class="textarea" rows="4" v-model="note"></textarea>
      </p>
    </div>
    <!--
      <div class="field mt-4 px-0 mx-0">
        <label class="label fs-14">Loại thiết lập <span class="has-text-danger"> * </span>
        </label>
        <div class="control is-expanded fs-14">
          <span class="mr-4" v-for="(v,i) in $filter(store.settingtype, {code: ['private', 'public']})">
          <a class="icon-text" @click="changeOption(v)">
        <SvgIcon v-bind="{name: `radio-${radioOption===v.code? '' : 'un'}checked.svg`, type: radioOption===v.code? 'primary' : 'gray', size: 22}"></SvgIcon>
        </a>
          {{v.name}}
      </span>
      </div>
    </div>-->
  </template>
  <div class="field mt-5 px-0 mx-0">
    <label class="label fs-14" v-if="status !== undefined" :class="status ? 'has-text-primary' : 'has-text-danger'">
      {{ status ? "Lưu thiết lập thành công." : "Lỗi. Lưu thiết lập thất bại." }}
    </label>
    <p class="control is-expanded">
      <a class="button is-primary has-text-white" @click="saveSetting()">Lưu lại</a>
    </p>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { useStore } from "@/stores/index";
const emit = defineEmits([]);
const store = useStore();
var props = defineProps({
  pagename: String,
  classify: String,
  option: String,
  data: Object,
  focus: Boolean,
});
const { $empty, $copy, $filter, $stripHtml, $updateapi, $insertapi, $findIndex, $snackbar } = useNuxtApp();
var pagename = props.pagename;
var radioOption = ref();
var login = { id: 1 };
var errors = [];
var radioType = undefined;
var radioDefault = 0;
var radioSave = ref("new");
var note = undefined;
var status = undefined;
var name = undefined;
var currentsetting = undefined;
var pagedata = store[props.pagename];
async function saveSetting() {
  errors = [];
  let detail = pagename ? { fields: pagedata.fields } : {};
  if (pagename) {
    let element = pagedata.tablesetting || {};
    if (element !== store.originsetting) detail.tablesetting = element;
    if (pagedata.filters ? pagedata.filters.length > 0 : false) {
      detail.filters = pagedata.filters;
    }
  }
  if (props.option) detail.option = props.option;
  if (props.data) detail.data = props.data;
  let data = {
    user: login.id,
    name: name,
    detail: detail,
    note: note,
    type: radioType.id,
    classify: props.classify ? props.classify : store.settingclass.find((v) => v.code === "data-field").id,
    default: radioDefault,
    update_time: new Date(),
  };
  let result;
  if (radioSave.value === "new") {
    if ($empty(name)) {
      return errors.push({ name: "name", msg: "Tên thiết lập không được bỏ trống" });
    }
    result = await $insertapi("usersetting", data);
  } else {
    let copy = $copy(currentsetting);
    copy.detail = detail;
    copy.update_time = new Date();
    result = await $updateapi("usersetting", copy);
  }
  if (radioSave.value === "new") {
    emit("modalevent", { name: "opensetting", data: result });
  } else {
    let idx = $findIndex(store.settings, { id: result.id });
    if (idx >= 0) {
      let copy = $copy(store.settings);
      copy[idx] = result;
      store.commit("settings", copy);
    }
    $snackbar("Lưu thiết lập thành công");
    emit("modalevent", { name: "updatesetting", data: result });
    emit("close");
  }
}
function isOverwrite() {
  return true;
}
function changeType(value) {
  radioSave.value = value;
}
function changeOption(v) {
  radioOption.value = v.code;
}
function initData() {
  radioType = store.settingtype.find((v) => v.code === "private");
  if (props.pagename) currentsetting = $copy(pagedata.setting ? pagedata.setting : undefined);
  if (!currentsetting) radioSave.value = "new";
  else if (currentsetting.user !== login.id) radioSave.value = "new";
  else radioSave.value = "overwrite";
}
initData();
</script>
