const { validationResult } = require('express-validator');
const { Op } = require('sequelize');
const HarmlessPlace = require('../models/HarmlessPlace');

// 获取无害化场所列表
exports.getList = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, keyword = '', status = '' } = req.query;
    const offset = (page - 1) * pageSize;
    
    const where = {};
    
    if (keyword) {
      where[Op.or] = [
        { name: { [Op.like]: `%${keyword}%` } },
        { licenseNumber: { [Op.like]: `%${keyword}%` } }
      ];
    }
    
    if (status) {
      where.status = status;
    }

    // 移除排序部分，避免使用不存在的created_at字段
    const result = await HarmlessPlace.findAndCountAll({
      where,
      attributes: ['id', 'name', 'address', 'contactPerson', 'contactPhone', 'licenseNumber', 'status'],
      limit: parseInt(pageSize),
      offset: parseInt(offset)
    });

    res.json({
      code: 200,
      message: '获取成功',
      data: {
        list: result.rows,
        total: result.count
      }
    });
  } catch (error) {
    console.error('获取无害化场所列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取失败',
      error: error.message
    });
  }
};

// 获取无害化场所详情
exports.getDetail = async (req, res) => {
  try {
    const { id } = req.params;
    const place = await HarmlessPlace.findByPk(id);
    
    if (!place) {
      return res.status(404).json({
        code: 404,
        message: '无害化场所不存在'
      });
    }
    
    res.json({
      code: 200,
      message: '获取成功',
      data: place
    });
  } catch (error) {
    console.error('获取无害化场所详情失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取失败',
      error: error.message
    });
  }
};

// 创建无害化场所
exports.create = async (req, res) => {
  try {
    // 验证请求数据
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        code: 400,
        message: '参数错误',
        errors: errors.array()
      });
    }
    
    const { name, address, contactPerson, contactPhone, licenseNumber, status } = req.body;
    
    // 创建无害化场所
    const place = await HarmlessPlace.create({
      name,
      address,
      contactPerson,
      contactPhone,
      licenseNumber,
      status: status || '正常'
    });
    
    res.json({
      code: 200,
      message: '创建成功',
      data: place
    });
  } catch (error) {
    console.error('创建无害化场所失败:', error);
    res.status(500).json({
      code: 500,
      message: '创建失败',
      error: error.message
    });
  }
};

// 更新无害化场所
exports.update = async (req, res) => {
  try {
    // 验证请求数据
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        code: 400,
        message: '参数错误',
        errors: errors.array()
      });
    }
    
    const { id } = req.params;
    const { name, address, contactPerson, contactPhone, licenseNumber, status } = req.body;
    
    // 查找无害化场所
    const place = await HarmlessPlace.findByPk(id);
    
    if (!place) {
      return res.status(404).json({
        code: 404,
        message: '无害化场所不存在'
      });
    }
    
    // 更新无害化场所
    await place.update({
      name,
      address,
      contactPerson,
      contactPhone,
      licenseNumber,
      status
    });
    
    res.json({
      code: 200,
      message: '更新成功',
      data: place
    });
  } catch (error) {
    console.error('更新无害化场所失败:', error);
    res.status(500).json({
      code: 500,
      message: '更新失败',
      error: error.message
    });
  }
};

// 删除无害化场所
exports.delete = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 查找无害化场所
    const place = await HarmlessPlace.findByPk(id);
    
    if (!place) {
      return res.status(404).json({
        code: 404,
        message: '无害化场所不存在'
      });
    }
    
    // 删除无害化场所
    await place.destroy();
    
    res.json({
      code: 200,
      message: '删除成功'
    });
  } catch (error) {
    console.error('删除无害化场所失败:', error);
    res.status(500).json({
      code: 500,
      message: '删除失败',
      error: error.message
    });
  }
};