import {Component, Prop, Watch, Vue, Mixins, Emit} from 'vue-property-decorator';
import { Getter, State } from 'vuex-class';
import { cloneDeep, uniqBy } from 'lodash';
import Number from '../Number/index.vue';
import QGTable from '@editor/component/QgTable/index.vue';
import { validateType } from '@/service/utils.service';
import operationApi from '@api/operation.api';
import DynamicFormMixin from '../mixins/dynamicForm.mixin';

@Component({ components: { Number, QGTable }, name: 'ComponentSelect' })
export default class DynamicForm extends Mixins(DynamicFormMixin) {
  @State(state => state.editor.curEleIndex) curEleIndex;
  @Getter('pageData') pageData;
  @Prop({ default: () => ([]), type: Array }) formControl;
  @Prop({ default: () => ([]), type: Array }) table;
  @Prop([Object, Array]) value;
  @Prop(String) title;
  @Prop([Object, Array]) templates;

  form: object = {};
  modal: boolean = false;
  selections: object[] = [];
  activeName: number = 0;
  isSelected: boolean = false;

  get idsLength() {
    return this.getLength('value');
  }

  getTableData() {
    const tableData = this.$refs?.[`qgTable${this.activeName}`]?.[0]?.tableData || [];
    console.log('get tableData', tableData);
    return this.isSelected ? tableData : [];
  }

  changePageNo() {
    this.isSelected = false;
  }

  // 获取除本页之外的默认值
  getDefaultIds() {
    const tableData = this.getTableData();
    let defaultIds = this.value;
    if (validateType(this.value) === 'object') {
      defaultIds = this.value.type === this.table[this.activeName].type ? this.value?.ids : [];
    }

    let filterIds = [];
    if (this.table.length > 1) {
      filterIds = tableData.map(v => v[this.table[this.activeName].key]);
    } else {
      filterIds = tableData.map(v => v.id);
    }

    const rs = this.isSelected ? defaultIds.filter(v => !filterIds.includes(v)) : defaultIds;
    return rs;
  }

  // 获取本页的选中值
  getSelectionsIds() {
    if (this.table.length > 1) {
      return this.selections.map(v => v[this.table[this.activeName].key]);
    } else {
      return this.selections.map(v => v.id);
    }
  }

  // 获取本页之外的临时值
  getTemplateIds() {
    let filterIds = [];
    let templates = [];
    const tableData = this.getTableData();
    if (this.table.length > 1) {
      filterIds = tableData.map(v => v[this.table[this.activeName].key]);
      templates = this.templates.ids;
    } else {
      filterIds = tableData.map(v => v.id);
      templates = this.templates;
    }

    const rs = this.isSelected ? templates.filter(v => !filterIds.includes(v)) : templates;
    return rs;
  }

  getLength(type) {
    const rs = type === 'templates' ? this.templates : this.value;
    if (validateType(this.templates) === 'object') {
      return rs?.ids?.length;
    }
    return rs?.length;
  }

  // 当table取消全选时的默认值
  getDefaultSelections() {
    let rs = [];
    if (this.table.length > 1) {
      const key = this.table[this.activeName].key;
      rs = [{ [key]: -1 }];
    } else {
      rs = [{ id: -1 }];
    }
    return rs;
  }

  setTemplates(ids = []) {
    let rs = null;
    if (this.table.length > 1) {
      rs = {
        type: this.table[this.activeName].type,
        ids
      };
    } else {
      rs = ids;
    }

    return rs;
  }

  @Watch('curEleIndex', { immediate: true })
  onElementChange(newVal) {
    this.formControl.forEach(schame => {
      this.$set(this.form, schame.key, this.pageData.elements[this.curEleIndex].props[schame.key]);
    });
  }

  @Watch('form', { immediate: true, deep: true })
  onFormChange(newVal) {
    let parent = this.$parent;
    while (!parent.modProps) {
      parent = parent.$parent;
    }
    parent.modProps(this.form, 'component');
  }

  @Watch('value', { immediate: true })
  onValueChange(newVal) {
    if (newVal && this.table.length > 1) {
      this.activeName = this.table.findIndex(v => v.type === newVal.type);
    }
  }

  @Emit('update:templates')
  selectionChange(selection) {
    if (!this.table[this.activeName]?.multiple && selection.length > 1) {
      this.$Notice.warning({
        title: '商品组只能单选'
      });
      return this.templates;
    }
    this.isSelected = true;
    this.selections = selection.length ? selection : this.getDefaultSelections();
    const ids = Array.from(new Set([...this.getSelectionsIds(), ...(this.getLength('templates') ? this.getTemplateIds() : this.getDefaultIds())]));

    console.log('selectionChange', ids, selection);

    const rs = this.setTemplates(ids);
    return rs;
  }

  add() {
    this.modal = true;
  }

  ok() {
    let ids = [...this.getSelectionsIds(), ...(this.getLength('templates') ? this.getTemplateIds() : this.getDefaultIds())];
    // ids为空时表示未选择
    if (!ids.length) { return; }
    // 当前页selections为空
    ids = ids.filter(v => v !== -1);
    this.selections = [];
    this.isSelected = false;
    // console.log('commit', selections);
    if (this.table.length > 1) {
      this.$emit('update:templates', {});
      this.$emit('input', {
        type: this.table[this.activeName].type,
        ids: Array.from(new Set(ids))
      });
    } else {
      this.$emit('update:templates', this.setTemplates());
      this.$emit('input', Array.from(new Set(ids)));
    }
  }

  @Emit('update:templates')
  cancel() {
    this.selections = [];
    this.isSelected = false;

    let rs = null;
    if (this.table.length > 1) {
      rs = {};
    } else {
      rs = [];
    }
    return rs;
  }

  async menuChange(name) {
    // console.log('menuChange', `qgTable${name}`, this.$refs);
    await this.$refs[`qgTable${name}`][0].query();
    this.activeName = name;
    this.$emit('update:templates', this.setTemplates());
    this.selections = [];
  }

  editText(type) {
    let rs = '';
    switch (type) {
    case 'edit':
      rs = `编辑${this.title}`;
      break;
    case 'add':
      rs = `添加${this.title}`;
      break;
    case 'choose':
      rs = `选择${this.title}`;
      break;
    }
    return rs;
  }
}