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

// 获取审批流程列表
const getApprovalProcesses = async (req, res) => {
  try {
    const { 
      page = 1, 
      pageSize = 9, 
      status,
      applicant,
      type
    } = req.query;

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

    // 构建查询条件
    if (status) {
      where.status = status;
    }
    if (applicant) {
      where.applicant = {
        [Op.like]: `%${applicant}%`
      };
    }
    if (type) {
      where.type = type;
    }

    const { count, rows } = await ApprovalProcess.findAndCountAll({
      where,
      limit: parseInt(pageSize),
      offset: parseInt(offset),
      order: [['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 getApprovalProcessById = async (req, res) => {
  try {
    const { id } = req.params;
    const approvalProcess = await ApprovalProcess.findByPk(id);
    
    if (!approvalProcess) {
      return res.status(404).json({
        code: 404,
        message: '审批流程不存在'
      });
    }

    res.json({
      code: 200,
      message: '获取成功',
      data: approvalProcess
    });
  } catch (error) {
    console.error('获取审批流程详情失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

// 创建审批流程
const createApprovalProcess = async (req, res) => {
  try {
    const {
      title,
      type,
      applicant,
      phone,
      farmName,
      quantity,
      description,
      files,
      remarks
    } = req.body;

    const approvalProcess = await ApprovalProcess.create({
      title,
      type,
      applicant,
      phone,
      farmName,
      quantity,
      description,
      files,
      remarks,
      status: 'pending'
    });

    res.status(201).json({
      code: 201,
      message: '创建成功',
      data: approvalProcess
    });
  } catch (error) {
    console.error('创建审批流程失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

// 更新审批流程
const updateApprovalProcess = async (req, res) => {
  try {
    const { id } = req.params;
    const {
      title,
      type,
      applicant,
      phone,
      farmName,
      quantity,
      description,
      files,
      remarks
    } = req.body;

    const approvalProcess = await ApprovalProcess.findByPk(id);
    if (!approvalProcess) {
      return res.status(404).json({
        code: 404,
        message: '审批流程不存在'
      });
    }

    await approvalProcess.update({
      title,
      type,
      applicant,
      phone,
      farmName,
      quantity,
      description,
      files,
      remarks
    });

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

// 删除审批流程
const deleteApprovalProcess = async (req, res) => {
  try {
    const { id } = req.params;
    const approvalProcess = await ApprovalProcess.findByPk(id);
    
    if (!approvalProcess) {
      return res.status(404).json({
        code: 404,
        message: '审批流程不存在'
      });
    }

    await approvalProcess.destroy();

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

// 审批操作（通过/拒绝）
const processApproval = async (req, res) => {
  try {
    const { id } = req.params;
    const { action, approvalComment, approver } = req.body;
    
    const approvalProcess = await ApprovalProcess.findByPk(id);
    if (!approvalProcess) {
      return res.status(404).json({
        code: 404,
        message: '审批流程不存在'
      });
    }

    const status = action === 'approve' ? 'approved' : 'rejected';
    
    await approvalProcess.update({
      status,
      approvalComment,
      approver,
      approvalTime: new Date()
    });

    res.json({
      code: 200,
      message: action === 'approve' ? '审批通过' : '审批拒绝',
      data: approvalProcess
    });
  } catch (error) {
    console.error('审批操作失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

// 更新审批状态
const updateApprovalStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    
    const approvalProcess = await ApprovalProcess.findByPk(id);
    if (!approvalProcess) {
      return res.status(404).json({
        code: 404,
        message: '审批流程不存在'
      });
    }

    await approvalProcess.update({ status });

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

module.exports = {
  getApprovalProcesses,
  getApprovalProcessById,
  createApprovalProcess,
  updateApprovalProcess,
  deleteApprovalProcess,
  processApproval,
  updateApprovalStatus
};
