/**
 * 省市区管理API接口系统
 * 支持省市区数据的增删改查、层级管理
 */

class LocationApiService {
  constructor() {
    this.listeners = []; // 数据变化监听器
    this.initLocationData();
  }

  // 初始化省市区数据
  initLocationData() {
    const locations = this.getAllLocations();
    if (locations.length === 0) {
      const sampleLocations = [
        // 省份
        {
          id: 'province_001',
          name: '北京市',
          code: '110000',
          level: 'province',
          parentId: null,
          sort: 1,
          status: 'active',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        },
        {
          id: 'province_002',
          name: '上海市',
          code: '310000',
          level: 'province',
          parentId: null,
          sort: 2,
          status: 'active',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        },
        {
          id: 'province_003',
          name: '广东省',
          code: '440000',
          level: 'province',
          parentId: null,
          sort: 3,
          status: 'active',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        },
        // 城市
        {
          id: 'city_001',
          name: '北京市',
          code: '110100',
          level: 'city',
          parentId: 'province_001',
          sort: 1,
          status: 'active',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        },
        {
          id: 'city_002',
          name: '上海市',
          code: '310100',
          level: 'city',
          parentId: 'province_002',
          sort: 1,
          status: 'active',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        },
        {
          id: 'city_003',
          name: '广州市',
          code: '440100',
          level: 'city',
          parentId: 'province_003',
          sort: 1,
          status: 'active',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        },
        {
          id: 'city_004',
          name: '深圳市',
          code: '440300',
          level: 'city',
          parentId: 'province_003',
          sort: 2,
          status: 'active',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        },
        // 区县
        {
          id: 'district_001',
          name: '朝阳区',
          code: '110105',
          level: 'district',
          parentId: 'city_001',
          sort: 1,
          status: 'active',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        },
        {
          id: 'district_002',
          name: '海淀区',
          code: '110108',
          level: 'district',
          parentId: 'city_001',
          sort: 2,
          status: 'active',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        },
        {
          id: 'district_003',
          name: '东城区',
          code: '110101',
          level: 'district',
          parentId: 'city_001',
          sort: 3,
          status: 'active',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        },
        {
          id: 'district_004',
          name: '黄浦区',
          code: '310101',
          level: 'district',
          parentId: 'city_002',
          sort: 1,
          status: 'active',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        },
        {
          id: 'district_005',
          name: '浦东新区',
          code: '310115',
          level: 'district',
          parentId: 'city_002',
          sort: 2,
          status: 'active',
          createTime: '2024-01-15 10:00:00',
          updateTime: '2024-01-15 10:00:00'
        }
      ];
      this.saveLocations(sampleLocations);
    }
  }

  // 获取所有地区
  getAllLocations() {
    try {
      return wx.getStorageSync('locations') || [];
    } catch (error) {
      console.error('获取地区数据失败:', error);
      return [];
    }
  }

  // 保存地区数据
  saveLocations(locations) {
    try {
      wx.setStorageSync('locations', locations);
      this.notifyListeners(locations);
      return true;
    } catch (error) {
      console.error('保存地区数据失败:', error);
      return false;
    }
  }

  // 根据ID获取地区
  getLocationById(locationId) {
    const locations = this.getAllLocations();
    return locations.find(location => location.id === locationId);
  }

  // 根据层级获取地区
  getLocationsByLevel(level) {
    const locations = this.getAllLocations();
    return locations.filter(location => location.level === level);
  }

  // 根据父级ID获取子地区
  getLocationsByParentId(parentId) {
    const locations = this.getAllLocations();
    return locations.filter(location => location.parentId === parentId);
  }

  // 获取省份列表
  getProvinces() {
    return this.getLocationsByLevel('province');
  }

  // 获取城市列表
  getCities(provinceId = null) {
    if (provinceId) {
      return this.getLocationsByParentId(provinceId);
    }
    return this.getLocationsByLevel('city');
  }

  // 获取区县列表
  getDistricts(cityId = null) {
    if (cityId) {
      return this.getLocationsByParentId(cityId);
    }
    return this.getLocationsByLevel('district');
  }

  // 创建地区
  createLocation(locationData) {
    const locations = this.getAllLocations();
    const newLocation = {
      ...locationData,
      id: this.generateLocationId(locationData.level),
      createTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      status: locationData.status || 'active'
    };
    
    locations.push(newLocation);
    this.saveLocations(locations);
    return newLocation;
  }

  // 更新地区
  updateLocation(locationId, updateData) {
    const locations = this.getAllLocations();
    const locationIndex = locations.findIndex(location => location.id === locationId);
    
    if (locationIndex === -1) {
      throw new Error('地区不存在');
    }

    locations[locationIndex] = {
      ...locations[locationIndex],
      ...updateData,
      updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
    };

    this.saveLocations(locations);
    return locations[locationIndex];
  }

