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

// 获取生资认证列表
const getProductionMaterialCertifications = async (req, res) => {
  try {
    const { 
      page = 1, 
      pageSize = 20, 
      materialName, 
      materialType, 
      manufacturer,
      certificationType,
      certificationStatus 
    } = req.query;

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

    // 构建查询条件
    if (materialName) {
      where.materialName = {
        [Op.like]: `%${materialName}%`
      };
    }
    if (materialType) {
      where.materialType = materialType;
    }
    if (manufacturer) {
      where.manufacturer = {
        [Op.like]: `%${manufacturer}%`
      };
    }
    if (certificationType) {
      where.certificationType = certificationType;
    }
    if (certificationStatus) {
      where.certificationStatus = certificationStatus;
    }

    const { count, rows } = await ProductionMaterialCertification.findAndCountAll({
      where,
      limit: parseInt(pageSize),
      offset: parseInt(offset),
      order: [['updatedAt', '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 getProductionMaterialCertificationById = async (req, res) => {
  try {
    const { id } = req.params;
    const certification = await ProductionMaterialCertification.findByPk(id);
    
    if (!certification) {
      return res.status(404).json({
        code: 404,
        message: '生资认证不存在'
      });
    }

    res.json({
      code: 200,
      message: '获取成功',
      data: certification
    });
  } catch (error) {
    console.error('获取生资认证详情失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

// 创建生资认证
const createProductionMaterialCertification = async (req, res) => {
  try {
    const {
      materialName,
      materialType,
      manufacturer,
      certificationNumber,
      certificationType,
      certificationAuthority,
      issueDate,
      expiryDate,
      certificationStatus = 'valid',
      description,
      specifications,
      applicableScope,
      contactPerson,
      contactPhone,
      remarks
    } = req.body;

    const certification = await ProductionMaterialCertification.create({
      materialName,
      materialType,
      manufacturer,
      certificationNumber,
      certificationType,
      certificationAuthority,
      issueDate,
      expiryDate,
      certificationStatus,
      description,
      specifications,
      applicableScope,
      contactPerson,
      contactPhone,
      remarks
    });

    res.status(201).json({
      code: 201,
      message: '创建成功',
      data: certification
    });
  } catch (error) {
    console.error('创建生资认证失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

// 更新生资认证
const updateProductionMaterialCertification = async (req, res) => {
  try {
    const { id } = req.params;
    const {
      materialName,
      materialType,
      manufacturer,
      certificationNumber,
      certificationType,
      certificationAuthority,
      issueDate,
      expiryDate,
      certificationStatus,
      description,
      specifications,
      applicableScope,
      contactPerson,
      contactPhone,
      remarks
    } = req.body;

    const certification = await ProductionMaterialCertification.findByPk(id);
    if (!certification) {
      return res.status(404).json({
        code: 404,
        message: '生资认证不存在'
      });
    }

    await certification.update({
      materialName,
      materialType,
      manufacturer,
      certificationNumber,
      certificationType,
      certificationAuthority,
      issueDate,
      expiryDate,
      certificationStatus,
      description,
      specifications,
      applicableScope,
      contactPerson,
      contactPhone,
      remarks
    });

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

// 删除生资认证
const deleteProductionMaterialCertification = async (req, res) => {
  try {
    const { id } = req.params;
    const certification = await ProductionMaterialCertification.findByPk(id);
    
    if (!certification) {
      return res.status(404).json({
        code: 404,
        message: '生资认证不存在'
      });
    }

    await certification.destroy();

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

// 切换认证状态
const toggleCertificationStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    
    const certification = await ProductionMaterialCertification.findByPk(id);
    if (!certification) {
      return res.status(404).json({
        code: 404,
        message: '生资认证不存在'
      });
    }

    await certification.update({ certificationStatus: status });

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

module.exports = {
  getProductionMaterialCertifications,
  getProductionMaterialCertificationById,
  createProductionMaterialCertification,
  updateProductionMaterialCertification,
  deleteProductionMaterialCertification,
  toggleCertificationStatus
};
