<template>
  <div class="field has-addons is-justify-content-center">
    <!-- <p class="control">
      <button
        class="button is-light is-primary"
        @click="checkFilter() ? false : $emit('modalevent', { name: 'dosort', data: 'az' })"
      >
        <span class="icon">
          <Icon
            name="mdi:sort-alphabetical-ascending"
            :size="22"
            :class="checkFilter() && 'has-text-grey-light'"
          />
        </span>
      </button>
      <span
        class="tooltiptext"
        style="top: 110%; bottom: unset; min-width: max-content; left: 25px"
        >Sắp xếp tăng dần</span
      >
    </p>
    <p class="control">
      <button
        class="button is-light is-primary"
        @click="checkFilter() ? false : $emit('modalevent', { name: 'dosort', data: 'za' })"
      >
        <span class="icon">
          <Icon
            name="mdi:sort-alphabetical-descending"
            :size="22"
            :class="checkFilter() && 'has-text-grey-light'"
          />
        </span>
      </button>
      <span
        class="tooltiptext"
        style="top: 110%; bottom: unset; min-width: max-content; left: 25px"
        >Sắp xếp giảm dần</span
      >
    </p> -->
    <p class="control">
      <button
        class="button"
        @click="moveLeft()"
      >
        <span class="icon">
          <Icon
            name="material-symbols:arrow-back-rounded"
            :size="20"
          />
        </span>
      </button>
      <span
        class="tooltiptext"
        style="top: 110%; bottom: unset; min-width: max-content; left: 25px"
        >Chuyển cột sang trái</span
      >
    </p>
    <p class="control">
      <button
        class="button"
        @click="moveRight()"
      >
        <span class="icon">
          <Icon
            name="material-symbols:arrow-forward-rounded"
            :size="20"
          />
        </span>
      </button>
      <span
        class="tooltiptext"
        style="top: 110%; bottom: unset; min-width: max-content; left: 25px"
        >Chuyển cột sang phải</span
      >
    </p>
    <p class="control">
      <button
        class="button"
        @click="resizeWidth()"
      >
        <span class="icon">
          <Icon
            name="fluent:arrow-fit-16-regular"
            :size="20"
          />
        </span>
      </button>
      <span
        class="tooltiptext"
        style="top: 110%; bottom: unset; min-width: max-content; left: 25px"
        >Tăng độ rộng cột</span
      >
    </p>
    <p class="control">
      <button
        class="button"
        @click="resizeWidth(true)"
      >
        <span class="icon">
          <Icon
            name="fluent:arrow-fit-in-16-regular"
            :size="20"
          />
        </span>
      </button>
      <span
        class="tooltiptext"
        style="top: 110%; bottom: unset; min-width: max-content; left: 25px"
        >Giảm độ rộng cột</span
      >
    </p>
    <p class="control">
      <button
        class="button"
        @click="hideField()"
      >
        <span class="icon">
          <Icon
            name="material-symbols:visibility-off-outline-rounded"
            :size="20"
          />
        </span>
      </button>
      <span
        class="tooltiptext"
        style="top: 110%; bottom: unset; min-width: max-content; left: 25px"
        >Ẩn cột</span
      >
    </p>
    <p class="control">
      <button
        class="button"
        @click="!currentField.mandatory && doRemove()"
      >
        <span class="icon">
          <Icon
            name="material-symbols:delete-outline-rounded"
            :size="20"
          />
        </span>
      </button>
      <span
        class="tooltiptext"
        style="top: 110%; bottom: unset; min-width: max-content; left: 25px"
        >Xóa cột</span
      >
    </p>
    <p class="control">
      <button
        class="button"
        :class="currentField.format !== 'number' && 'has-text-grey-light'"
        @click="currentField.format === 'number' && $emit('modalevent', { name: 'copyfield', data: currentField })"
      >
        <span class="icon">
          <Icon
            name="material-symbols:content-copy-outline-rounded"
            :size="20"
          />
        </span>
      </button>
      <span
        class="tooltiptext"
        style="top: 110%; bottom: unset; min-width: max-content; left: 25px"
        >Sao chép cột</span
      >
    </p>
    <p class="control">
      <button
        class="button"
        @click="fieldList()"
      >
        <span class="icon">
          <Icon
            name="material-symbols:view-column-outline-rounded"
            :size="20"
          />
        </span>
      </button>
      <span
        class="tooltiptext"
        style="top: 110%; bottom: unset; min-width: max-content; left: 25px"
        >Danh sách cột</span
      >
    </p>
    <p class="control">
      <button
        class="button"
        @click="createField()"
      >
        <span class="icon">
          <Icon
            name="material-symbols:add-rounded"
            :size="20"
          />
        </span>
      </button>
      <span
        class="tooltiptext"
        style="top: 110%; bottom: unset; min-width: max-content; left: 25px"
        >Tạo cột mới</span
      >
    </p>
    <p class="control">
      <button
        class="button"
        @click="tableOption()"
      >
        <span class="icon">
          <Icon
            name="material-symbols:table-edit-outline"
            :size="20"
          />
        </span>
      </button>
      <span
        class="tooltiptext"
        style="top: 110%; bottom: unset; min-width: max-content; left: -45px"
        >Tùy chọn bảng</span
      >
    </p>
    <p class="control">
      <button
        class="button is-primary"
        @click="saveSetting()"
      >
        <span class="icon">
          <Icon
            name="material-symbols:save-rounded"
            :size="20"
          />
        </span>
      </button>
      <span
        class="tooltiptext has-background-primary has-text-white"
        style="top: 110%; bottom: unset; min-width: max-content; left: -45px"
        >Lưu thiết lập</span
      >
    </p>
  </div>
  <div class="tabs is-centered">
    <ul>
      <li
        v-for="(v, i) in getMenu().filter((x) =>
          currentField.format === 'number'
            ? currentField.formula
              ? true
              : x.code !== 'formula'
            : !['filter', 'formula'].find((y) => y === x.code),
        )"
        :key="i"
        :class="selectTab.code === v.code ? 'is-active' : 'has-text-primary'"
        @click="changeTab(v)"
      >
        <a class="px-16 py-1.5 fs-14">{{ v.name }}</a>
      </li>
    </ul>
  </div>
  <div v-if="currentTab === 'detail'">
    <p class="field fs-14 is-flex is-gap-0.5 is-align-items-center">
      <span class="font-semibold">Tên trường:</span>
      <span>{{ currentField.name }}</span>
      <button
        class="button is-small size-8 is-primary is-light is-rounded"
        @click="copyContent(currentField.name)"
      >
        <span class="icon">
          <Icon
            name="material-symbols:content-copy-outline-rounded"
            :size="16"
          />
        </span>
      </button>
    </p>
    <div class="field">
      <label class="label fs-14">Mô tả<span class="has-text-danger"> *</span></label>
      <div class="control">
        <div class="field has-addons">
          <div class="control is-expanded">
            <input
              class="input fs-14 h-full"
              type="text"
              @change="changeLabel($event.target.value)"
              v-model="label"
            />
          </div>
          <div class="control">
            <button
              class="button h-full"
              @click="editLabel()"
            >
              <span class="icon">
                <Icon
                  name="material-symbols:edit-outline-rounded"
                  :size="18"
                />
              </span>
            </button>
          </div>
        </div>
      </div>
      <p
        v-if="errors.find((v) => v.name === 'label')"
        class="help is-danger"
      >
        {{ errors.find((v) => v.name === "label").msg }}
      </p>
    </div>
    <div class="field">
      <label class="label fs-14">Kiểu dữ liệu<span class="has-text-danger"> * </span></label>
      <div class="control is-flex is-gap-0.5">
        <button
          v-for="(v, i) in datatype"
          :key="i"
          :class="['button fs-14', radioType === v ? 'is-primary is-light' : 'is-white']"
        >
          <span class="icon">
            <Icon
              :name="
                radioType === v
                  ? 'material-symbols:radio-button-checked-outline'
                  : 'material-symbols:radio-button-unchecked'
              "
              :size="22"
            />
          </span>
          <span>{{ v.name }}</span>
        </button>
      </div>
    </div>
    <div
      v-if="currentField.format === 'number'"
      class="field is-horizontal"
    >
      <div class="field-body">
        <div class="field">
          <label class="label fs-14">Đơn vị <span class="has-text-danger"> * </span> </label>
          <div class="control">
            <SearchBox
              v-bind="{
                vdata: moneyunit,
                field: 'name',
                column: ['name'],
                first: true,
                position: 'is-top-left',
              }"
              @option="selected('_account', $event)"
            />
          </div>
          <p
            class="help has-text-danger"
            v-if="errors.find((v) => v.name === 'unit')"
          >
            {{ errors.find((v) => v.name === "unit").msg }}
          </p>
        </div>
        <div class="field is-narrow">
          <label class="label fs-14">Phần thập phân</label>
          <div class="control">
            <input
              class="input"
              type="text"
              placeholder=""
              v-model="decimal"
              @input="changeDecimal($event.target.value)"
            />
          </div>
        </div>
      </div>
    </div>
    <div class="field">
      <div class="field">
        <label class="label fs-14">Định dạng nâng cao</label>
        <div class="control is-flex is-gap-0.5">
          <button
            v-for="(v, i) in colorchoice.filter((v) => v.code !== 'condition')"
            :key="i"
            @click="changeTemplate(v)"
            :class="['button fs-14', radioTemplate === v.code ? 'is-primary is-light' : 'is-white']"
          >
            <span class="icon">
              <Icon
                :name="
                  radioTemplate === v.code
                    ? 'material-symbols:radio-button-checked-outline'
                    : 'material-symbols:radio-button-unchecked'
                "
                :size="22"
              />
            </span>
            <span>{{ v.name }}</span>
          </button>
          <button
            v-if="radioTemplate === 'option'"
            class="button is-primary is-outlined fs-14 ml-2"
            @click="showSidebar()"
          >
            <span class="icon">
              <Icon
                :name="currentField.template ? 'material-symbols:edit-outline-rounded' : 'material-symbols:add-rounded'"
                :size="17"
              />
            </span>
            <span>{{ currentField.template ? "Sửa" : "Tạo" }} định dạng</span>
          </button>
        </div>
      </div>
    </div>
  </div>
  <div v-else-if="currentTab === 'value'">
    <ScrollBox
      v-bind="{
        data: props.filterData,
        name: props.field.name,
        maxHeight: '380px',
        perpage: 20,
        inContext: true,
      }"
      @selected="doSelect"
    />
  </div>
  <Modal
    v-bind="showmodal"
    v-if="showmodal"
    @label="changeLabel"
    @updatefields="updateFields"
    @close="close"
  />
