<template>
  <div class="panel" :class="panelStatus">
    <!-- Panel Header -->
    <div
      class="panel-heading"
      :class="{
        collapsed: !isOpen && !isStatic,
        active: isOpen,
        static: isStatic,
      }"
      :data-toggle="hasBodySlot && !isStatic ? 'collapse' : false"
      :data-parent="'#' + parent_id"
      :data-target="'#' + id"
      @click="onClick"
    >
      <h4 class="panel-title">{{ title }}</h4>
      <div class="panel-subtitle">{{ sub_title }}</div>
      <!-- items -->
      <dl
        v-if="
          items &&
          Object.keys(items).length > 0 &&
          items_orientation === 'horizontal'
        "
        class="dl-inline"
      >
        <fragment v-for="(v, k) in items" :key="k">
          <dt>{{ k }}</dt>
          <dd>{{ v }}</dd>
        </fragment>
      </dl>
      <slot v-else name="items"></slot>
    </div>
    <!-- Panel Collapsible -->
    <div
      v-if="hasBodySlot && !isStatic"
      :id="id"
      class="panel-collapse collapse"
      :class="{
        in: isOpen,
      }"
    >
      <!-- Panel Body -->
      <div class="panel-body">
        <slot name="body"></slot>
      </div>
    </div>
    <div v-else-if="hasBodySlot && isStatic" class="panel-body">
      <slot name="body"></slot>
    </div>
    <!-- Panel Footer -->
    <div v-if="hasFooterSlot" class="panel-footer">
      <!-- <div class="btn-link-toolbar pull-left"></div> -->
      <slot name="footer"></slot>
    </div>
  </div>
</template>

<script>
import { str2bool } from "../../util";
export default {
  name: "bc-panel",
  props: {
    id: {
      type: String,
      default: null,
    },
    parent_id: {
      type: String,
      default: "",
    },
    items: {
      type: Object,
      default() {
        return {};
      },
    },
    items_orientation: {
      type: String,
      default: "horizontal",
    },
    status: {
      type: String,
      default: null,
    },
    title: {
      type: String,
      default: null,
    },
    sub_title: {
      type: String,
      default: null,
    },
    is_static: {
      type: [Boolean, String],
      default: false,
    },
  },
  data() {
    return {
      isOpen: false,
      state: "closed",
      onceOpen: false,
    };
  },
  mounted() {
    this.$nextTick(function () {
      this.$parent.$emit("mounted", this.id);
    });
  },
  computed: {
    panelStatus() {
      if (this.status) {
        return `panel-${this.status}`;
      }
      return "";
    },
    hasBodySlot() {
      return !!this.$slots.body;
    },
    hasFooterSlot() {
      return !!this.$slots.footer;
    },
    isStatic() {
      // if there is not body slot then by default static is true
      if (!this.hasBodySlot) {
        return true;
      }
      return str2bool(this.is_static, false);
    },
  },
  methods: {
    onClick() {
      if (this.onceOpen) {
        this.isOpen = !this.isOpen;
      } else {
        this.onceOpen = true;
      }
    },
  },
};
</script>