const AnimalClaimModel = require('../models/AnimalClaim');
const AnimalModel = require('../models/Animal');

class AnimalClaimService {
  /**
   * 申请认领动物
   * @param {Object} claimData - 认领申请数据
   * @returns {Object} 认领申请记录
   */
  async createClaim(claimData) {
    try {
      const { animal_id, user_id, claim_reason, claim_duration, contact_info } = claimData;

      // 检查动物是否存在且可认领
      const animal = await AnimalModel.findById(animal_id);
      if (!animal) {
        throw new Error('动物不存在');
      }

      if (animal.status !== 'available') {
        throw new Error('该动物当前不可认领');
      }

      // 检查用户是否已经认领过该动物
      const existingClaim = await AnimalClaimModel.findActiveClaimByUserAndAnimal(user_id, animal_id);
      if (existingClaim) {
        throw new Error('您已经认领过该动物，请勿重复申请');
      }

      // 生成认领订单号
      const claimNo = this.generateClaimNo();

      // 创建认领申请
      const claim = await AnimalClaimModel.create({
        claim_no: claimNo,
        animal_id,
        user_id,
        claim_reason: claim_reason || '喜欢这只动物',
        claim_duration: claim_duration || 12, // 默认12个月
        contact_info,
        status: 'pending',
        total_amount: animal.price * (claim_duration || 12)
      });

      return this.sanitizeClaim(claim);
    } catch (error) {
      console.error('创建动物认领申请服务错误:', error);
      throw error;
    }
  }

  /**
   * 取消认领申请
   * @param {number} claimId - 认领申请ID
   * @param {number} userId - 用户ID
   * @returns {Object} 更新后的认领申请
   */
  async cancelClaim(claimId, userId) {
    try {
      // 获取认领申请
      const claim = await AnimalClaimModel.findById(claimId);
      if (!claim) {
        throw new Error('认领申请不存在');
      }

      // 检查权限
      if (claim.user_id !== userId) {
        throw new Error('无权操作此认领申请');
      }

      // 检查状态
      if (!['pending', 'approved'].includes(claim.status)) {
        throw new Error('当前状态不允许取消');
      }

      // 更新状态
      const updatedClaim = await AnimalClaimModel.updateStatus(claimId, 'cancelled', {
        cancelled_at: new Date(),
        cancel_reason: '用户主动取消'
      });

      // 如果动物状态是已认领，需要恢复为可认领
      if (claim.status === 'approved') {
        await AnimalModel.updateStatus(claim.animal_id, 'available');
      }

      return this.sanitizeClaim(updatedClaim);
    } catch (error) {
      console.error('取消动物认领服务错误:', error);
      throw error;
    }
  }

  /**
   * 获取用户的认领申请列表
   * @param {number} userId - 用户ID
   * @param {Object} options - 查询选项
   * @returns {Object} 分页结果
   */
  async getUserClaims(userId, options = {}) {
    try {
      const result = await AnimalClaimModel.getUserClaims(userId, options);
      
      return {
        data: result.data.map(claim => this.sanitizeClaim(claim)),
        pagination: result.pagination
      };
    } catch (error) {
      console.error('获取用户认领申请服务错误:', error);
      throw error;
    }
  }

  /**
   * 获取动物的认领申请列表
   * @param {number} animalId - 动物ID
   * @param {Object} options - 查询选项
   * @returns {Object} 分页结果
   */
  async getAnimalClaims(animalId, options = {}) {
    try {
      const result = await AnimalClaimModel.getAnimalClaims(animalId, options);
      
      return {
        data: result.data.map(claim => this.sanitizeClaim(claim)),
        pagination: result.pagination
      };
    } catch (error) {
      console.error('获取动物认领申请服务错误:', error);
      throw error;
    }
  }

  /**
   * 获取所有认领申请列表（管理员）
   * @param {Object} options - 查询选项
   * @returns {Object} 分页结果
   */
  async getAllClaims(options = {}) {
    try {
      const result = await AnimalClaimModel.getAllClaims(options);
      
      return {
        data: result.data.map(claim => this.sanitizeClaim(claim)),
        pagination: result.pagination
      };
    } catch (error) {
      console.error('获取所有认领申请服务错误:', error);
      throw error;
    }
  }

  /**
   * 审核认领申请
   * @param {number} claimId - 认领申请ID
   * @param {string} status - 审核状态
   * @param {Object} reviewData - 审核数据
   * @returns {Object} 更新后的认领申请
   */
  async reviewClaim(claimId, status, reviewData = {}) {
    try {
      const { reviewed_by, review_remark } = reviewData;

      // 获取认领申请
      const claim = await AnimalClaimModel.findById(claimId);
      if (!claim) {
        throw new Error('认领申请不存在');
      }

      // 检查状态
      if (claim.status !== 'pending') {
        throw new Error('只能审核待审核的申请');
      }

      // 验证审核状态
      const validStatuses = ['approved', 'rejected'];
      if (!validStatuses.includes(status)) {
        throw new Error('无效的审核状态');
      }

      // 更新认领申请状态
      const updateData = {
        reviewed_by,
        review_remark,
        reviewed_at: new Date()
      };

      if (status === 'approved') {
        updateData.approved_at = new Date();
        updateData.start_date = new Date();
        
        // 计算结束日期
        const endDate = new Date();
        endDate.setMonth(endDate.getMonth() + claim.claim_duration);
        updateData.end_date = endDate;

        // 更新动物状态为已认领
        await AnimalModel.updateStatus(claim.animal_id, 'claimed');
        
        // 增加动物认领次数
        await AnimalModel.incrementClaimCount(claim.animal_id);
      }

      const updatedClaim = await AnimalClaimModel.updateStatus(claimId, status, updateData);

      return this.sanitizeClaim(updatedClaim);
    } catch (error) {
      console.error('审核认领申请服务错误:', error);
      throw error;
    }
  }