</template>
<script setup>
import { useStore } from "@/stores/index";
import ScrollBox from "@/components/datatable/ScrollBox.vue";
const store = useStore();
const { $copy, $stripHtml, $clone, $arrayMove, $snackbar, $copyToClipboard } = useNuxtApp();
var props = defineProps({
  pagename: String,
  field: Object,
  filters: Object,
  filterData: Object,
  width: String,
});
const emit = defineEmits(["modalevent", "changepos", "close"]);
var colorchoice = store.colorchoice;
const errors = ref([]);
const currentTab = ref("value");
var currentField = $copy(props.field);
var pagedata = store[props.pagename];
var fields = [];
var label = currentField.label;
const showmodal = ref();
const checkFilter = function () {};
const getMenu = function () {
  let field = currentField;
  field.disable = "display,tooltip";
  let arr = field.disable ? field.disable.split(",") : undefined;
  let array = arr ? store.menuchoice.filter((v) => arr.findIndex((x) => x === v.code) < 0) : store.menuchoice;
  //if (store.login ? !(store.login.is_admin === false) : true) array = [array[0]];
  return array;
};
var selectTab = getMenu()[0];
var datatype = store.datatype;
var current = 1;
var value1 = undefined;
var value2 = undefined;
const moneyunit = store.moneyunit;
const radioType = store.datatype.find((v) => v.code === currentField.format);
var selectUnit = currentField.format === "number" ? moneyunit.find((v) => v.detail === currentField.unit) : undefined;
var bgcolor = undefined;
var radioBGcolor = colorchoice.find((v) => v.code === "none");
var color = undefined;
var radioColor = colorchoice.find((v) => v.code === "none");
var textsize = undefined;
var radioSize = colorchoice.find((v) => v.code === "none");
var minwidth = undefined;
var radioWidth = colorchoice.find((v) => v.code === "none");
var radioMaxWidth = colorchoice.find((v) => v.code === "none");
var maxwidth = undefined;
var selectAlign = undefined;
var radioAlign = colorchoice.find((v) => v.code === "none");
var radioTemplate = ref(colorchoice.find((v) => v.code === (currentField.template ? "option" : "none"))["code"]);
var selectPlacement = store.placement.find((v) => v.code === "is-right");
var selectScheme = store.colorscheme.find((v) => v.code === "is-primary");
var radioTooltip = store.colorchoice.find((v) => v.code === "none");
var selectField = undefined;
var tags = currentField.tags ? currentField.tags.map((v) => fields.find((x) => x.name === v)) : [];
var formula = currentField.formula ? currentField.formula : undefined;
var decimal = currentField.decimal;
let shortmenu = store.menuchoice.filter((x) =>
  currentField.format === "number"
    ? currentField.formula
      ? true
      : x.code !== "formula"
    : !["filter", "formula"].find((y) => y === x.code),
);
var selectTab = shortmenu.find((v) => selectTab.code === v.code)
  ? selectTab
  : menuchoice.find((v) => v.code === "value");
