import { Namespace } from "../../utils/namespace";
import Icon from '../icon/icon.jsx';

const namespace = Namespace.Create('collapse-item');

export default {
  name: namespace.name,
  components: {
    Icon,
  },
  props: {
    title: {
      type: String
    },
    name: {
      type: [String, Number],
      default: ''
    },
    value: {
      type: Number,
      default: 0
    },
  },
  data () {
    return {
      height: ''
    }
  },
  computed: {
    cls () {
      return namespace.derive({
        active: this.isActive,
      })
    },
    headerCls () {
      return namespace.derive('header')
    },
    headerTitleCls () {
      return namespace.derive('header-title')
    },
    contentCls () {
      return namespace.derive('content')
    },
    iconCls(){
      return namespace.derive('icon',{
        active: this.isActive
      })
    },
    contentStyle () {
      const style = {}
      if (this.isActive) {
        style.height = `${this.height}px`
      } else {
        style.height = `0px`
      }
      return style;
    },
    key(){
      return this.name || this.$parent.$children.indexOf(this).toString()
    },
    isActive () {
      const { innerValue } = this.$parent.$data
      return this.$parent.accordion ? 
              innerValue === this.key 
              : innerValue?.findIndex(x=>x === this.key) != -1 
    },
  },
  mounted () {
    this.height = this.$refs.collapseItemContentRef.offsetHeight
  },
  methods: {
    handleItemClick () {
      this.$parent.handleItemClick(this.key)
    },
  },
  render () {
    const renderHeader = () => (
      <div class={this.headerCls} onClick={this.handleItemClick}>
        {renderTitle()}
        <Icon class={this.iconCls} name="arrow-down" size={10} />
      </div>
    )

    const renderTitle = () => {
      if (this.$slots.title) {
        return this.$slots.title
      }
      return (
        <div class={this.headerTitleCls}>
          {this.title}
        </div>
      )
    }

    const renderContent = () => (
      <div class={this.contentCls} style={this.contentStyle}>
        <div ref="collapseItemContentRef">
          {this.$slots.default}
        </div>
      </div>
    )

    return (
      <div class={this.cls}>
        {renderHeader()}
        {renderContent()}
      </div >
    )
  }
}