const Animal = require('../../models/Animal');
const AnimalClaim = require('../../models/AnimalClaim');
const { validationResult } = require('express-validator');

/**
 * 管理员动物管理控制器
 * @class AnimalManagementController
 */
class AnimalManagementController {
  /**
   * 获取动物列表
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async getAnimalList(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '参数验证失败',
          errors: errors.array()
        });
      }

      const {
        page = 1,
        limit = 10,
        keyword,
        species,
        status,
        merchant_id,
        start_date,
        end_date,
        sort_by = 'created_at',
        sort_order = 'desc'
      } = req.query;

      const offset = (page - 1) * limit;

      // 构建查询条件
      let whereClause = '';
      const params = [];

      if (keyword) {
        whereClause += ' AND (a.name LIKE ? OR a.description LIKE ?)';
        params.push(`%${keyword}%`, `%${keyword}%`);
      }

      if (species) {
        whereClause += ' AND a.species = ?';
        params.push(species);
      }

      if (status) {
        whereClause += ' AND a.status = ?';
        params.push(status);
      }

      if (merchant_id) {
        whereClause += ' AND a.merchant_id = ?';
        params.push(merchant_id);
      }

      if (start_date) {
        whereClause += ' AND DATE(a.created_at) >= ?';
        params.push(start_date);
      }

      if (end_date) {
        whereClause += ' AND DATE(a.created_at) <= ?';
        params.push(end_date);
      }

      // 获取动物列表
      const animals = await Animal.getAnimalListWithMerchant({
        whereClause,
        params,
        sortBy: sort_by,
        sortOrder: sort_order,
        limit: parseInt(limit),
        offset
      });

      // 获取总数
      const totalCount = await Animal.getAnimalCount({
        whereClause,
        params
      });

      res.json({
        success: true,
        message: '获取成功',
        data: {
          animals,
          pagination: {
            current_page: parseInt(page),
            per_page: parseInt(limit),
            total: totalCount,
            total_pages: Math.ceil(totalCount / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取动物列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取动物列表失败',
        error: error.message
      });
    }
  }

  /**
   * 获取动物详情
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async getAnimalDetail(req, res) {
    try {
      const { animal_id } = req.params;

      // 获取动物详情
      const animal = await Animal.getAnimalDetailWithMerchant(animal_id);
      if (!animal) {
        return res.status(404).json({
          success: false,
          message: '动物不存在'
        });
      }

      // 获取认领统计
      const claimStats = await AnimalClaim.getAnimalClaimStats(animal_id);

      // 获取最近的认领记录
      const recentClaims = await AnimalClaim.getAnimalClaimList(animal_id, {
        limit: 5,
        offset: 0
      });

      res.json({
        success: true,
        message: '获取成功',
        data: {
          animal,
          claimStats,
          recentClaims
        }
      });
    } catch (error) {
      console.error('获取动物详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取动物详情失败',
        error: error.message
      });
    }
  }

  /**
   * 更新动物状态
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async updateAnimalStatus(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '参数验证失败',
          errors: errors.array()
        });
      }

      const { animal_id } = req.params;
      const { status, reason } = req.body;
      const adminId = req.user.id;

      // 检查动物是否存在
      const animal = await Animal.findById(animal_id);
      if (!animal) {
        return res.status(404).json({
          success: false,
          message: '动物不存在'
        });
      }

      // 更新动物状态
      await Animal.updateAnimalStatus(animal_id, status, adminId, reason);

      res.json({
        success: true,
        message: '动物状态更新成功'
      });
    } catch (error) {
      console.error('更新动物状态失败:', error);
      res.status(500).json({
        success: false,
        message: '更新动物状态失败',
        error: error.message
      });
    }
  }

  /**
   * 批量更新动物状态
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async batchUpdateAnimalStatus(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '参数验证失败',
          errors: errors.array()
        });
      }

      const { animal_ids, status, reason } = req.body;
      const adminId = req.user.id;

      // 批量更新动物状态
      const results = await Animal.batchUpdateAnimalStatus(animal_ids, status, adminId, reason);

      res.json({
        success: true,
        message: '批量更新动物状态成功',
        data: {
          updated_count: results.affectedRows
        }
      });
    } catch (error) {
      console.error('批量更新动物状态失败:', error);
      res.status(500).json({
        success: false,
        message: '批量更新动物状态失败',
        error: error.message
      });
    }
  }

  /**
   * 获取动物统计信息
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async getAnimalStatistics(req, res) {
    try {
      // 获取动物总体统计
      const totalStats = await Animal.getAnimalTotalStats();

      // 获取按物种分类的统计
      const speciesStats = await Animal.getAnimalStatsBySpecies();

      // 获取按状态分类的统计
      const statusStats = await Animal.getAnimalStatsByStatus();

      // 获取按商家分类的统计
      const merchantStats = await Animal.getAnimalStatsByMerchant();

      // 获取认领统计
      const claimStats = await AnimalClaim.getClaimTotalStats();

      // 获取月度趋势数据
      const monthlyTrend = await Animal.getAnimalMonthlyTrend();

      res.json({
        success: true,
        message: '获取成功',
        data: {
          totalStats,
          speciesStats,
          statusStats,
          merchantStats,
          claimStats,
          monthlyTrend
        }
      });
    } catch (error) {
      console.error('获取动物统计信息失败:', error);
      res.status(500).json({
        success: false,
        message: '获取动物统计信息失败',
        error: error.message
      });
    }
  }

  /**
   * 导出动物数据
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async exportAnimalData(req, res) {
    try {
      const {
        format = 'csv',
        keyword,
        species,
        status,
        merchant_id,
        start_date,
        end_date
      } = req.query;

      // 构建查询条件
      let whereClause = '';
      const params = [];

      if (keyword) {
        whereClause += ' AND (a.name LIKE ? OR a.description LIKE ?)';
        params.push(`%${keyword}%`, `%${keyword}%`);
      }

      if (species) {
        whereClause += ' AND a.species = ?';
        params.push(species);
      }

      if (status) {
        whereClause += ' AND a.status = ?';
        params.push(status);
      }

      if (merchant_id) {
        whereClause += ' AND a.merchant_id = ?';
        params.push(merchant_id);
      }

      if (start_date) {
        whereClause += ' AND DATE(a.created_at) >= ?';
        params.push(start_date);
      }

      if (end_date) {
        whereClause += ' AND DATE(a.created_at) <= ?';
        params.push(end_date);
      }

      // 获取导出数据
      const animals = await Animal.getAnimalExportData({
        whereClause,
        params
      });

      if (format === 'csv') {
        // 生成CSV格式
        const csvHeader = 'ID,名称,物种,品种,年龄,性别,价格,状态,商家名称,创建时间\n';
        const csvData = animals.map(animal => 
          `${animal.id},"${animal.name}","${animal.species}","${animal.breed || ''}",${animal.age || ''},"${animal.gender || ''}",${animal.price},"${animal.status}","${animal.merchant_name}","${animal.created_at}"`
        ).join('\n');

        res.setHeader('Content-Type', 'text/csv; charset=utf-8');
        res.setHeader('Content-Disposition', `attachment; filename="animals_${Date.now()}.csv"`);
        res.send('\ufeff' + csvHeader + csvData); // 添加BOM以支持中文
      } else {
        // 返回JSON格式
        res.json({
          success: true,
          message: '导出成功',
          data: {
            animals,
            export_time: new Date().toISOString(),
            total_count: animals.length
          }
        });
      }
    } catch (error) {
      console.error('导出动物数据失败:', error);
      res.status(500).json({
        success: false,
        message: '导出动物数据失败',
        error: error.message
      });
    }
  }

  /**
   * 获取动物认领记录
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async getAnimalClaimRecords(req, res) {
    try {
      const { animal_id } = req.params;
      const {
        page = 1,
        limit = 10,
        status
      } = req.query;

      const offset = (page - 1) * limit;

      // 获取认领记录
      const claims = await AnimalClaim.getAnimalClaimList(animal_id, {
        status,
        limit: parseInt(limit),
        offset
      });

      // 获取总数
      const totalCount = await AnimalClaim.getAnimalClaimCount(animal_id, { status });

      res.json({
        success: true,
        message: '获取成功',
        data: {
          claims,
          pagination: {
            current_page: parseInt(page),
            per_page: parseInt(limit),
            total: totalCount,
            total_pages: Math.ceil(totalCount / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取动物认领记录失败:', error);
      res.status(500).json({
        success: false,
        message: '获取动物认领记录失败',
        error: error.message
      });
    }
  }
}

module.exports = AnimalManagementController;