  /**
   * 续期认领
   * @param {number} claimId - 认领申请ID
   * @param {number} userId - 用户ID
   * @param {Object} renewData - 续期数据
   * @returns {Object} 续期结果
   */
  async renewClaim(claimId, userId, renewData) {
    try {
      const { duration, payment_method } = renewData;

      // 获取认领申请
      const claim = await AnimalClaimModel.findById(claimId);
      if (!claim) {
        throw new Error('认领申请不存在');
      }

      // 检查权限
      if (claim.user_id !== userId) {
        throw new Error('无权操作此认领申请');
      }

      // 检查状态
      if (claim.status !== 'approved') {
        throw new Error('只有已通过的认领申请才能续期');
      }

      // 检查是否即将到期（提前30天可以续期）
      const now = new Date();
      const endDate = new Date(claim.end_date);
      const daysUntilExpiry = Math.ceil((endDate - now) / (1000 * 60 * 60 * 24));
      
      if (daysUntilExpiry > 30) {
        throw new Error('距离到期还有超过30天，暂时无法续期');
      }

      // 获取动物信息计算续期费用
      const animal = await AnimalModel.findById(claim.animal_id);
      const renewAmount = animal.price * duration;

      // 创建续期记录
      const renewRecord = await AnimalClaimModel.createRenewal({
        claim_id: claimId,
        duration,
        amount: renewAmount,
        payment_method,
        status: 'pending'
      });

      return {
        renewal: renewRecord,
        amount: renewAmount,
        message: '续期申请已提交，请完成支付'
      };
    } catch (error) {
      console.error('续期认领服务错误:', error);
      throw error;
    }
  }

  /**
   * 获取认领统计信息
   * @param {Object} filters - 筛选条件
   * @returns {Object} 统计信息
   */
  async getClaimStatistics(filters = {}) {
    try {
      const statistics = await AnimalClaimModel.getClaimStatistics(filters);
      return statistics;
    } catch (error) {
      console.error('获取认领统计服务错误:', error);
      throw error;
    }
  }

  /**
   * 检查认领权限
   * @param {number} userId - 用户ID
   * @param {number} animalId - 动物ID
   * @returns {boolean} 是否有权限
   */
  async checkClaimPermission(userId, animalId) {
    try {
      // 检查动物是否存在
      const animal = await AnimalModel.findById(animalId);
      if (!animal) {
        return false;
      }

      // 检查动物状态
      if (animal.status !== 'available') {
        return false;
      }

      // 检查用户是否已有活跃的认领申请
      const existingClaim = await AnimalClaimModel.findActiveClaimByUserAndAnimal(userId, animalId);
      if (existingClaim) {
        return false;
      }

      return true;
    } catch (error) {
      console.error('检查认领权限服务错误:', error);
      return false;
    }
  }

  /**
   * 生成认领订单号
   * @returns {string} 认领订单号
   */
  generateClaimNo() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const timestamp = now.getTime().toString().slice(-6);
    
    return `CLAIM${year}${month}${day}${timestamp}`;
  }

  /**
   * 清理认领申请数据
   * @param {Object} claim - 认领申请数据
   * @returns {Object} 清理后的数据
   */
  sanitizeClaim(claim) {
    if (!claim) return null;

    return {
      id: claim.id,
      claim_no: claim.claim_no,
      animal_id: claim.animal_id,
      animal_name: claim.animal_name,
      animal_type: claim.animal_type,
      animal_image: claim.animal_image,
      user_id: claim.user_id,
      username: claim.username,
      user_phone: claim.user_phone,
      claim_reason: claim.claim_reason,
      claim_duration: claim.claim_duration,
      total_amount: parseFloat(claim.total_amount || 0),
      contact_info: claim.contact_info,
      status: claim.status,
      start_date: claim.start_date,
      end_date: claim.end_date,
      reviewed_by: claim.reviewed_by,
      reviewer_name: claim.reviewer_name,
      review_remark: claim.review_remark,
      reviewed_at: claim.reviewed_at,
      approved_at: claim.approved_at,
      cancelled_at: claim.cancelled_at,
      cancel_reason: claim.cancel_reason,
      created_at: claim.created_at,
      updated_at: claim.updated_at
    };
  }
}

module.exports = new AnimalClaimService();