<template>
  <div v-if="['bgcolor', 'color', 'textsize'].find((x) => x === sideBar)">
    <p class="has-text-right has-text-grey is-italic fs-13">
      Màu sắc sẽ hiển thị theo điều kiện Đúng / Sai, mã lệnh do hệ thống tự sinh
    </p>
    <div class="tabs is-boxed">
      <ul>
        <li
          v-for="(v, i) in tabs"
          :key="i"
          :class="tab.code === v.code ? 'is-active' : ''"
          @click="tab = v"
        >
          <a>{{ v.name }}</a>
        </li>
      </ul>
    </div>
  </div>

  <template v-if="tab.code === 'expression' && ['bgcolor', 'color', 'textsize'].find((x) => x === sideBar)">
    <template v-if="radio ? radio.code === 'condition' && sideBar === 'bgcolor' : false">
      <div
        v-for="(v, i) in bgcolorFilter"
        :key="v.id"
        class="px-4"
      >
        <FilterOption
          v-bind="{
            filterObj: v,
            filterType: 'color',
            pagename: pagename,
            field: openField,
          }"
          :ref="v.id"
          @databack="doConditionFilter($event, 'bgcolor', v.id)"
        />
        <p
          class="fs-14 mt-1"
          :class="props.currentField.format === 'string' ? 'mb-1' : 'mb-2'"
        >
          <a
            class="has-text-primary mr-5"
            @click="addCondition(bgcolorFilter)"
            v-if="bgcolorFilter.length <= 30"
          >
            Thêm
          </a>
          <a
            class="has-text-danger"
            @click="removeCondition(bgcolorFilter, i)"
            v-if="bgcolorFilter.length > 1"
          >
            Bớt
          </a>
        </p>
      </div>
    </template>

    <template v-else-if="radio ? radio.code === 'condition' && sideBar === 'color' : false">
      <div
        v-for="(v, i) in colorFilter"
        :key="v.id"
        class="px-4"
      >
        <FilterOption
          v-bind="{
            filterObj: v,
            filterType: 'color',
            pagename: pagename,
            field: openField,
          }"
          :ref="v.id"
          @databack="doConditionFilter($event, 'color', v.id)"
        />
        <p
          class="fs-14 mt-1"
          :class="props.currentField.format === 'string' ? 'mb-1' : 'mb-2'"
        >
          <a
            class="has-text-primary mr-5"
            @click="addCondition(colorFilter)"
            v-if="colorFilter.length <= 30"
          >
            Thêm
          </a>
          <a
            class="has-text-danger"
            @click="removeCondition(colorFilter, i)"
            v-if="colorFilter.length > 1"
          >
            Bớt
          </a>
        </p>
      </div>
    </template>

    <template v-else-if="radio ? radio.code === 'condition' && sideBar === 'textsize' : false">
      <div
        v-for="(v, i) in sizeFilter"
        :key="v.id"
        class="px-4"
      >
        <FilterOption
          v-bind="{
            filterObj: v,
            filterType: 'size',
            pagename: pagename,
            field: openField,
          }"
          :ref="v.id"
          @databack="doConditionFilter($event, 'textsize', v.id)"
        />
        <p
          class="fs-14 mt-1"
          :class="props.currentField.format === 'string' ? 'mb-1' : 'mb-2'"
        >
          <a
            class="has-text-primary mr-5"
            @click="addCondition(sizeFilter)"
            v-if="sizeFilter.length <= 30"
          >
            Thêm
          </a>
          <a
            class="has-text-danger"
            @click="removeCondition(sizeFilter, i)"
            v-if="sizeFilter.length > 1"
          >
            Bớt
          </a>
        </p>
      </div>
    </template>
  </template>

  <template v-else-if="tab.code === 'script' && ['bgcolor', 'color', 'textsize'].find((x) => x === sideBar)">
    <div class="buttons has-addons mb-3">
      <button
        @click="copyContent(script || '')"
        class="button is-primary is-light fs-14"
      >
        <span class="icon">
          <Icon
            name="material-symbols:content-copy-outline-rounded"
            :size="18"
          />
        </span>
        <span>Copy</span>
      </button>
      <button
        @click="paste"
        class="button is-primary is-light fs-14"
      >
        <span class="icon">
          <Icon
            name="material-symbols:content-paste-rounded"
            :size="18"
          />
        </span>
        <span>Paste</span>
      </button>
    </div>
    <textarea
      class="textarea fs-13 is-family-monospace"
      rows="4"
      v-model="script"
      @change="checkScript"
      @dblclick="doCheck"
    ></textarea>
    <p class="mt-5">
      <span class="icon-text">
        <span class="fs-17 font-semibold">Replace</span>
        <span class="icon">
          <Icon
            name="material-symbols:arrow-forward-ios-rounded"
            :size="18"
          />
        </span>
      </span>
    </p>
    <div class="field is-grouped mt-4">
      <div class="control">
        <p class="fsb-14 mb-1">Đoạn text</p>
        <input
          class="input"
          type="text"
          placeholder=""
          v-model="source"
        />
      </div>
      <div class="control">
        <p class="fsb-14 mb-1">Thay bằng</p>
        <input
          class="input"
          type="text"
          v-model="target"
        />
      </div>
      <div class="control">
        <label class="label is-sr-only">Hidden</label>
        <button
          class="button is-primary is-light"
          @click="replace"
        >
          Replace
        </button>
      </div>
    </div>
    <p class="mt-5">
      <span class="icon-text">
        <span class="fs-17 font-semibold">Thay đổi màu</span>
        <span class="icon">
          <Icon
            name="material-symbols:arrow-forward-ios-rounded"
            :size="18"
          />
        </span>
      </span>
    </p>
    <p class="mt-4">
      <button
        class="button is-primary is-rounded"
        @click="changeScript"
      >
        Cập nhật
      </button>
    </p>
  </template>
  <TableOption
    v-else-if="sideBar === 'option'"
    v-bind="{ pagename }"
  />
  <CreateTemplate
    v-else-if="sideBar === 'template'"
    v-bind="{ pagename, field: openField }"
  />
