// 动物列表页面
const app = getApp();

Page({
  data: {
    animalList: [],
    loading: true,
    refreshing: false,
    hasMore: true,
    cursor: null,
    searchKeyword: '',
    filterFarm: '',
    filterStatus: 'all',
    filterBreed: '',
    farmList: [],
    breedList: [],
    statusOptions: [
      { value: 'all', label: '全部状态' },
      { value: 'healthy', label: '健康' },
      { value: 'sick', label: '患病' },
      { value: 'treatment', label: '治疗中' },
      { value: 'quarantine', label: '隔离' }
    ]
  },

  onLoad(options) {
    // 如果有指定养殖场ID，设置筛选条件
    if (options.farmId) {
      this.setData({ filterFarm: options.farmId });
    }
    
    this.checkLogin();
  },

  onShow() {
    if (app.globalData.userInfo) {
      this.loadInitialData();
    }
  },

  onPullDownRefresh() {
    this.setData({ refreshing: true });
    this.loadAnimalList(true).finally(() => {
      this.setData({ refreshing: false });
      wx.stopPullDownRefresh();
    });
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadAnimalList();
    }
  },

  // 检查登录状态
  checkLogin() {
    if (!app.globalData.userInfo) {
      wx.navigateTo({
        url: '/pages/auth/login'
      });
      return;
    }
    this.loadInitialData();
  },

  // 加载初始数据
  async loadInitialData() {
    try {
      await Promise.all([
        this.loadFarmList(),
        this.loadBreedList(),
        this.loadAnimalList(true)
      ]);
    } catch (error) {
      console.error('加载初始数据失败：', error);
      app.showError('加载失败，请重试');
    }
  },

  // 加载养殖场列表（用于筛选）
  async loadFarmList() {
    try {
      const res = await app.request({
        url: '/farms',
        method: 'GET',
        data: { limit: 100 }
      });
      
      this.setData({
        farmList: res.data.list || []
      });
    } catch (error) {
      console.error('加载养殖场列表失败：', error);
    }
  },

  // 加载品种列表（用于筛选）
  async loadBreedList() {
    try {
      const res = await app.request({
        url: '/animals/breeds',
        method: 'GET'
      });
      
      this.setData({
        breedList: res.data || []
      });
    } catch (error) {
      console.error('加载品种列表失败：', error);
    }
  },

  // 加载动物列表
  async loadAnimalList(refresh = false) {
    if (this.data.loading && !refresh) return;

    try {
      this.setData({ loading: true });

      if (refresh) {
        this.setData({
          animalList: [],
          cursor: null,
          hasMore: true
        });
      }

      const params = {
        limit: 20,
        cursor: this.data.cursor
      };

      // 添加筛选条件
      if (this.data.searchKeyword) {
        params.keyword = this.data.searchKeyword;
      }
      if (this.data.filterFarm) {
        params.farm_id = this.data.filterFarm;
      }
      if (this.data.filterStatus !== 'all') {
        params.health_status = this.data.filterStatus;
      }
      if (this.data.filterBreed) {
        params.breed = this.data.filterBreed;
      }

      const res = await app.request({
        url: '/animals',
        method: 'GET',
        data: params
      });

      const { list, has_more, next_cursor } = res.data;

      this.setData({
        animalList: refresh ? list : [...this.data.animalList, ...list],
        hasMore: has_more,
        cursor: next_cursor
      });

    } catch (error) {
      console.error('加载动物列表失败：', error);
      app.showError('加载失败，请重试');
    } finally {
      this.setData({ loading: false });
    }
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 搜索确认
  onSearchConfirm() {
    this.loadAnimalList(true);
  },

  // 清除搜索
  onSearchClear() {
    this.setData({
      searchKeyword: ''
    });
    this.loadAnimalList(true);
  },

  // 养殖场筛选
  onFarmFilter() {
    const farmOptions = ['全部养殖场', ...this.data.farmList.map(farm => farm.name)];
    
    wx.showActionSheet({
      itemList: farmOptions,
      success: (res) => {
        const selectedFarm = res.tapIndex === 0 ? '' : this.data.farmList[res.tapIndex - 1].id;
        this.setData({
          filterFarm: selectedFarm
        });
        this.loadAnimalList(true);
      }
    });
  },

  // 状态筛选
  onStatusFilter() {
    wx.showActionSheet({
      itemList: this.data.statusOptions.map(item => item.label),
      success: (res) => {
        const selectedStatus = this.data.statusOptions[res.tapIndex];
        this.setData({
          filterStatus: selectedStatus.value
        });
        this.loadAnimalList(true);
      }
    });
  },

  // 品种筛选
  onBreedFilter() {
    const breedOptions = ['全部品种', ...this.data.breedList];
    
    wx.showActionSheet({
      itemList: breedOptions,
      success: (res) => {
        const selectedBreed = res.tapIndex === 0 ? '' : this.data.breedList[res.tapIndex - 1];
        this.setData({
          filterBreed: selectedBreed
        });
        this.loadAnimalList(true);
      }
    });
  },

  // 点击动物项
  onAnimalTap(e) {
    const { animal } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/animal/detail?id=${animal.id}`
    });
  },

  // 编辑动物
  onEditAnimal(e) {
    e.stopPropagation();
    const { animal } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/animal/edit?id=${animal.id}`
    });
  },

  // 删除动物
  onDeleteAnimal(e) {
    e.stopPropagation();
    const { animal } = e.currentTarget.dataset;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除动物"${animal.name}"吗？此操作不可恢复。`,
      confirmText: '删除',
      confirmColor: '#dc3545',
      success: async (res) => {
        if (res.confirm) {
          await this.deleteAnimal(animal.id);
        }
      }
    });
  },

  // 执行删除
  async deleteAnimal(animalId) {
    try {
      app.showLoading('删除中...');
      
      await app.request({
        url: `/animals/${animalId}`,
        method: 'DELETE'
      });
      
      app.showSuccess('删除成功');
      this.loadAnimalList(true);
      
    } catch (error) {
      console.error('删除动物失败：', error);
      app.showError('删除失败，请重试');
    } finally {
      app.hideLoading();
    }
  },

  // 添加动物
  onAddAnimal() {
    wx.navigateTo({
      url: '/pages/animal/add'
    });
  },

  // 健康记录
  onHealthRecord(e) {
    e.stopPropagation();
    const { animal } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/animal/health?id=${animal.id}`
    });
  },

  // 格式化健康状态
  formatHealthStatus(status) {
    const statusMap = {
      'healthy': { text: '健康', class: 'status-success' },
      'sick': { text: '患病', class: 'status-danger' },
      'treatment': { text: '治疗中', class: 'status-warning' },
      'quarantine': { text: '隔离', class: 'status-info' },
      'recovery': { text: '康复中', class: 'status-warning' }
    };
    return statusMap[status] || { text: '未知', class: 'status-info' };
  },

  // 计算年龄
  calculateAge(birthDate) {
    if (!birthDate) return '未知';
    
    const birth = new Date(birthDate);
    const now = new Date();
    const diffTime = Math.abs(now - birth);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays < 30) {
      return `${diffDays}天`;
    } else if (diffDays < 365) {
      const months = Math.floor(diffDays / 30);
      return `${months}个月`;
    } else {
      const years = Math.floor(diffDays / 365);
      const months = Math.floor((diffDays % 365) / 30);
      return months > 0 ? `${years}年${months}个月` : `${years}年`;
    }
  },

  // 格式化体重
  formatWeight(weight) {
    if (!weight) return '未称重';
    return `${weight}kg`;
  }
});