  // 删除地区
  deleteLocation(locationId) {
    const locations = this.getAllLocations();
    
    // 检查是否有子地区
    const children = this.getLocationsByParentId(locationId);
    if (children.length > 0) {
      throw new Error('该地区下还有子地区，无法删除');
    }

    const filteredLocations = locations.filter(location => location.id !== locationId);
    
    if (filteredLocations.length === locations.length) {
      throw new Error('地区不存在');
    }

    this.saveLocations(filteredLocations);
    return true;
  }

  // 搜索地区
  searchLocations(searchParams) {
    const locations = this.getAllLocations();
    let filteredLocations = [...locations];

    // 按名称搜索
    if (searchParams.name) {
      filteredLocations = filteredLocations.filter(location => 
        location.name.includes(searchParams.name)
      );
    }

    // 按层级搜索
    if (searchParams.level) {
      filteredLocations = filteredLocations.filter(location => 
        location.level === searchParams.level
      );
    }

    // 按父级ID搜索
    if (searchParams.parentId) {
      filteredLocations = filteredLocations.filter(location => 
        location.parentId === searchParams.parentId
      );
    }

    // 按状态搜索
    if (searchParams.status) {
      filteredLocations = filteredLocations.filter(location => 
        location.status === searchParams.status
      );
    }

    // 排序
    const sortBy = searchParams.sortBy || 'sort';
    const sortOrder = searchParams.sortOrder || 'asc';
    
    filteredLocations.sort((a, b) => {
      let aValue = a[sortBy];
      let bValue = b[sortBy];
      
      if (sortOrder === 'asc') {
        return aValue > bValue ? 1 : -1;
      } else {
        return aValue < bValue ? 1 : -1;
      }
    });

    return {
      locations: filteredLocations,
      total: filteredLocations.length,
      page: searchParams.page || 1,
      pageSize: searchParams.pageSize || 20
    };
  }

  // 获取地区统计信息
  getLocationStatistics() {
    const locations = this.getAllLocations();
    
    const stats = {
      total: locations.length,
      byLevel: {},
      byStatus: {},
      byParent: {}
    };

    locations.forEach(location => {
      // 按层级统计
      stats.byLevel[location.level] = (stats.byLevel[location.level] || 0) + 1;
      
      // 按状态统计
      stats.byStatus[location.status] = (stats.byStatus[location.status] || 0) + 1;
      
      // 按父级统计
      if (location.parentId) {
        stats.byParent[location.parentId] = (stats.byParent[location.parentId] || 0) + 1;
      }
    });

    return stats;
  }

  // 批量更新地区状态
  batchUpdateLocationStatus(locationIds, status) {
    const locations = this.getAllLocations();
    const updatedLocations = locations.map(location => {
      if (locationIds.includes(location.id)) {
        return {
          ...location,
          status,
          updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
        };
      }
      return location;
    });

    this.saveLocations(updatedLocations);
    return true;
  }

  // 获取地区树形结构
  getLocationTree() {
    const locations = this.getAllLocations();
    const tree = [];
    const locationMap = {};

    // 创建地区映射
    locations.forEach(location => {
      locationMap[location.id] = { ...location, children: [] };
    });

    // 构建树形结构
    locations.forEach(location => {
      if (location.parentId) {
        if (locationMap[location.parentId]) {
          locationMap[location.parentId].children.push(locationMap[location.id]);
        }
      } else {
        tree.push(locationMap[location.id]);
      }
    });

    return tree;
  }

  // 导出地区数据
  exportLocations(searchParams = {}) {
    const result = this.searchLocations(searchParams);
    return {
      locations: result.locations,
      exportTime: new Date().toISOString(),
      total: result.total,
      searchParams
    };
  }

  // 生成地区ID
  generateLocationId(level) {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    const levelPrefix = {
      'province': 'province',
      'city': 'city',
      'district': 'district'
    };
    return `${levelPrefix[level]}_${timestamp}_${random}`;
  }

  // 监听器管理
  addListener(callback) {
    this.listeners.push(callback);
  }

  removeListener(callback) {
    const index = this.listeners.indexOf(callback);
    if (index > -1) {
      this.listeners.splice(index, 1);
    }
  }

  notifyListeners(locations) {
    this.listeners.forEach(callback => {
      try {
        callback(locations);
      } catch (error) {
        console.error('地区数据监听器回调执行失败:', error);
      }
    });
  }

  // 同步地区数据
  syncLocationData() {
    const locations = this.getAllLocations();
    this.notifyListeners(locations);
    return locations;
  }
}

// 创建单例实例
const locationApiService = new LocationApiService();

export default locationApiService;

