const AnimalClaimService = require('../services/animalClaim');
const { validateRequired, validatePositiveInteger } = require('../utils/validation');

class AnimalClaimController {
  /**
   * 申请认领动物
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async createClaim(req, res) {
    try {
      const { animal_id, claim_reason, claim_duration, contact_info } = req.body;
      const user_id = req.user.id;

      // 参数验证
      if (!validateRequired(animal_id) || !validatePositiveInteger(animal_id)) {
        return res.status(400).json({
          success: false,
          message: '动物ID不能为空且必须为正整数'
        });
      }

      if (!validateRequired(contact_info)) {
        return res.status(400).json({
          success: false,
          message: '联系方式不能为空'
        });
      }

      if (claim_duration && (!validatePositiveInteger(claim_duration) || claim_duration < 1 || claim_duration > 60)) {
        return res.status(400).json({
          success: false,
          message: '认领时长必须为1-60个月之间的整数'
        });
      }

      // 创建认领申请
      const claim = await AnimalClaimService.createClaim({
        animal_id: parseInt(animal_id),
        user_id,
        claim_reason,
        claim_duration: claim_duration ? parseInt(claim_duration) : 12,
        contact_info
      });

      res.status(201).json({
        success: true,
        message: '认领申请提交成功',
        data: claim
      });
    } catch (error) {
      console.error('创建认领申请控制器错误:', error);
      res.status(400).json({
        success: false,
        message: error.message || '创建认领申请失败'
      });
    }
  }

  /**
   * 取消认领申请
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async cancelClaim(req, res) {
    try {
      const { id } = req.params;
      const user_id = req.user.id;

      // 参数验证
      if (!validatePositiveInteger(id)) {
        return res.status(400).json({
          success: false,
          message: '认领申请ID无效'
        });
      }

      // 取消认领申请
      const claim = await AnimalClaimService.cancelClaim(parseInt(id), user_id);

      res.json({
        success: true,
        message: '认领申请已取消',
        data: claim
      });
    } catch (error) {
      console.error('取消认领申请控制器错误:', error);
      res.status(400).json({
        success: false,
        message: error.message || '取消认领申请失败'
      });
    }
  }

  /**
   * 获取用户的认领申请列表
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async getUserClaims(req, res) {
    try {
      const user_id = req.user.id;
      const {
        page = 1,
        limit = 10,
        status,
        animal_type,
        start_date,
        end_date
      } = req.query;

      // 参数验证
      if (!validatePositiveInteger(page) || !validatePositiveInteger(limit)) {
        return res.status(400).json({
          success: false,
          message: '分页参数必须为正整数'
        });
      }

      if (parseInt(limit) > 100) {
        return res.status(400).json({
          success: false,
          message: '每页数量不能超过100'
        });
      }

      // 获取认领申请列表
      const result = await AnimalClaimService.getUserClaims(user_id, {
        page: parseInt(page),
        limit: parseInt(limit),
        status,
        animal_type,
        start_date,
        end_date
      });

      res.json({
        success: true,
        message: '获取认领申请列表成功',
        data: result.data,
        pagination: result.pagination
      });
    } catch (error) {
      console.error('获取用户认领申请列表控制器错误:', error);
      res.status(500).json({
        success: false,
        message: '获取认领申请列表失败'
      });
    }
  }

  /**
   * 获取动物的认领申请列表
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async getAnimalClaims(req, res) {
    try {
      const { animal_id } = req.params;
      const {
        page = 1,
        limit = 10,
        status
      } = req.query;

      // 参数验证
      if (!validatePositiveInteger(animal_id)) {
        return res.status(400).json({
          success: false,
          message: '动物ID无效'
        });
      }

      if (!validatePositiveInteger(page) || !validatePositiveInteger(limit)) {
        return res.status(400).json({
          success: false,
          message: '分页参数必须为正整数'
        });
      }

      // 获取动物认领申请列表
      const result = await AnimalClaimService.getAnimalClaims(parseInt(animal_id), {
        page: parseInt(page),
        limit: parseInt(limit),
        status
      });

      res.json({
        success: true,
        message: '获取动物认领申请列表成功',
        data: result.data,
        pagination: result.pagination
      });
    } catch (error) {
      console.error('获取动物认领申请列表控制器错误:', error);
      res.status(500).json({
        success: false,
        message: '获取动物认领申请列表失败'
      });
    }
  }

  /**
   * 获取所有认领申请列表（管理员）
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async getAllClaims(req, res) {
    try {
      const {
        page = 1,
        limit = 10,
        status,
        animal_type,
        user_id,
        start_date,
        end_date,
        keyword
      } = req.query;

      // 参数验证
      if (!validatePositiveInteger(page) || !validatePositiveInteger(limit)) {
        return res.status(400).json({
          success: false,
          message: '分页参数必须为正整数'
        });
      }

      if (parseInt(limit) > 100) {
        return res.status(400).json({
          success: false,
          message: '每页数量不能超过100'
        });
      }

      // 获取所有认领申请列表
      const result = await AnimalClaimService.getAllClaims({
        page: parseInt(page),
        limit: parseInt(limit),
        status,
        animal_type,
        user_id: user_id ? parseInt(user_id) : undefined,
        start_date,
        end_date,
        keyword
      });

      res.json({
        success: true,
        message: '获取认领申请列表成功',
        data: result.data,
        pagination: result.pagination
      });
    } catch (error) {
      console.error('获取所有认领申请列表控制器错误:', error);
      res.status(500).json({
        success: false,
        message: '获取认领申请列表失败'
      });
    }
  }

  /**
   * 审核认领申请
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async reviewClaim(req, res) {
    try {
      const { id } = req.params;
      const { status, review_remark } = req.body;
      const reviewed_by = req.user.id;

      // 参数验证
      if (!validatePositiveInteger(id)) {
        return res.status(400).json({
          success: false,
          message: '认领申请ID无效'
        });
      }

      if (!validateRequired(status)) {
        return res.status(400).json({
          success: false,
          message: '审核状态不能为空'
        });
      }

      const validStatuses = ['approved', 'rejected'];
      if (!validStatuses.includes(status)) {
        return res.status(400).json({
          success: false,
          message: '无效的审核状态'
        });
      }

      // 审核认领申请
      const claim = await AnimalClaimService.reviewClaim(parseInt(id), status, {
        reviewed_by,
        review_remark
      });

      res.json({
        success: true,
        message: `认领申请${status === 'approved' ? '审核通过' : '审核拒绝'}`,
        data: claim
      });
    } catch (error) {
      console.error('审核认领申请控制器错误:', error);
      res.status(400).json({
        success: false,
        message: error.message || '审核认领申请失败'
      });
    }
  }

  /**
   * 续期认领
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async renewClaim(req, res) {
    try {
      const { id } = req.params;
      const { duration, payment_method } = req.body;
      const user_id = req.user.id;

      // 参数验证
      if (!validatePositiveInteger(id)) {
        return res.status(400).json({
          success: false,
          message: '认领申请ID无效'
        });
      }

      if (!validateRequired(duration) || !validatePositiveInteger(duration) || duration < 1 || duration > 60) {
        return res.status(400).json({
          success: false,
          message: '续期时长必须为1-60个月之间的整数'
        });
      }

      if (!validateRequired(payment_method)) {
        return res.status(400).json({
          success: false,
          message: '支付方式不能为空'
        });
      }

      // 续期认领
      const result = await AnimalClaimService.renewClaim(parseInt(id), user_id, {
        duration: parseInt(duration),
        payment_method
      });

      res.json({
        success: true,
        message: result.message,
        data: result
      });
    } catch (error) {
      console.error('续期认领控制器错误:', error);
      res.status(400).json({
        success: false,
        message: error.message || '续期认领失败'
      });
    }
  }

  /**
   * 获取认领统计信息
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async getClaimStatistics(req, res) {
    try {
      const { start_date, end_date, animal_type } = req.query;

      // 获取认领统计信息
      const statistics = await AnimalClaimService.getClaimStatistics({
        start_date,
        end_date,
        animal_type
      });

      res.json({
        success: true,
        message: '获取认领统计信息成功',
        data: statistics
      });
    } catch (error) {
      console.error('获取认领统计信息控制器错误:', error);
      res.status(500).json({
        success: false,
        message: '获取认领统计信息失败'
      });
    }
  }

  /**
   * 检查认领权限
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async checkClaimPermission(req, res) {
    try {
      const { animal_id } = req.params;
      const user_id = req.user.id;

      // 参数验证
      if (!validatePositiveInteger(animal_id)) {
        return res.status(400).json({
          success: false,
          message: '动物ID无效'
        });
      }

      // 检查认领权限
      const hasPermission = await AnimalClaimService.checkClaimPermission(user_id, parseInt(animal_id));

      res.json({
        success: true,
        message: '检查认领权限成功',
        data: {
          can_claim: hasPermission
        }
      });
    } catch (error) {
      console.error('检查认领权限控制器错误:', error);
      res.status(500).json({
        success: false,
        message: '检查认领权限失败'
      });
    }
  }
}

module.exports = new AnimalClaimController();