const { CattleExitRecord, IotCattle, CattlePen, Farm } = require('../models');
const { Op } = require('sequelize');

/**
 * 离栏记录控制器
 */
class CattleExitRecordController {
  /**
   * 获取离栏记录列表
   */
  async getExitRecords(req, res) {
    try {
      const { page = 1, pageSize = 10, search, exitReason, status, dateRange } = req.query;
      const offset = (page - 1) * pageSize;

      // 构建查询条件
      const where = {};
      if (search) {
        console.log('🔍 [后端-离栏记录] 搜索关键词:', search);
        where[Op.or] = [
          { recordId: { [Op.like]: `%${search}%` } },
          { earNumber: { [Op.like]: `%${search}%` } }
        ];
        console.log('🔍 [后端-离栏记录] 搜索条件构建完成');
      }
      if (exitReason) {
        where.exitReason = exitReason;
      }
      if (status) {
        where.status = status;
      }
      if (dateRange && dateRange.length === 2) {
        where.exitDate = {
          [Op.between]: [dateRange[0], dateRange[1]]
        };
      }

      console.log('🔍 [后端-离栏记录] 搜索请求参数:', {
        search,
        exitReason,
        status,
        dateRange,
        page,
        pageSize
      });
      
      console.log('🔍 [后端-离栏记录] 构建的查询条件:', JSON.stringify(where, null, 2));

      console.log('🔍 [后端-离栏记录] 开始执行查询...');
      const { count, rows } = await CattleExitRecord.findAndCountAll({
        where,
        attributes: ['id', 'recordId', 'animalId', 'earNumber', 'exitDate', 'exitReason', 'originalPenId', 'destination', 'disposalMethod', 'handler', 'status', 'remark', 'farmId', 'created_at', 'updated_at'],
        include: [
          {
            model: IotCattle,
            as: 'cattle',
            attributes: ['id', 'earNumber', 'strain', 'sex'],
            required: false
          },
          {
            model: CattlePen,
            as: 'originalPen',
            attributes: ['id', 'name', 'code'],
            required: false
          },
          {
            model: Farm,
            as: 'farm',
            attributes: ['id', 'name'],
            required: false
          }
        ],
        limit: parseInt(pageSize),
        offset: parseInt(offset),
        order: [['exit_date', 'DESC']]
      });
      
      console.log('📊 [后端-离栏记录] 查询结果:', {
        总数: count,
        当前页记录数: rows.length,
        记录列表: rows.map(item => ({
          id: item.id,
          recordId: item.recordId,
          earNumber: item.earNumber,
          exitReason: item.exitReason,
          status: item.status
        }))
      });

      res.json({
        success: true,
        data: {
          list: rows,
          total: count,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        },
        message: '获取离栏记录列表成功'
      });
    } catch (error) {
      console.error('获取离栏记录列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取离栏记录列表失败',
        error: error.message
      });
    }
  }

  /**
   * 获取单个离栏记录详情
   */
  async getExitRecordById(req, res) {
    try {
      const { id } = req.params;
      
      console.log('=== 获取离栏记录详情 ===');
      console.log('请求时间:', new Date().toISOString());
      console.log('记录ID:', id);
      console.log('请求来源:', req.ip);
      console.log('用户信息:', req.user ? { id: req.user.id, username: req.user.username } : '未登录');
      console.log('User-Agent:', req.get('User-Agent'));
      console.log('请求URL:', req.originalUrl);
      console.log('请求方法:', req.method);
      console.log('Referer:', req.get('Referer'));
      console.log('操作类型: 获取详情（可能用于编辑）');

      const record = await CattleExitRecord.findByPk(id, {
        attributes: ['id', 'recordId', 'animalId', 'earNumber', 'exitDate', 'exitReason', 'originalPenId', 'destination', 'disposalMethod', 'handler', 'status', 'remark', 'farmId', 'created_at', 'updated_at'],
        include: [
          {
            model: IotCattle,
            as: 'cattle',
            attributes: ['id', 'earNumber', 'strain', 'sex']
          },
          {
            model: CattlePen,
            as: 'originalPen',
            attributes: ['id', 'name', 'code']
          },
          {
            model: Farm,
            as: 'farm',
            attributes: ['id', 'name']
          }
        ]
      });

      if (!record) {
        console.log('离栏记录不存在，ID:', id);
        return res.status(404).json({
          success: false,
          message: '离栏记录不存在'
        });
      }
      
      console.log('找到离栏记录:', {
        id: record.id,
        recordId: record.recordId,
        earNumber: record.earNumber,
        exitDate: record.exitDate,
        exitReason: record.exitReason,
        originalPenId: record.originalPenId,
        farmId: record.farmId,
        status: record.status
      });
      
      // 格式化返回数据
      const formattedData = {
        id: record.id,
        recordId: record.recordId,
        animalId: record.animalId,
        earNumber: record.earNumber,
        exitDate: record.exitDate,
        exitReason: record.exitReason,
        originalPenId: record.originalPenId,
        originalPen: record.originalPen ? {
          id: record.originalPen.id,
          name: record.originalPen.name,
          code: record.originalPen.code
        } : null,
        destination: record.destination,
        disposalMethod: record.disposalMethod,
        handler: record.handler,
        status: record.status,
        remark: record.remark,
        farmId: record.farmId,
        farm: record.farm ? {
          id: record.farm.id,
          name: record.farm.name
        } : null,
        cattle: record.cattle ? {
          id: record.cattle.id,
          earNumber: record.cattle.earNumber,
          strain: record.cattle.strain,
          sex: record.cattle.sex
        } : null,
        created_at: record.created_at,
        updated_at: record.updated_at
      };
      
      console.log('=== 返回格式化后的数据 ===');
      console.log('格式化数据示例:', {
        id: formattedData.id,
        recordId: formattedData.recordId,
        earNumber: formattedData.earNumber,
        exitDate: formattedData.exitDate,
        exitReason: formattedData.exitReason,
        originalPenId: formattedData.originalPenId,
        originalPenName: formattedData.originalPen?.name,
        destination: formattedData.destination,
        disposalMethod: formattedData.disposalMethod,
        handler: formattedData.handler,
        status: formattedData.status,
        farmId: formattedData.farmId,
        farmName: formattedData.farm?.name
      });
      console.log('完整返回数据字段:', Object.keys(formattedData));

      res.json({
        success: true,
        data: formattedData,
        message: '获取离栏记录详情成功'
      });
    } catch (error) {
      console.error('=== 获取离栏记录详情失败 ===');
      console.error('错误时间:', new Date().toISOString());
      console.error('记录ID:', req.params.id);
      console.error('错误信息:', error.message);
      console.error('错误堆栈:', error.stack);
      
      res.status(500).json({
        success: false,
        message: '获取离栏记录详情失败',
        error: error.message
      });
    }
  }

  /**
   * 创建离栏记录
   */
  async createExitRecord(req, res) {
    try {
      console.log('🆕 [后端-离栏记录] 开始创建操作');
      console.log('📋 [后端-离栏记录] 请求数据:', req.body);

      const recordData = req.body;

      // 验证必填字段
      if (!recordData.earNumber || !recordData.exitDate || !recordData.exitReason || !recordData.originalPenId || !recordData.handler) {
        console.log('❌ [后端-离栏记录] 必填字段验证失败:', {
          earNumber: !!recordData.earNumber,
          exitDate: !!recordData.exitDate,
          exitReason: !!recordData.exitReason,
          originalPenId: !!recordData.originalPenId,
          handler: !!recordData.handler
        });
        return res.status(400).json({
          success: false,
          message: '请填写所有必填字段（牛只耳号、离栏日期、离栏原因、原栏舍、处理人员）'
        });
      }

      // 生成记录编号
      const recordId = `EX${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(new Date().getDate()).padStart(2, '0')}${String(Date.now()).slice(-3)}`;

      // 通过耳号查找动物（支持数字和字符串类型）
      const earNumber = recordData.earNumber;
      const animal = await IotCattle.findOne({
        where: {
          [Op.or]: [
            { earNumber: earNumber },
            { earNumber: parseInt(earNumber) },
            { earNumber: earNumber.toString() }
          ]
        }
      });
      if (!animal) {
        console.log('❌ [后端-离栏记录] 动物不存在，耳号:', recordData.earNumber);
        return res.status(400).json({
          success: false,
          message: '牛只不存在，请检查耳号是否正确'
        });
      }

      console.log('✅ [后端-离栏记录] 找到动物:', {
        id: animal.id,
        earNumber: animal.earNumber,
        currentPenId: animal.penId
      });

      // 检查原栏舍是否存在
      const originalPen = await CattlePen.findByPk(recordData.originalPenId);
      if (!originalPen) {
        console.log('❌ [后端-离栏记录] 原栏舍不存在:', recordData.originalPenId);
        return res.status(400).json({
          success: false,
          message: '原栏舍不存在'
        });
      }

      // 准备创建数据
      const createData = {
        recordId,
        animalId: animal.id,
        earNumber: animal.earNumber,
        exitDate: new Date(recordData.exitDate),
        exitReason: recordData.exitReason,
        originalPenId: parseInt(recordData.originalPenId),
        destination: recordData.destination || '',
        disposalMethod: recordData.disposalMethod || '',
        handler: recordData.handler,
        status: recordData.status || '待确认',
        remark: recordData.remark || '',
        farmId: recordData.farmId || 1
      };

      console.log('📝 [后端-离栏记录] 准备创建的数据:', createData);

      const record = await CattleExitRecord.create(createData);

      // 如果状态是已确认，将动物从栏舍中移除
      if (recordData.status === '已确认') {
        await animal.update({ penId: null });
        console.log('✅ [后端-离栏记录] 动物已从栏舍中移除');
      }

      console.log('✅ [后端-离栏记录] 离栏记录创建成功:', record.id);

      res.status(201).json({
        success: true,
        data: record,
        message: '创建离栏记录成功'
      });
    } catch (error) {
      console.error('❌ [后端-离栏记录] 创建失败:', error);
      res.status(500).json({
        success: false,
        message: '创建离栏记录失败',
        error: error.message
      });
    }
  }

  /**
   * 更新离栏记录
   */
  async updateExitRecord(req, res) {
    try {
      const { id } = req.params;
      const updateData = req.body;

      console.log('🔄 [后端-离栏记录] 开始更新操作');
      console.log('📋 [后端-离栏记录] 请求参数:', {
        recordId: id,
        updateData: updateData
      });

      const record = await CattleExitRecord.findByPk(id);
      if (!record) {
        console.log('❌ [后端-离栏记录] 记录不存在，ID:', id);
        return res.status(404).json({
          success: false,
          message: '离栏记录不存在'
        });
      }

      console.log('📝 [后端-离栏记录] 原始记录数据:', {
        id: record.id,
        animalId: record.animalId,
        earNumber: record.earNumber,
        exitDate: record.exitDate,
        exitReason: record.exitReason,
        originalPenId: record.originalPenId,
        destination: record.destination,
        disposalMethod: record.disposalMethod,
        handler: record.handler,
        status: record.status,
        remark: record.remark
      });

      // 如果状态从非已确认变为已确认，将动物从栏舍中移除
      if (record.status !== '已确认' && updateData.status === '已确认') {
        console.log('🔄 [后端-离栏记录] 检测到状态变更为已确认，将动物从栏舍中移除');
        console.log('📝 [后端-离栏记录] 状态变更详情:', {
          oldStatus: record.status,
          newStatus: updateData.status,
          animalId: record.animalId
        });
        
        const animal = await IotCattle.findByPk(record.animalId);
        if (animal) {
          await animal.update({ penId: null });
          console.log('✅ [后端-离栏记录] 动物栏舍清空成功');
        } else {
          console.log('⚠️ [后端-离栏记录] 未找到对应的动物记录');
        }
      }

      await record.update(updateData);
      console.log('✅ [后端-离栏记录] 记录更新成功');

      res.json({
        success: true,
        data: record,
        message: '更新离栏记录成功'
      });
    } catch (error) {
      console.error('❌ [后端-离栏记录] 更新失败:', error);
      res.status(500).json({
        success: false,
        message: '更新离栏记录失败',
        error: error.message
      });
    }
  }

  /**
   * 删除离栏记录
   */
  async deleteExitRecord(req, res) {
    try {
      const { id } = req.params;

      const record = await CattleExitRecord.findByPk(id);
      if (!record) {
        return res.status(404).json({
          success: false,
          message: '离栏记录不存在'
        });
      }

      await record.destroy();

      res.json({
        success: true,
        message: '删除离栏记录成功'
      });
    } catch (error) {
      console.error('删除离栏记录失败:', error);
      res.status(500).json({
        success: false,
        message: '删除离栏记录失败',
        error: error.message
      });
    }
  }

  /**
   * 批量删除离栏记录
   */
  async batchDeleteExitRecords(req, res) {
    try {
      const { ids } = req.body;

      if (!ids || !Array.isArray(ids) || ids.length === 0) {
        return res.status(400).json({
          success: false,
          message: '请选择要删除的记录'
        });
      }

      await CattleExitRecord.destroy({
        where: { id: { [Op.in]: ids } }
      });

      res.json({
        success: true,
        message: `成功删除 ${ids.length} 条离栏记录`
      });
    } catch (error) {
      console.error('批量删除离栏记录失败:', error);
      res.status(500).json({
        success: false,
        message: '批量删除离栏记录失败',
        error: error.message
      });
    }
  }

  /**
   * 确认离栏记录
   */
  async confirmExitRecord(req, res) {
    try {
      const { id } = req.params;

      const record = await CattleExitRecord.findByPk(id);
      if (!record) {
        return res.status(404).json({
          success: false,
          message: '离栏记录不存在'
        });
      }

      if (record.status === '已确认') {
        return res.status(400).json({
          success: false,
          message: '记录已确认，无需重复操作'
        });
      }

      await record.update({ status: '已确认' });

      // 将动物从栏舍中移除
      const animal = await IotCattle.findByPk(record.animalId);
      if (animal) {
        await animal.update({ penId: null });
      }

      res.json({
        success: true,
        message: '确认离栏记录成功'
      });
    } catch (error) {
      console.error('确认离栏记录失败:', error);
      res.status(500).json({
        success: false,
        message: '确认离栏记录失败',
        error: error.message
      });
    }
  }

  /**
   * 获取可用的牛只列表
   */
  async getAvailableIotCattles(req, res) {
    try {
      const { search } = req.query;
      const where = {};
      
      if (search) {
        where.earNumber = { [Op.like]: `%${search}%` };
      }

      const animals = await IotCattle.findAll({
        where,
        include: [
          {
            model: CattlePen,
            as: 'pen',
            attributes: ['id', 'name', 'code']
          }
        ],
        attributes: ['id', 'earNumber', 'strain', 'sex', 'ageInMonths', 'physiologicalStage'],
        limit: 50,
        order: [['earNumber', 'ASC']]
      });

      res.json({
        success: true,
        data: animals,
        message: '获取可用牛只列表成功'
      });
    } catch (error) {
      console.error('获取可用牛只列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取可用牛只列表失败',
        error: error.message
      });
    }
  }

  /**
   * 获取可用的牛只列表
   */
  async getAvailableAnimals(req, res) {
    try {
      const { search, page = 1, pageSize = 10 } = req.query;
      const offset = (page - 1) * pageSize;

      // 构建查询条件
      const where = {};
      if (search) {
        where[Op.or] = [
          { earNumber: { [Op.like]: `%${search}%` } },
          { strain: { [Op.like]: `%${search}%` } }
        ];
      }

      const { count, rows } = await IotCattle.findAndCountAll({
        where,
        include: [
          {
            model: Farm,
            as: 'farm',
            attributes: ['id', 'name']
          }
        ],
        attributes: ['id', 'earNumber', 'sex', 'strain', 'orgId'],
        limit: parseInt(pageSize),
        offset: offset,
        order: [['earNumber', 'ASC']]
      });

      res.json({
        success: true,
        data: {
          list: rows,
          total: count,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        },
        message: '获取可用牛只列表成功'
      });
    } catch (error) {
      console.error('获取可用牛只列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取可用牛只列表失败',
        error: error.message
      });
    }
  }
}

module.exports = new CattleExitRecordController();
