<script>
import Migrating from 'ccxd-ux/src/mixins/migrating';

export default {
  name: 'ElSteps',

  mixins: [Migrating],

  props: {
    space: [Number, String],
    active: Number,
    direction: {
      type: String,
      default: 'horizontal'
    },
    stepWidth: {
      type: String,
      default: '300px'
    },
    alignCenter: {
      type: Boolean,
      default: true
    },
    simple: Boolean,
    finishStatus: {
      type: String,
      default: 'finish'
    },
    processStatus: {
      type: String,
      default: 'process'
    }
  },

  data() {
    return {
      steps: [],
      stepOffset: 0,
      slots: [],
      slotsContent: []
    };
  },
  created() {
    this.$on('step-slot-update', this.calcContentInstances.bind(null, true));
  },
  mounted() {
    this.calcContentInstances();
  },

  methods: {
    getMigratingConfig() {
      return {
        props: {
          'center': 'center is removed.'
        }
      };
    },
    calcContentInstances(isForceUpdate = false) {
      if (this.$slots.default) {
        const stepSlots = this.$slots.default.filter(vnode => vnode.tag &&
          vnode.componentOptions && vnode.componentOptions.Ctor.options.name === 'ElStep');
        // update indeed
        const steps = stepSlots.map((({ componentInstance }) => componentInstance));
        const panesChanged = !(steps.length === this.slots.length && steps.every((pane, index) => pane === this.slots[index]));
        if (isForceUpdate || panesChanged) {
          this.slots = steps;
          this.slotsContent = [];
          this.slots.forEach((Element => {
            if (Element.$slots && Element.$slots.default && Element.$slots.default[0]) {
              this.slotsContent.push(Element.$slots.default[0]);
            } else {
              this.slotsContent.push(null);
            };
          }));
        };
      } else if (this.steps.length !== 0) {
        this.slots = [];
      }
    }
  },

  watch: {
    active(newVal, oldVal) {
      this.$emit('change', newVal, oldVal);
    },

    steps(steps) {
      steps.forEach((child, index) => {
        child.index = index;
      });
    }
  },

  render(h) {
    let {
      simple,
      direction,
      stepWidth
    } = this;

    const step = (
      <div
        class={['el-steps', !simple && 'el-steps--' + direction]}
        style={ stepWidth && direction === 'vertical' ? 'width:' + stepWidth + ';' : '' }
      >
        {this.$slots.default}
      </div>
    );

    const content = (
      <div
        class={this.slotsContent[this.active] ? 'el-steps--content--' + direction : ''}
        style={ 'left:' + stepWidth + ';' }
      >
        { this.slotsContent[this.active] }
      </div>
    );

    return (
      <div style="height:100%;position: relative;">
        { [step, content] }
      </div>
    );
  }
};
</script>
