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

/**
 * 转栏记录控制器
 */
class CattleTransferRecordController {
  /**
   * 获取转栏记录列表
   */
  async getTransferRecords(req, res) {
    try {
      const { page = 1, pageSize = 10, search, fromPen, toPen, dateRange } = req.query;
      const offset = (page - 1) * pageSize;

      // 详细的搜索参数日志
      console.group('🔍 [后端-转栏记录] 搜索请求详情');
      console.log('🕒 请求时间:', new Date().toISOString());
      console.log('📋 接收到的查询参数:', {
        page: page,
        pageSize: pageSize,
        search: search,
        fromPen: fromPen,
        toPen: toPen,
        dateRange: dateRange
      });
      console.log('🔍 搜索关键词:', search || '无');
      console.log('📊 分页参数:', { page, pageSize, offset });
      console.groupEnd();

      // 构建查询条件
      const where = {};
      if (search) {
        where[Op.or] = [
          { recordId: { [Op.like]: `%${search}%` } },
          { ear_number: { [Op.like]: `%${search}%` } }
        ];
        console.log('🔍 [后端-转栏记录] 搜索条件构建:', {
          搜索关键词: search,
          搜索字段: ['recordId', 'ear_number'],
          搜索模式: 'LIKE %keyword%'
        });
      }
      if (fromPen) {
        where.fromPenId = fromPen;
        console.log('🏠 [后端-转栏记录] 转出栏舍筛选:', fromPen);
      }
      if (toPen) {
        where.toPenId = toPen;
        console.log('🏠 [后端-转栏记录] 转入栏舍筛选:', toPen);
      }
      if (dateRange && dateRange.length === 2) {
        where.transferDate = {
          [Op.between]: [dateRange[0], dateRange[1]]
        };
        console.log('📅 [后端-转栏记录] 日期范围筛选:', dateRange);
      }

      const { count, rows } = await CattleTransferRecord.findAndCountAll({
        where,
        attributes: ['id', 'recordId', 'animalId', 'earNumber', 'fromPenId', 'toPenId', 'transferDate', 'reason', 'operator', 'status', 'remark', 'farmId', 'created_at', 'updated_at'],
        include: [
          {
            model: CattlePen,
            as: 'fromPen',
            attributes: ['id', 'name', 'code']
          },
          {
            model: CattlePen,
            as: 'toPen',
            attributes: ['id', 'name', 'code']
          },
          {
            model: Farm,
            as: 'farm',
            attributes: ['id', 'name']
          }
        ],
        limit: parseInt(pageSize),
        offset: parseInt(offset),
        order: [['transfer_date', 'DESC']]
      });

      // 详细的查询结果日志
      console.group('📊 [后端-转栏记录] 查询结果详情');
      console.log('📈 查询统计:', {
        总记录数: count,
        当前页数据量: rows.length,
        当前页码: page,
        每页大小: pageSize,
        总页数: Math.ceil(count / pageSize)
      });
      console.log('🔍 查询条件:', where);
      console.log('⏱️ 查询耗时:', '已记录在数据库层面');
      console.groupEnd();
      
      // 调试：检查关联数据
      if (rows.length > 0) {
        console.group('🔗 [后端-转栏记录] 关联数据检查');
        console.log('📋 第一条记录详情:', {
          id: rows[0].id,
          recordId: rows[0].recordId,
          earNumber: rows[0].earNumber,
          fromPenId: rows[0].fromPenId,
          toPenId: rows[0].toPenId,
          transferDate: rows[0].transferDate,
          reason: rows[0].reason,
          operator: rows[0].operator
        });
        console.log('🏠 栏舍关联信息:', {
          fromPen: rows[0].fromPen ? {
            id: rows[0].fromPen.id,
            name: rows[0].fromPen.name,
            code: rows[0].fromPen.code
          } : '无关联数据',
          toPen: rows[0].toPen ? {
            id: rows[0].toPen.id,
            name: rows[0].toPen.name,
            code: rows[0].toPen.code
          } : '无关联数据'
        });
        console.groupEnd();
      } else {
        console.log('📭 [后端-转栏记录] 查询结果为空');
      }

      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 getTransferRecordById(req, res) {
    try {
      const { id } = req.params;

      const record = await CattleTransferRecord.findByPk(id, {
        include: [
          {
            model: IotCattle,
            as: 'cattle',
            attributes: ['id', 'earNumber', 'strain', 'sex']
          },
          {
            model: CattlePen,
            as: 'fromPen',
            attributes: ['id', 'name', 'code']
          },
          {
            model: CattlePen,
            as: 'toPen',
            attributes: ['id', 'name', 'code']
          },
          {
            model: Farm,
            as: 'farm',
            attributes: ['id', 'name']
          }
        ]
      });

      if (!record) {
        return res.status(404).json({
          success: false,
          message: '转栏记录不存在'
        });
      }

      res.json({
        success: true,
        data: record,
        message: '获取转栏记录详情成功'
      });
    } catch (error) {
      console.error('获取转栏记录详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取转栏记录详情失败',
        error: error.message
      });
    }
  }

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

      const recordData = req.body;

      // 验证必填字段
      if (!recordData.earNumber || !recordData.fromPenId || !recordData.toPenId || !recordData.transferDate || !recordData.reason || !recordData.operator) {
        console.log('❌ [后端-转栏记录] 必填字段验证失败:', {
          earNumber: !!recordData.earNumber,
          fromPenId: !!recordData.fromPenId,
          toPenId: !!recordData.toPenId,
          transferDate: !!recordData.transferDate,
          reason: !!recordData.reason,
          operator: !!recordData.operator
        });
        return res.status(400).json({
          success: false,
          message: '请填写所有必填字段（牛只耳号、转出栏舍、转入栏舍、转栏日期、转栏原因、操作人员）'
        });
      }

      // 生成记录编号
      const recordId = `TR${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 fromPen = await CattlePen.findByPk(recordData.fromPenId);
      const toPen = await CattlePen.findByPk(recordData.toPenId);
      if (!fromPen || !toPen) {
        console.log('❌ [后端-转栏记录] 栏舍不存在:', {
          fromPenId: recordData.fromPenId,
          toPenId: recordData.toPenId,
          fromPenExists: !!fromPen,
          toPenExists: !!toPen
        });
        return res.status(400).json({
          success: false,
          message: '栏舍不存在'
        });
      }

      // 准备创建数据
      const createData = {
        recordId,
        animalId: animal.id,
        earNumber: animal.earNumber,
        fromPenId: parseInt(recordData.fromPenId),
        toPenId: parseInt(recordData.toPenId),
        transferDate: new Date(recordData.transferDate),
        reason: recordData.reason,
        operator: recordData.operator,
        status: recordData.status || '已完成',
        remark: recordData.remark || '',
        farmId: recordData.farmId || 1
      };

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

      const record = await CattleTransferRecord.create(createData);

      // 更新动物的当前栏舍
      await animal.update({ penId: recordData.toPenId });
      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 updateTransferRecord(req, res) {
    try {
      const { id } = req.params;
      const updateData = req.body;

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

      const record = await CattleTransferRecord.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,
        fromPenId: record.fromPenId,
        toPenId: record.toPenId,
        transferDate: record.transferDate,
        reason: record.reason,
        operator: record.operator,
        status: record.status,
        remark: record.remark
      });

      // 如果更新了转入栏舍，需要更新动物的当前栏舍
      if (updateData.toPenId && updateData.toPenId !== record.toPenId) {
        console.log('🔄 [后端-转栏记录] 检测到栏舍变更，更新动物当前栏舍');
        console.log('📝 [后端-转栏记录] 栏舍变更详情:', {
          oldPenId: record.toPenId,
          newPenId: updateData.toPenId,
          animalId: record.animalId
        });
        
        const animal = await IotCattle.findByPk(record.animalId);
        if (animal) {
          await animal.update({ penId: updateData.toPenId });
          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 deleteTransferRecord(req, res) {
    try {
      const { id } = req.params;

      const record = await CattleTransferRecord.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 batchDeleteTransferRecords(req, res) {
    try {
      const { ids } = req.body;

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

      await CattleTransferRecord.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 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 CattleTransferRecordController();
