import moment from 'moment';
import { PLATFORM_MODELS, normalizeTimestamp } from './constant';

export default {
  data() {
    return {
      filter: {
        shopId: '',
        platform: '',
        createdAt: null,
        search: '',
      },
      rawData: [],
    };
  },
  methods: {
    onFilterChange() {
      this.pagging.current = 1;
      this.applyFilter();
    },
    onResetFilter() {
      this.filter = {
        shopId: '',
        platform: '',
        createdAt: null,
        search: '',
      };
      this.onFilterChange();
    },
    applyFilter() {
      let data = this.rawData.filter(({ platform }) => {
        if (!this.filter.platform) {
          return true;
        }

        return this.filter.platform === platform;
      });

      data = this.filterDataByShopId(data);
      data = this.filterDataBySearch(data);
      data = this.filterDataByDate(data);

      data.sort((a, b) => {
        const dateA = normalizeTimestamp(a.createdAt) || 0;
        const dateB = normalizeTimestamp(b.createdAt) || 0;
        return dateB - dateA;
      });

      const skip = (this.pagging.current - 1) * this.pagging.limit;

      this.tablePdf.rows = data.slice(skip, skip + this.pagging.limit);
      this.pagging.total = data.length;
    },
    filterDataBySearch(data) {
      if (!this.filter.search) {
        return data;
      }

      const searchLower = this.filter.search.toLowerCase();

      return data.filter((item) => {
        const printId = (item.printId || '').toLowerCase();
        const search = (item.search || '').toLowerCase();
        const text = (item.text || '').toLowerCase();

        return (
          printId.includes(searchLower)
            || search.includes(searchLower)
            || text.includes(searchLower)
        );
      });
    },
    filterDataByShopId(data) {
      if (!this.filter.shopId) {
        return data;
      }

      const shopIdLower = this.filter.shopId.toLowerCase();

      return data.filter((item) => {
        const shopId = (item.shopId || '').toLowerCase();
        return shopId.includes(shopIdLower);
      });
    },
    filterDataByDate(data) {
      if (
        !this.filter.createdAt
          || !Array.isArray(this.filter.createdAt)
          || this.filter.createdAt.length !== 2
      ) {
        return data;
      }

      const startDate = moment(this.filter.createdAt[0]).startOf('day').valueOf();
      const endDate = moment(this.filter.createdAt[1]).endOf('day').valueOf();

      return data.filter((item) => {
        const ts = normalizeTimestamp(item.createdAt);

        if (!ts || ts === 0 || isNaN(ts)) {
          return false;
        }

        return ts >= startDate && ts <= endDate;
      });
    },
    async fetchData() {
      this.query.loading = true;

      try {
        const results = await Promise.all(
          PLATFORM_MODELS.map(async ({ name, model }) => {
            const data = await model.findAll();
            return data
              .filter((item) => item._id && !item._id.startsWith('_design/'))
              .map((item) => ({ ...item, platform: name }));
          }),
        );

        this.rawData = results.flat();
        this.applyFilter();
      } catch (error) {
        this.$Message.error(this.$t('ERROR_GET_DATA'));
        this.loggerApi.error('PDF_LOG_FETCH_ERROR', error);
      } finally {
        this.query.loading = false;
      }
    },
  },
};