</template>
<script setup>
import CreateTemplate from "~/components/datatable/CreateTemplate";
import FilterOption from "~/components/datatable/FilterOption.vue";
import TableOption from "~/components/datatable/TableOption.vue";
const { $id, $copy, $empty } = useNuxtApp();
const props = defineProps({
  event: Object,
  currentField: Object,
  pagename: String,
});
let openField = {};
let bgcolorFilter = [];
let colorFilter = [];
let sizeFilter = [];
const sideBar = ref();
let script = undefined;
let radio = undefined;
const tabs = [
  { code: "expression", name: "Biểu thức" },
  { code: "script", name: "Mã lệnh" },
];
const tab = ref({ code: "expression", name: "Biểu thức" });
let source = undefined;
let target = $copy(props.currentField.name);

const initData = function () {
  openField = props.event.field;
  sideBar.value = props.event.name;
  script = props.event.script;
  radio = props.event.radio;
  let field = props.event.field;
  bgcolorFilter = [{ id: $id() }];
  if (field.bgcolor) {
    if (Array.isArray(field.bgcolor)) bgcolorFilter = $copy(field.bgcolor);
  }
  colorFilter = [{ id: $id() }];
  if (field.color) {
    if (Array.isArray(field.color)) colorFilter = $copy(field.color);
  }
  sizeFilter = [{ id: $id() }];
  if (field.textsize) {
    if (Array.isArray(field.textsize)) sizeFilter = field.textsize;
  }
};

const doCheck = function () {
  let text = window.getSelection().toString();
  if ($empty(text)) return;
  source = text;
};
const replace = function () {
  if ($empty(script)) return;
  script = script.replaceAll(source, target);
};
const paste = async function () {
  script = await navigator.clipboard.readText();
};
const addCondition = function (arr) {
  arr.push({ id: $id() });
};
const removeCondition = function (arr, i) {
  $delete(arr, i);
};
const copyContent = function (value) {
  $copyToClipboard(value);
};
const checkScript = function () {
  if ($empty(script)) return;
  try {
    JSON.parse(script);
  } catch (e) {
    return false;
  }
  return true;
};
const changeScript = function () {
  if (!checkScript()) return;
  let copy = $copy(openField);
  copy[sideBar.value] = JSON.parse(script);
  $emit("modalevent", { name: "updatefields", data: copy });
};
const doConditionFilter = function (v, type, id) {
  v.id = id;
  let copy = $copy(props.currentField);
  if (copy[type] ? Array.isArray(copy[type]) : false) {
    let idx = copy[type].findIndex((x) => x.id === id);
    idx >= 0 ? (copy[type][idx] = v) : copy[type].push(v);
  } else copy[type] = [v];
  $emit("modalevent", { name: "updatefields", data: copy });
};
initData();
</script>
