import {Component, Mixins, Prop, Watch, Vue} from 'vue-property-decorator';
import { Getter, State } from 'vuex-class';
import EventBus from '@/service/eventBus.service';

@Component({ components: {}, name: 'ComponentSelect' })
export default class DynamicForm extends Vue {
  @State(state => state.editor.curEleIndex) curEleIndex;
  @Getter('pageData') pageData;

  @Prop([String, Number]) value;
  @Prop(String) limitName;

  selected: string = this.value;
  list: object[] = [];

  @Watch('selected', { immediate: true })
  onSelectedChange(val) {
    this.$emit('input', val);
  }

  @Watch('curEleIndex', { immediate: true })
  onCurEleIndexChange(val) {
    this.updateOptions(val);
  }

  mounted() {
    EventBus.$on('component-moved', () => {
      this.updateOptions();
    });
  }

  updateOptions(val = this.curEleIndex) {
    if (val || val === 0) {
      const pointY = this.pageData?.elements[val]?.point?.y;
      let list = [];
      if (this.limitName) {
        list = this.pageData?.elements?.filter(v => pointY < v?.point?.y && v?.name === this.limitName);
      } else {
        list = this.pageData?.elements?.filter(v => pointY < v?.point?.y);
      }
      list = list.sort((cur, next) => {
        return cur.point.y > next.point.y ? 1 : -1;
      });
      this.list = list.map((element, index) => ({ id: element.id, label: element.title + '-' + element.id}));
      if (!this.list.some(item => item.id === this.selected)) {
        this.selected = '';
      }
      // console.log('curEleIndex', pointY, this.pageData?.elements?.filter(v => pointY < v?.point?.y), this.list);
    }
  }
}
