/**
 * 筛选条件管理工具
 * 统一管理前端筛选条件，避免v-model绑定问题
 */

import { reactive, watch } from 'vue';

/**
 * 创建筛选条件管理器
 * @param {Object} initialFilters - 初始筛选条件
 * @param {Function} onFilterChange - 筛选条件变化回调
 * @returns {Object} 筛选条件管理器
 */
export const createFilterManager = (initialFilters = {}, onFilterChange = null) => {
  // 创建响应式筛选条件对象
  const filters = reactive({
    // 通用筛选条件
    search: '',
    page: 1,
    limit: 10,
    sortBy: '',
    sortOrder: 'desc',
    dateRange: null,
    status: '',
    
    // 合并初始筛选条件
    ...initialFilters
  });

  // 创建筛选条件更新函数
  const updateFilter = (key, value) => {
    console.log(`更新筛选条件: ${key} = ${value}`);
    filters[key] = value;
    
    // 如果是分页相关，不触发搜索
    if (key === 'page') {
      return;
    }
    
    // 其他筛选条件变化时重置页码
    if (key !== 'page' && key !== 'limit') {
      filters.page = 1;
    }
    
    // 触发筛选条件变化回调
    if (onFilterChange && typeof onFilterChange === 'function') {
      onFilterChange(filters);
    }
  };

  // 批量更新筛选条件
  const updateFilters = (newFilters) => {
    console.log('批量更新筛选条件:', newFilters);
    Object.assign(filters, newFilters);
    
    // 触发筛选条件变化回调
    if (onFilterChange && typeof onFilterChange === 'function') {
      onFilterChange(filters);
    }
  };

  // 重置筛选条件
  const resetFilters = () => {
    console.log('重置筛选条件');
    Object.keys(filters).forEach(key => {
      if (key === 'page') {
        filters[key] = 1;
      } else if (key === 'limit') {
        filters[key] = 10;
      } else {
        filters[key] = initialFilters[key] || '';
      }
    });
    
    // 触发筛选条件变化回调
    if (onFilterChange && typeof onFilterChange === 'function') {
      onFilterChange(filters);
    }
  };

  // 获取查询参数
  const getQueryParams = () => {
    const params = new URLSearchParams();
    
    Object.keys(filters).forEach(key => {
      const value = filters[key];
      if (value !== null && value !== undefined && value !== '') {
        if (Array.isArray(value)) {
          // 处理数组类型的筛选条件
          value.forEach(item => {
            if (item !== null && item !== undefined && item !== '') {
              params.append(key, item);
            }
          });
        } else if (typeof value === 'object' && value !== null) {
          // 处理对象类型的筛选条件（如日期范围）
          if (value.start && value.end) {
            params.append(`${key}Start`, value.start);
            params.append(`${key}End`, value.end);
          }
        } else {
          params.append(key, value);
        }
      }
    });
    
    // 添加时间戳防止缓存
    params.append('_t', Date.now().toString());
    
    return params;
  };

  // 获取URL查询字符串
  const getQueryString = () => {
    return getQueryParams().toString();
  };

  // 从URL参数初始化筛选条件
  const initFromUrl = (urlParams) => {
    console.log('从URL参数初始化筛选条件:', urlParams);
    Object.keys(urlParams).forEach(key => {
      if (filters.hasOwnProperty(key)) {
        filters[key] = urlParams[key];
      }
    });
  };

  // 监听筛选条件变化
  const watchFilters = (callback) => {
    return watch(filters, (newFilters, oldFilters) => {
      console.log('筛选条件变化:', { newFilters, oldFilters });
      if (callback && typeof callback === 'function') {
        callback(newFilters, oldFilters);
      }
    }, { deep: true });
  };

  return {
    filters,
    updateFilter,
    updateFilters,
    resetFilters,
    getQueryParams,
    getQueryString,
    initFromUrl,
    watchFilters
  };
};

/**
 * 防抖筛选条件更新
 * @param {Function} updateFunction - 更新函数
 * @param {number} delay - 延迟时间（毫秒）
 * @returns {Function} 防抖后的更新函数
 */
export const debounceFilter = (updateFunction, delay = 300) => {
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      updateFunction(...args);
    }, delay);
  };
};

/**
 * 节流筛选条件更新
 * @param {Function} updateFunction - 更新函数
 * @param {number} delay - 延迟时间（毫秒）
 * @returns {Function} 节流后的更新函数
 */
export const throttleFilter = (updateFunction, delay = 300) => {
  let lastCall = 0;
  return (...args) => {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      updateFunction(...args);
    }
  };
};

/**
 * 筛选条件预设
 */
export const FILTER_PRESETS = {
  // 日期范围预设
  DATE_RANGES: {
    TODAY: 'today',
    YESTERDAY: 'yesterday',
    LAST_7_DAYS: 'last7days',
    LAST_30_DAYS: 'last30days',
    THIS_MONTH: 'thisMonth',
    LAST_MONTH: 'lastMonth',
    THIS_YEAR: 'thisYear',
    LAST_YEAR: 'lastYear',
    CUSTOM: 'custom'
  },
  
  // 状态预设
  STATUS: {
    ALL: '',
    ACTIVE: 'active',
    INACTIVE: 'inactive',
    PENDING: 'pending',
    COMPLETED: 'completed',
    CANCELLED: 'cancelled'
  },
  
  // 排序预设
  SORT_ORDERS: {
    ASC: 'asc',
    DESC: 'desc'
  }
};

/**
 * 获取日期范围
 * @param {string} preset - 预设类型
 * @returns {Object} 日期范围对象
 */
export const getDateRange = (preset) => {
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  
  switch (preset) {
    case FILTER_PRESETS.DATE_RANGES.TODAY:
      return {
        start: today,
        end: new Date(today.getTime() + 24 * 60 * 60 * 1000 - 1)
      };
    case FILTER_PRESETS.DATE_RANGES.YESTERDAY:
      const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
      return {
        start: yesterday,
        end: new Date(yesterday.getTime() + 24 * 60 * 60 * 1000 - 1)
      };
    case FILTER_PRESETS.DATE_RANGES.LAST_7_DAYS:
      return {
        start: new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000),
        end: new Date(today.getTime() + 24 * 60 * 60 * 1000 - 1)
      };
    case FILTER_PRESETS.DATE_RANGES.LAST_30_DAYS:
      return {
        start: new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000),
        end: new Date(today.getTime() + 24 * 60 * 60 * 1000 - 1)
      };
    case FILTER_PRESETS.DATE_RANGES.THIS_MONTH:
      return {
        start: new Date(now.getFullYear(), now.getMonth(), 1),
        end: new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999)
      };
    case FILTER_PRESETS.DATE_RANGES.LAST_MONTH:
      return {
        start: new Date(now.getFullYear(), now.getMonth() - 1, 1),
        end: new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59, 999)
      };
    case FILTER_PRESETS.DATE_RANGES.THIS_YEAR:
      return {
        start: new Date(now.getFullYear(), 0, 1),
        end: new Date(now.getFullYear(), 11, 31, 23, 59, 59, 999)
      };
    case FILTER_PRESETS.DATE_RANGES.LAST_YEAR:
      return {
        start: new Date(now.getFullYear() - 1, 0, 1),
        end: new Date(now.getFullYear() - 1, 11, 31, 23, 59, 59, 999)
      };
    default:
      return null;
  }
};