var search = undefined;
// if(selectTab.code==='value') {
//  let self = this
//  setTimeout(function() {self.$refs[currentField.name]? self.$refs[currentField.name].focus() : false}, 50)
// }
//==============================================================
function moveLeft() {
  let copy = $clone(pagedata);
  let i = copy.fields.findIndex((v) => v.name === props.field.name);
  let idx = i - 1 >= 0 ? i - 1 : copy.fields.length - 1;
  $arrayMove(copy.fields, i, idx);
  copy.update = { fields: copy.fields };
  store.commit(props.pagename, copy);
  emit("changepos");
}
function moveRight() {
  let copy = $clone(pagedata);
  let i = copy.fields.findIndex((v) => v.name === props.field.name);
  let idx = copy.fields.length - 1 > i ? i + 1 : 0;
  $arrayMove(copy.fields, i, idx);
  copy.update = { fields: copy.fields };
  store.commit(props.pagename, copy);
  emit("changepos");
}
function hideField() {
  let copy = $clone(store[props.pagename]);
  let found = copy.fields.find((v) => v.name === props.field.name);
  found.show = false;
  copy.update = { fields: copy.fields };
  store.commit(props.pagename, copy);
  emit("close");
}
function doRemove() {
  let copy = $clone(store[props.pagename]);
  let idx = copy.fields.findIndex((v) => v.name === props.field.name);
  copy.fields.splice(idx, 1);
  copy.update = { fields: copy.fields };
  store.commit(props.pagename, copy);
}
function fieldList() {
  showmodal.value = {
    component: "datatable/TableOption",
    vbind: { pagename: props.pagename },
    title: "Danh sách cột",
    width: "50%",
    height: "630px",
  };
}
function tableOption() {
  showmodal.value = {
    component: "datatable/TableSetting",
    vbind: { pagename: props.pagename },
    title: "Tùy chọn bảng",
    width: "50%",
    height: "400px",
  };
}
const getFields = function () {
  fields = pagedata ? $copy(pagedata.fields) : [];
  fields.map((v) => (v.caption = (v.label ? v.label.indexOf("<") >= 0 : false) ? v.name : v.label));
};
const doSelect = function (evt) {
  emit("modalevent", { name: "selected", data: evt[props.field.name] });
};
const changeLabel = function (text) {
  currentField.label = text;
  updateFields(currentField);
};
function editLabel() {
  showmodal.value = {
    component: "datatable/EditLabel",
    title: "Điều chỉnh tiêu đề",
    width: "500px",
    height: "auto",
    vbind: { label },
  };
}
const changeTemplate = function (v) {
  radioTemplate.value = v.code;
  let copy = $copy(currentField);
  copy.template = v.code;
  updateFields(copy);
};
function createField() {
  showmodal.value = {
    component: "datatable/NewField",
    vbind: { pagename: props.pagename },
    title: "Tạo cột mới",
    width: "50%",
    height: "630px",
  };
}
function copyContent(value) {
  $copyToClipboard(value);
}
function close() {
  showmodal.value = undefined;
}
const updateFields = function (field, type) {
  let copy = $clone(store[props.pagename]);
  let idx = copy.fields.findIndex((v) => v.name === field.name);
  copy.fields[idx] = field;
  store.commit(props.pagename, copy);
};
const changeTab = function (v) {
  currentTab.value = v.code;
  selectTab = v;
};
const saveSetting = function () {
  showmodal.value = {
    component: "datatable/MenuSave",
    vbind: { pagename: props.pagename, classify: 4 },
    title: "Lưu thiết lập",
    width: "500px",
    height: "auto",
  };
};
const showSidebar = function () {
  let event = { name: "template", field: currentField };
  let title = "Danh sách cột";
  if (event.name === "bgcolor") title = `Đổi màu nền: ${event.field.name} / ${$stripHtml(event.field.label, 30)}`;
  else if (event.name === "color") title = `Đổi màu chữ: ${event.field.name} / ${$stripHtml(event.field.label, 30)}`;
  else if (event.name === "template") title = `Định dạng nâng cao: ${$stripHtml(event.field.label, 30)}`;
  showmodal.value = {
    component: "datatable/FormatOption",
    vbind: {
      event: event,
      currentField: currentField,
      pagename: props.pagename,
    },
    width: "850px",
    height: "600px",
    title: title,
  };
};
function resizeWidth(minus) {
  let val = maxwidth || minwidth || 80;
  val = minus ? parseInt(val - 0.1 * val) : parseInt(val + 0.1 * val);
  if (val > 1000) return $snackbar("Độ rộng cột lớn hơn giới hạn cho phép");
  else if (val < 20) return $snackbar("Độ rộng cột nhỏ hơn giới hạn cho phép");
  radioMaxWidth = store.colorchoice.find((v) => v.code === "option");
  radioWidth = store.colorchoice.find((v) => v.code === "option");
  maxwidth = val;
  currentField.maxwidth = val;
  minwidth = val;
  currentField.minwidth = val;
  updateFields(currentField);
}
</script>
<style lang="css" scoped>
p.control {
  flex-grow: 1;

  > button {
    width: 100%;
  }
}

.button.is-primary.is-outlined:hover {
  /* TODO: make it global: when outlined, 
  border width shouldn't change, background-color should change */

  --bulma-button-border-width: max(1px, 0.0625em);
  /* same as not-hovered */
  background-color: var(--bulma-primary-95);
}
</style>
