import { formBaseElement } from "../../../formBaseElement.js";
import useScopedStyleMixin from '../../../useScopedStyleMixin.js';
import EditRowStyles from './EditRowStyles.js';

const EditRow = {
  template: /*html*/`
    <div
      :class="componentClass + hash"
      @click="onClick" 
    >
      <template
        v-for="(element, index) in fields" 
        v-html="{{ listDataString( actualFieldsSource[field][element], rowData[element] ) }}"
      >
        <span 
          v-if="rowData[element]"
          :class="componentClass + '__text' + hash"
          @click="onClick" 
        >
          {{ listDataString( actualFieldsSource[field][element], rowData[element] )}}
        </span>
        <span 
          v-if="isBeetween(index)"
          :class="componentClass + '__split' + hash"
        >/</span>
      </template>
    </div>
  `,
  inject: ["formDataSource"],
  props: {
    data: Object,
    rowData: Object,
    fields: Object,
    index: Number,
  },
  name: 'edit-row',
  mixins: [formBaseElement, useScopedStyleMixin, EditRowStyles],
  computed: {
    isBeetween() {
      return (index) =>
        index < this.fields.length - 1
    },
  },
  data() {
    this.linesFromFields();
    this.blocksFromLines();
    return {
      names: {}, // имена для tables, groups, fields
      activeTable: 0, // id текущей таблицы для fields
      formStatus: "",
      editIndex: 0,
      isArchived: false,
      componentClass: 'edit-row',
    }
  },
  methods: {
    onClick(e) {
      e.preventDefault();
      this.$emit('edit', this.index, e);
    },
    async getNames(optionsFrom) {
      switch(optionsFrom.source) {
        case 'tables':
          if (!this.names.tables) {
            await window.CB.metadata.getDataTables(this.store.isRoot()).then((result) => {
              this.names.tables = result;

            })
          }
          break;

        case 'groups':
          if (!this.names.groups) {
            await window.CB.metadata.getGroups().then((result) => {
              this.names.groups = result;
            })
          }
          break;

        case 'fields':
          if(this.activeTable) {
            await window.CB.metadata.getFields(this.activeTable, 0/*optionsFrom.fieldType*/, this.store.isRoot()).then((result) => {
              if (!this.names.fields) {
                this.names.fields = {}
              }
              this.names.fields[this.activeTable] = result;
            })
          }
          break;

        case 'subtables':
          if(this.activeTable) {
            await window.CB.metadata.getSubtables(this.activeTable, this.store.isRoot()).then((result) => {
              if (!this.names.subtables) {
                this.names.subtables = {}
              }
              this.names.subtables[this.activeTable] = result;
            })
          }
          break;

        case 'filters':
          if(this.activeTable) {
            await window.CB.metadata.getFilters(this.activeTable, this.store.isRoot()).then((result) => {
              if (!this.names.filters) {
                this.names.filters = {}
              }
              this.names.filters[this.activeTable] = result;
            })
          }
          break;
/*
        case 'list':
            if (this.formDataSource[optionsFrom.field]) {

            }
*/            
      }
    },

    //Выдать название options
    listDataString(field, value) {
      let string = ''

      if (field && value) {
        //Проверки для правильной сборки строки
        if (field.optionsFrom) { //Обработка optionsFrom
            if (field.optionsFrom.source === 'fields') {
              this.getNames(field.optionsFrom, value)

              if (this.activeTable && this.names.fields) {
                string = this.names.fields[this.activeTable][value]
              }
            } else if (field.optionsFrom.source === 'tables') {
              this.getNames(field.optionsFrom)
              this.activeTable = value //Записываем текущую таблицу, нужно для fields, subtables, filters

              if(this.names[field.optionsFrom.source]) {
                string = this.names[field.optionsFrom.source][value]
              }

            } else if (field.optionsFrom.source === 'subtables') {
              this.getNames(field.optionsFrom)

              if (this.names.subtables) {
                string = this.names.subtables[this.activeTable][value]
              }
            } else if (field.optionsFrom.source === 'filters') {
              this.getNames(field.optionsFrom)

              if (this.names.filters) {
                string = this.names.filters[this.activeTable][value]
              }
            } else if (field.optionsFrom.source === 'list') {
                let fieldIdent = field.optionsFrom.field;
                if (Array.isArray(this.formDataSource[fieldIdent])) {
                  if (field.optionsFrom.value) {
                    //Если в качестве значения указано использовать поле
                    this.formDataSource[fieldIdent].forEach((item, index) => {
                      if (item[field.optionsFrom.value] == value) {
                          string = item[field.optionsFrom.label];
                      }
                    });                    
                  } else {
                    //Если в качестве значения используется индекс массива
                    string = this.formDataSource[value][field.optionsFrom.label];
                  }
                }
            } else if (field.optionsFrom.source === 'options') {
              let fieldIdent = field.optionsFrom.field;
              let fieldValue = this.formDataSource[fieldIdent];
              if (field.optionsFrom.optionsDir) {
                string = this.store.data['__options'][fieldIdent][fieldValue]['__dir'][field.optionsFrom.optionsDir][value]['name'];
              } else {/*
                if (typeof this.store.data['__options'][fieldIdent][fieldValue] == "string") {
                  string = this.store.data['__options'][fieldIdent][fieldValue];
                } else if ((typeof this.store.data['__options'][fieldIdent][fieldValue] == "object") && this.store.data['__options'][fieldIdent][fieldValue]["__label"]) {
                  */
                  string = this.store.data['__options'][fieldIdent][fieldValue]['name'];
                //}
              }
            } else {
              this.getNames(field.optionsFrom)
              if(this.names[field.optionsFrom.source]) {
                string = this.names[field.optionsFrom.source][value]
              }
            }
        } else if (field.options) { //Вывод простых options
          string = field.options[value];

        } else { //Вывод простой строки
          string = value;
        }
      } else {
        return string
      }

      return string
    }
  },
};

export default EditRow;