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

// 查询防疫机构列表
exports.getEpidemicAgencies = async (req, res) => {
  try {
    const { keyword, status, type, page = 1, pageSize = 10 } = req.query;
    
    const where = {};
    
    if (keyword) {
      where[Op.or] = [
        { name: { [Op.like]: `%${keyword}%` } },
        { director: { [Op.like]: `%${keyword}%` } },
        { phone: { [Op.like]: `%${keyword}%` } }
      ];
    }
    
    if (status) {
      where.status = status;
    }
    
    if (type) {
      where.type = type;
    }
    
    const { count, rows } = await EpidemicAgency.findAndCountAll({
      where,
      offset: (page - 1) * pageSize,
      limit: parseInt(pageSize),
      attributes: ['id', 'name', 'director', 'phone', 'address', 'email', 'type', 'status', 'establishmentDate', 'epidemicScope', 'description']
    });
    
    res.json({
      code: 200,
      data: {
        list: rows,
        total: count,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      },
      message: '查询成功'
    });
  } catch (error) {
    console.error('查询防疫机构列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
};

// 查询单个防疫机构详情
exports.getEpidemicAgencyById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const agency = await EpidemicAgency.findByPk(id);
    
    if (!agency) {
      return res.status(404).json({
        code: 404,
        message: '防疫机构不存在'
      });
    }
    
    res.json({
      code: 200,
      data: agency,
      message: '查询成功'
    });
  } catch (error) {
    console.error('查询防疫机构详情失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
};

// 新增防疫机构
exports.createEpidemicAgency = async (req, res) => {
  try {
    const { name, director, phone, address, email, type, status, establishmentDate, epidemicScope, description } = req.body;
    
    const existingAgency = await EpidemicAgency.findOne({
      where: { name }
    });
    
    if (existingAgency) {
      return res.status(400).json({
        code: 400,
        message: '该机构名称已存在'
      });
    }
    
    const agency = await EpidemicAgency.create({
      name,
      director,
      phone,
      address,
      email,
      type,
      status,
      establishmentDate,
      epidemicScope,
      description,
      created_by: req.user?.id || null,
      updated_by: req.user?.id || null
    });
    
    res.json({
      code: 201,
      data: agency,
      message: '新增成功'
    });
  } catch (error) {
    console.error('新增防疫机构失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
};

// 更新防疫机构
exports.updateEpidemicAgency = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, director, phone, address, email, type, status, establishmentDate, epidemicScope, description } = req.body;
    
    const agency = await EpidemicAgency.findByPk(id);
    
    if (!agency) {
      return res.status(404).json({
        code: 404,
        message: '防疫机构不存在'
      });
    }
    
    // 检查名称是否重复（排除当前机构）
    if (name && name !== agency.name) {
      const existingAgency = await EpidemicAgency.findOne({
        where: {
          name,
          id: { [Op.ne]: id }
        }
      });
      
      if (existingAgency) {
        return res.status(400).json({
          code: 400,
          message: '该机构名称已存在'
        });
      }
    }
    
    await agency.update({
      name,
      director,
      phone,
      address,
      email,
      type,
      status,
      establishmentDate,
      epidemicScope,
      description,
      updated_by: req.user?.id || null
    });
    
    res.json({
      code: 200,
      data: agency,
      message: '更新成功'
    });
  } catch (error) {
    console.error('更新防疫机构失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
};

// 删除防疫机构
exports.deleteEpidemicAgency = async (req, res) => {
  try {
    const { id } = req.params;
    
    const agency = await EpidemicAgency.findByPk(id);
    
    if (!agency) {
      return res.status(404).json({
        code: 404,
        message: '防疫机构不存在'
      });
    }
    
    await agency.destroy();
    
    res.json({
      code: 200,
      message: '删除成功'
    });
  } catch (error) {
    console.error('删除防疫机构失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
};

// 切换防疫机构状态
exports.toggleEpidemicAgencyStatus = async (req, res) => {
  try {
    const { id } = req.params;
    
    const agency = await EpidemicAgency.findByPk(id);
    
    if (!agency) {
      return res.status(404).json({
        code: 404,
        message: '防疫机构不存在'
      });
    }
    
    const newStatus = agency.status === 'active' ? 'inactive' : 'active';
    
    await agency.update({
      status: newStatus,
      updated_by: req.user?.id || null
    });
    
    res.json({
      code: 200,
      data: agency,
      message: '状态切换成功'
    });
  } catch (error) {
    console.error('切换防疫机构状态失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
};