const PaymentService = require('../services/payment');
const { validationResult } = require('express-validator');

class PaymentController {
  /**
   * 创建支付订单
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async createPayment(req, res) {
    try {
      // 验证请求参数
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '参数验证失败',
          errors: errors.array()
        });
      }

      const paymentData = req.body;
      const userId = req.user.id;

      // 验证必要字段
      if (!paymentData.order_id || !paymentData.amount || !paymentData.payment_method) {
        return res.status(400).json({
          success: false,
          message: '缺少必要字段: order_id, amount, payment_method'
        });
      }

      // 添加用户ID
      paymentData.user_id = userId;

      const payment = await PaymentService.createPayment(paymentData);

      res.status(201).json({
        success: true,
        message: '支付订单创建成功',
        data: payment
      });
    } catch (error) {
      console.error('创建支付订单控制器错误:', error);
      res.status(500).json({
        success: false,
        message: error.message || '创建支付订单失败'
      });
    }
  }

  /**
   * 获取支付订单详情
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async getPayment(req, res) {
    try {
      const { paymentId } = req.params;
      const userId = req.user.id;

      const payment = await PaymentService.getPaymentById(paymentId);

      // 检查权限：用户只能查看自己的支付订单
      if (req.user.role === 'user' && payment.user_id !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权访问此支付订单'
        });
      }

      res.json({
        success: true,
        data: payment
      });
    } catch (error) {
      console.error('获取支付订单控制器错误:', error);
      if (error.message === '支付订单不存在') {
        return res.status(404).json({
          success: false,
          message: '支付订单不存在'
        });
      }
      res.status(500).json({
        success: false,
        message: error.message || '获取支付订单失败'
      });
    }
  }

  /**
   * 查询支付状态
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async queryPaymentStatus(req, res) {
    try {
      const { paymentNo } = req.params;
      const userId = req.user.id;

      const payment = await PaymentService.getPaymentByNo(paymentNo);

      // 检查权限
      if (req.user.role === 'user' && payment.user_id !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权访问此支付订单'
        });
      }

      res.json({
        success: true,
        data: {
          payment_no: payment.payment_no,
          status: payment.status,
          amount: payment.amount,
          paid_at: payment.paid_at,
          transaction_id: payment.transaction_id
        }
      });
    } catch (error) {
      console.error('查询支付状态控制器错误:', error);
      if (error.message === '支付订单不存在') {
        return res.status(404).json({
          success: false,
          message: '支付订单不存在'
        });
      }
      res.status(500).json({
        success: false,
        message: error.message || '查询支付状态失败'
      });
    }
  }

  /**
   * 处理支付回调（微信支付）
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async handleWechatCallback(req, res) {
    try {
      const callbackData = req.body;

      // 验证回调数据
      if (!callbackData.out_trade_no || !callbackData.transaction_id) {
        return res.status(400).json({
          success: false,
          message: '回调数据不完整'
        });
      }

      // 处理支付回调
      const payment = await PaymentService.handlePaymentCallback({
        payment_no: callbackData.out_trade_no,
        transaction_id: callbackData.transaction_id,
        status: callbackData.result_code === 'SUCCESS' ? 'paid' : 'failed',
        paid_amount: callbackData.total_fee / 100, // 微信金额单位为分
        paid_at: new Date()
      });

      // 返回微信要求的格式
      res.set('Content-Type', 'application/xml');
      res.send(`
        <xml>
          <return_code><![CDATA[SUCCESS]]></return_code>
          <return_msg><![CDATA[OK]]></return_msg>
        </xml>
      `);
    } catch (error) {
      console.error('处理微信支付回调错误:', error);
      res.set('Content-Type', 'application/xml');
      res.send(`
        <xml>
          <return_code><![CDATA[FAIL]]></return_code>
          <return_msg><![CDATA[${error.message}]]></return_msg>
        </xml>
      `);
    }
  }

  /**
   * 处理支付回调（支付宝）
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async handleAlipayCallback(req, res) {
    try {
      const callbackData = req.body;

      // 验证回调数据
      if (!callbackData.out_trade_no || !callbackData.trade_no) {
        return res.status(400).json({
          success: false,
          message: '回调数据不完整'
        });
      }

      // 处理支付回调
      const payment = await PaymentService.handlePaymentCallback({
        payment_no: callbackData.out_trade_no,
        transaction_id: callbackData.trade_no,
        status: callbackData.trade_status === 'TRADE_SUCCESS' ? 'paid' : 'failed',
        paid_amount: parseFloat(callbackData.total_amount),
        paid_at: new Date()
      });

      res.send('success');
    } catch (error) {
      console.error('处理支付宝回调错误:', error);
      res.send('fail');
    }
  }

  /**
   * 申请退款
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async createRefund(req, res) {
    try {
      const { paymentId } = req.params;
      const refundData = req.body;
      const userId = req.user.id;

      // 验证必要字段
      if (!refundData.refund_amount || !refundData.refund_reason) {
        return res.status(400).json({
          success: false,
          message: '缺少必要字段: refund_amount, refund_reason'
        });
      }

      // 获取支付订单并验证权限
      const payment = await PaymentService.getPaymentById(paymentId);
      if (req.user.role === 'user' && payment.user_id !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权操作此支付订单'
        });
      }

      const refund = await PaymentService.createRefund({
        payment_id: paymentId,
        refund_amount: refundData.refund_amount,
        refund_reason: refundData.refund_reason,
        user_id: userId
      });

      res.status(201).json({
        success: true,
        message: '退款申请提交成功',
        data: refund
      });
    } catch (error) {
      console.error('申请退款控制器错误:', error);
      res.status(500).json({
        success: false,
        message: error.message || '申请退款失败'
      });
    }
  }

  /**
   * 处理退款（管理员）
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async processRefund(req, res) {
    try {
      const { refundId } = req.params;
      const { status, process_remark } = req.body;
      const adminId = req.user.id;

      // 验证状态
      const validStatuses = ['approved', 'rejected', 'completed'];
      if (!validStatuses.includes(status)) {
        return res.status(400).json({
          success: false,
          message: '无效的退款状态'
        });
      }

      const refund = await PaymentService.processRefund(refundId, status, {
        processed_by: adminId,
        process_remark
      });

      res.json({
        success: true,
        message: '退款处理成功',
        data: refund
      });
    } catch (error) {
      console.error('处理退款控制器错误:', error);
      res.status(500).json({
        success: false,
        message: error.message || '处理退款失败'
      });
    }
  }

  /**
   * 获取退款详情
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async getRefund(req, res) {
    try {
      const { refundId } = req.params;
      const userId = req.user.id;

      const refund = await PaymentService.getRefundById(refundId);

      // 检查权限
      if (req.user.role === 'user' && refund.user_id !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权访问此退款记录'
        });
      }

      res.json({
        success: true,
        data: refund
      });
    } catch (error) {
      console.error('获取退款详情控制器错误:', error);
      if (error.message === '退款记录不存在') {
        return res.status(404).json({
          success: false,
          message: '退款记录不存在'
        });
      }
      res.status(500).json({
        success: false,
        message: error.message || '获取退款详情失败'
      });
    }
  }

  /**
   * 获取支付统计信息（管理员）
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async getPaymentStatistics(req, res) {
    try {
      const filters = {
        start_date: req.query.start_date,
        end_date: req.query.end_date,
        payment_method: req.query.payment_method
      };

      const statistics = await PaymentService.getPaymentStatistics(filters);

      res.json({
        success: true,
        data: statistics
      });
    } catch (error) {
      console.error('获取支付统计控制器错误:', error);
      res.status(500).json({
        success: false,
        message: error.message || '获取支付统计失败'
      });
    }
  }
}

module.exports = new PaymentController();