const CattleAcademy = require('../models/CattleAcademy');
const { Op } = require('sequelize');

// 获取养牛学院资讯列表
const getCattleAcademyList = async (req, res) => {
  try {
    const { 
      page = 1, 
      pageSize = 10, 
      title, 
      category,
      status,
      author
    } = req.query;

    const offset = (page - 1) * pageSize;
    const where = {};

    // 构建查询条件
    if (title) {
      where.title = {
        [Op.like]: `%${title}%`
      };
    }
    if (category) {
      where.category = category;
    }
    if (status !== undefined) {
      where.status = status === 'true' || status === true;
    }
    if (author) {
      where.author = {
        [Op.like]: `%${author}%`
      };
    }

    const { count, rows } = await CattleAcademy.findAndCountAll({
      where,
      limit: parseInt(pageSize),
      offset: parseInt(offset),
      order: [['sort', 'DESC'], ['createdAt', 'DESC']]
    });

    res.json({
      code: 200,
      message: '获取成功',
      data: {
        list: rows,
        total: count,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    console.error('获取养牛学院资讯列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

// 根据ID获取养牛学院资讯详情
const getCattleAcademyById = async (req, res) => {
  try {
    const { id } = req.params;
    const cattleAcademy = await CattleAcademy.findByPk(id);
    
    if (!cattleAcademy) {
      return res.status(404).json({
        code: 404,
        message: '资讯不存在'
      });
    }

    // 增加浏览次数
    await cattleAcademy.increment('viewCount');

    res.json({
      code: 200,
      message: '获取成功',
      data: cattleAcademy
    });
  } catch (error) {
    console.error('获取养牛学院资讯详情失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

// 创建养牛学院资讯
const createCattleAcademy = async (req, res) => {
  try {
    const {
      title,
      coverImage,
      content,
      summary,
      category,
      tags,
      sort = 0,
      status = true,
      author,
      publishTime,
      isTop = false,
      isRecommend = false,
      remarks
    } = req.body;

    const cattleAcademy = await CattleAcademy.create({
      title,
      coverImage,
      content,
      summary,
      category,
      tags,
      sort,
      status,
      author,
      publishTime: publishTime || new Date(),
      isTop,
      isRecommend,
      remarks
    });

    res.status(201).json({
      code: 201,
      message: '创建成功',
      data: cattleAcademy
    });
  } catch (error) {
    console.error('创建养牛学院资讯失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

// 更新养牛学院资讯
const updateCattleAcademy = async (req, res) => {
  try {
    const { id } = req.params;
    const {
      title,
      coverImage,
      content,
      summary,
      category,
      tags,
      sort,
      status,
      author,
      publishTime,
      isTop,
      isRecommend,
      remarks
    } = req.body;

    const cattleAcademy = await CattleAcademy.findByPk(id);
    if (!cattleAcademy) {
      return res.status(404).json({
        code: 404,
        message: '资讯不存在'
      });
    }

    await cattleAcademy.update({
      title,
      coverImage,
      content,
      summary,
      category,
      tags,
      sort,
      status,
      author,
      publishTime,
      isTop,
      isRecommend,
      remarks
    });

    res.json({
      code: 200,
      message: '更新成功',
      data: cattleAcademy
    });
  } catch (error) {
    console.error('更新养牛学院资讯失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

// 删除养牛学院资讯
const deleteCattleAcademy = async (req, res) => {
  try {
    const { id } = req.params;
    const cattleAcademy = await CattleAcademy.findByPk(id);
    
    if (!cattleAcademy) {
      return res.status(404).json({
        code: 404,
        message: '资讯不存在'
      });
    }

    await cattleAcademy.destroy();

    res.json({
      code: 200,
      message: '删除成功'
    });
  } catch (error) {
    console.error('删除养牛学院资讯失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

// 切换资讯状态
const toggleCattleAcademyStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    
    const cattleAcademy = await CattleAcademy.findByPk(id);
    if (!cattleAcademy) {
      return res.status(404).json({
        code: 404,
        message: '资讯不存在'
      });
    }

    await cattleAcademy.update({ status });

    res.json({
      code: 200,
      message: '状态更新成功',
      data: cattleAcademy
    });
  } catch (error) {
    console.error('切换资讯状态失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

// 批量更新排序
const updateSort = async (req, res) => {
  try {
    const { items } = req.body; // [{id, sort}, ...]
    
    for (const item of items) {
      await CattleAcademy.update(
        { sort: item.sort },
        { where: { id: item.id } }
      );
    }

    res.json({
      code: 200,
      message: '排序更新成功'
    });
  } catch (error) {
    console.error('更新排序失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

module.exports = {
  getCattleAcademyList,
  getCattleAcademyById,
  createCattleAcademy,
  updateCattleAcademy,
  deleteCattleAcademy,
  toggleCattleAcademyStatus,
  updateSort
};
