<template>
  <ul
    :class="[
      componentClass,
      {'c-empty': whereFilteredList.length == 0}
    ]"
  >
    <li
      v-for="(item, index) in whereFilteredList"
      :key="index"
      :class="{ 'c-item': true }"
    >
      <div class="c-caption c-lbl">{{ item.label }}</div>
      <div class="c-value c-val">{{ whereFilteredListValue(item) }}</div>
      <div class="c-btn-remove c-btn-del" v-on:click="onClick(item)"></div>
    </li>
    <li
      class="c-btn-removeall c-btn-del-all"
      v-show="whereFilteredList.length > 0"
      v-on:click="onClickRemoveAll()"
    >
      {{ this.removeAllButtonLabel }}
    </li>
  </ul>
</template>

<script>
import base from "./c-base";
import { mapGetters } from 'vuex'

export default {
  extends: base,
  props: {
    items: {
      type: Array,
      default: null,
      required: true
    },
    forceRefreshDependency: {
      type: Boolean,
      default: true
    },
    removeAllButtonLabel: {
      type: String,
      default: "Wyczyść"
    }
  },
  data: function() {
    return {
      componentClass: "c-filter-presenter"
    };
  },
  computed: {
    ...mapGetters('csAppWindowsUtils', [
      'getDataSetWhereFieldsIdentsDataField'
    ]),
    whereFilteredList: function() {
      return this.items.filter(
        item =>
          this.where[item.dataFieldIdent] !== null &&
          this.where[item.dataFieldIdent] !== undefined &&
          this.where[item.dataFieldIdent] !== ""
      );
    }
  },
  methods: {
    onClick: function(item) {
      let payload = {
        sourceKind: "where",
        appWindowIdent: this.appWindowIdent,
        dataSet: this.dataSet,
        dataFieldIdent: item.dataFieldIdent,
        dataFieldValue: null
      };
      this.setDataSetFieldValue(payload);
      let whereField = this.getDataSetWhereFieldsIdentsDataField(this.dataSet, item.dataFieldIdent)
      let isrefreshDependency = whereField ? whereField.refreshDependency === 1 : false
      if (!isrefreshDependency && this.forceRefreshDependency)
        this.refresh()
    },

    onClickRemoveAll: function() {
      this.whereFilteredList.forEach(item => {
        let payload = {
          sourceKind: "where",
          appWindowIdent: this.appWindowIdent,
          dataSet: this.dataSet,
          dataFieldIdent: item.dataFieldIdent,
          dataFieldValue: null,
          refreshLock: 1
        };
        this.setDataSetFieldValue(payload);
      });
      if (this.forceRefreshDependency) this.refresh();
    },

    whereFilteredListValue: function(item) {
      let result
      const formatType = this.getDataSetWhereFieldsIdentsDataField(this.dataSet, item.dataFieldIdent)?.formatType
      let values = item.values;
      if (values) {
        result = values[this.where[item.dataFieldIdent]];
      } else result = this.where[item.dataFieldIdent];
      result = this.formatValue(result, formatType)
      return result
    }
  }
};
</script>