FilterBar.js 10.5 KB
// components/FilterBar/FilterBar.js
const IMG_URL =
  "https://img02.glsx.com.cn/weapp/resource/miniprogram/regional-assistant/";
const date = new Date();
const years = [];
const months = [];

for (let i = 2020; i <= date.getFullYear() + 5; i++) {
  years.push(i);
}

for (let i = 1; i <= 12; i++) {
  months.push(i);
}

Component({
  properties: {
    height: {
      type: String,
      value: "40%",
    },
    searchPlaceholder: {
      type: String,
      value: "门店名称",
    },
    searchObj: {
      type: Object,
      value: {},
    },
    searchKey: {
      type: String,
      value: "keyword",
    },
    // Array of filter objects: { type: 'month'|'select'|'date-range', label: 'Label', key: 'key', optionList: [], value: '', startKey: '', endKey: '' }
    filters: {
      type: Array,
      value: [],
    },
  },

  data: {
    IMG_URL,
    years: years,
    months: months,
    searchValue: "",
    formData: {},
    // Popup State
    showPopup: false,
    activeFilterIndex: -1, // Index of the filter currently being edited

    // Temp Values for Popups
    tempDateIndex: [years.indexOf(date.getFullYear()), date.getMonth()],
    tempDateValue: new Date().getTime(),
    pickerViewValue: new Date().getTime(),
    minDate: new Date(2020, 0, 1).getTime(),
    maxDate: new Date(new Date().getFullYear() + 5, 11, 31).getTime(),
    maxDateForCalendar: (function () {
      const d = new Date();
      const y = d.getFullYear();
      const m = (d.getMonth() + 1).toString().padStart(2, "0");
      const day = d.getDate().toString().padStart(2, "0");
      return `${y}-${m}-${day}`;
    })(),
    tempSelectIndex: 0,
  },

  methods: {
    // Search Handlers
    onSearch(e) {
      if (e.detail && e.detail.value !== undefined) {
        this.setData({ searchValue: e.detail.value });
      }
      this.triggerEvent("filterChange", this.getFilterData());
    },
    onSearchInput(e) {
      this.setData({ searchValue: e.detail.value });
    },
    clearSearch() {
      this.setData({ searchValue: "" });
      this.triggerEvent("filterChange", this.getFilterData());
    },

    // Filter Tag Click Handler
    onFilterTagTap(e) {
      const index = e.currentTarget.dataset.index;
      const filter = this.properties.filters[index];
      // const currentValue = this.data.formData[filter.key];

      let minDate = new Date(2020, 0, 1).getTime();
      let maxDate = new Date(new Date().getFullYear() + 5, 11, 31).getTime();

      if (filter.minDate) {
        let str = filter.minDate;
        if (/^\d{4}-\d{2}$/.test(str)) str += "-01";
        const d = new Date(str.replace(/-/g, "/"));
        if (!isNaN(d.getTime())) minDate = d.getTime();
      }

      if (filter.maxDate) {
        let str = filter.maxDate;
        if (/^\d{4}-\d{2}$/.test(str)) str += "-01";
        const d = new Date(str.replace(/-/g, "/"));
        if (!isNaN(d.getTime())) maxDate = d.getTime();
      }

      this.setData({
        activeFilterIndex: index,
        showPopup: true,
        formData: this.data.searchObj,
        minDate,
        maxDate
      });
      const currentValue = this.data.searchObj[filter.key]
      if (filter.type === "month") {
        this.initDatePicker(currentValue, filter.pickerType);
      } else if (filter.type === "select") {
        console.log('99999')
        this.initSelectPicker(currentValue);
      }
    },

    // Popup Logic
    closePopup() {
      this.setData({ showPopup: false, activeFilterIndex: -1 });
    },

    confirmPopup() {
      const index = this.data.activeFilterIndex;
      if (index === -1) return;

      const filter = this.properties.filters[index];
      let newValue = "";

      if (filter.type === "month") {
        newValue = this.getDateFromPicker(filter.pickerType);
      } else if (filter.type === "select") {
        newValue = this.data.formData[filter.key];
      }

      // Update the specific filter's value
      const key = `formData.${filter.key}`;

      this.setData({
        [key]: newValue,
        showPopup: false,
        activeFilterIndex: -1,
      });

      this.triggerEvent("filterChange", this.getFilterData());
    },

    // Date Range Logic
    onDateRangeSelect(e) {
      const index = e.currentTarget.dataset.index;
      const filter = this.properties.filters[index];
      const { start, end } = e.detail.date;

      if (!start || !end) return;

      const displayValue = `${start} 至 ${end}`;
      const updates = {};

      // Update formData with the display string for the main key (for display in FilterBar)
      this.updateForm(filter, displayValue, displayValue, updates);

      // Update startKey and endKey if configured
      if (filter.startKey) {
        updates[`formData.${filter.startKey}`] = start + ' 00:00:00';
      }
      if (filter.endKey) {
        updates[`formData.${filter.endKey}`] = end + ' 23:59:59';
      }

      this.setData(updates);
      this.triggerEvent("filterChange", this.getFilterData());
    },

    // Date Logic
    initDatePicker(currentValue, pickerType = "year-month") {
      let val = new Date().getTime();
      if (pickerType === "time") {
        val = currentValue || "00:00";
      } else {
        if (currentValue) {
          let str = currentValue;
          // Handle YYYY-MM for year-month type
          if (pickerType === "year-month" && /^\d{4}-\d{2}$/.test(str)) {
            str += "-01";
          }
          val = new Date(str.replace(/-/g, "/")).getTime();
          if (isNaN(val)) val = new Date().getTime();
        }
      }
      this.setData({ tempDateValue: val, pickerViewValue: val });
    },
    onDatePickChange(e) {
      this.setData({ tempDateValue: e.detail });
    },
    getDateFromPicker(pickerType = "year-month") {
      const val = this.data.tempDateValue;
      if (pickerType === "time") return val;

      const date = new Date(val);
      const y = date.getFullYear();
      const m = (date.getMonth() + 1).toString().padStart(2, "0");
      const d = date.getDate().toString().padStart(2, "0");

      if (pickerType === "date") return `${y}-${m}-${d}`;
      if (pickerType === "year-month") return `${y}-${m}`;
      return `${y}-${m}-${d}`; // default fallback
    },

    // Select Logic
    getSelectOptions(filter) {
      let optionList = filter.optionList || [];
      if (!filter.hideAllOption) {
        optionList = [{ confId: "", confLabel: "全部" }, ...optionList];
      }
      return optionList;
    },

    initSelectPicker(currentValue) {
      const filter = this.properties.filters[this.data.activeFilterIndex];
      const optionList = this.getSelectOptions(filter);
      let index = 0;

      if (currentValue) {
        index = optionList.findIndex((item) => item.confId == currentValue);
        if (index == -1) index = 0;
      } else {
        // If currentValue is empty, it might mean "All" is selected (if available) or no selection.
        // If "All" option exists (confId: ''), index should be 0.
        // If no "All" option, but optionList exist, default to first.
        index = 0;
      }

      // Default to first option if empty and not "All" (which is also empty string but valid)
      // Actually, if we have "All" option, confId is '', so formData is empty string, which is fine.
      // If we don't have "All" option, and currentValue is empty, we might want to default to first option.
      if (!currentValue && optionList.length > 0) {
        // If it's effectively "All" or unselected, we sync it.
        const firstOption = optionList[0];
        const updateData = {};
        this.updateForm(
          filter,
          firstOption.confId,
          firstOption.confLabel,
          updateData,
        );
        this.setData(updateData);
      }

      console.log(index, "index---");
      this.setData({
        currentSelectOptions: optionList, // Store current optionList to use in wxml or change handler
      }, () => {
        this.setData({
          tempSelectIndex: index
        })
      });
    },

    onSelectPickerChange(e) {
      const { index } = e.detail;
      // We need to use the same optionList list as displayed
      const filter = this.properties.filters[this.data.activeFilterIndex];
      const optionList =
        this.data.currentSelectOptions || this.getSelectOptions(filter);
      const value = optionList[index];

      const updateData = {
        tempSelectIndex: index,
      };

      // Update showKey if present
      this.updateForm(
        filter,
        value ? value.confId : "",
        value ? value.confLabel : "",
        updateData,
      );

      this.setData(updateData);
    },

    /**
     * Updates form data with value and optional display label
     * @param {Object} filter - Filter configuration object
     * @param {String|Number} keyVal - The value to set for the filter key
     * @param {String} showKeyVal - The label to set for the showKey (if configured)
     * @param {Object} targetObj - The object to mutate with updates
     */
    updateForm(filter, keyVal, showKeyVal, targetObj) {
      Object.assign(targetObj, {
        [`formData.${filter.key}`]: keyVal,
        ...(filter.showKey && { [`formData.${filter.showKey}`]: showKeyVal }),
      });
    },

    // Reset
    resetFilters() {
      // Reset search
      this.setData({ searchValue: "" });

      // Reset all filters
      const updates = {};
      this.properties.filters.forEach((f) => {
        this.updateForm(f, "", "", updates);
        if (f.startKey) updates[`formData.${f.startKey}`] = "";
        if (f.endKey) updates[`formData.${f.endKey}`] = "";
      });
      this.setData(updates);

      this.triggerEvent("filterChange", this.getFilterData());
    },

    // Helper
    getFilterData() {
      const result = {
        [this.properties.searchKey]: this.data.searchValue,
      };

      this.properties.filters.forEach((f) => {
        let keyVal = this.data.formData[f.key] || "";
        let showKeyVal = f.showKey ? this.data.formData[f.showKey] || "" : "";

        // 如果当前选中的confId为空并且confLabel为全部,则传‘’
        // If the value is empty and the label is "全部", treat label as empty string for output
        if (keyVal == "" && showKeyVal == "全部") {
          showKeyVal = "";
        }

        result[f.key] = keyVal;
        if (f.showKey) {
          result[f.showKey] = showKeyVal;
        }

        // Add startKey and endKey if they exist
        if (f.startKey) {
          result[f.startKey] = this.data.formData[f.startKey] || "";
        }
        if (f.endKey) {
          result[f.endKey] = this.data.formData[f.endKey] || "";
        }
      });

      return result;
    },
  },
});