<template>
  <div>
    <div
      v-for="(v, i) in lines"
      :key="i"
      :class="i > 0 && 'mt-4'"
    >
      <p class="font-semibold">
        Dòng thứ {{ i + 1 }}
        <span
          v-if="i === 0"
          class="has-text-danger"
        >
          *
        </span>
      </p>
      <div class="field has-addons mt-1">
        <div class="control is-expanded">
          <input
            class="input"
            type="text"
            v-model="v.label"
          />
        </div>
        <div
          class="control"
          @click="remove(i)"
          v-if="i > 0"
        >
          <button class="button is-danger is-light">
            <span class="icon">
              <Icon
                name="material-symbols:delete-outline-rounded"
                :size="20"
              />
            </span>
          </button>
        </div>
        <div class="control">
          <button
            class="button is-success is-light"
            @click="add"
          >
            <span class="icon">
              <Icon
                name="material-symbols:add-rounded"
                :size="20"
              />
            </span>
          </button>
        </div>
      </div>
      <p
        class="help has-text-danger"
        v-if="v.error"
      >
        {{ v.error }}
      </p>
    </div>
    <div class="buttons mt-5">
      <button
        class="button is-primary has-text-white"
        @click="update"
      >
        Cập nhật
      </button>
      <button
        class="button is-white"
        @click="$emit('close')"
      >
        Hủy
      </button>
    </div>
  </div>
</template>
<script>
export default {
  props: ["label"],
  data() {
    return {
      lines: [],
    };
  },
  created() {
    let arr1 = this.label.replace("<div>", "").replace("</div>", "").split("</p>");
    arr1.map((v) => {
      if (!this.$empty(v)) {
        let label = v + "</p>";
        label = this.$stripHtml(label);
        this.lines.push({ label });
      }
    });
  },
  methods: {
    add() {
      this.lines.push({ label: undefined });
    },
    remove(i) {
      this.$remove(this.lines, i);
    },
    checkError() {
      let error = false;
      this.lines.map((v) => {
        if (this.$empty(v.label)) {
          v.error = "Nội dung không được bỏ trống";
          error = true;
        }
      });
      if (error) this.lines = this.$copy(this.lines);
      return error;
    },
    update() {
      if (this.checkError()) return;
      let label = "";
      if (this.lines.length > 1) {
        this.lines.map((v, i) => {
          label += `<p${i < this.lines.length - 1 ? ' style="border-bottom: 1px solid white;"' : ""}>${v.label.trim()}</p>`;
        });
        label = `<div>${label}</div>`;
      } else label = this.lines[0].label.trim();
      this.$emit("modalevent", { name: "label", data: label });
      this.$emit("close");
    },
  },
};
</script>
