import Router from '@koa/router';
import { Context } from 'koa';
import * as PaymentService from './payment.service';
import { BadRequestError } from '../../middleware/errorHandler';
import { authMiddleware } from '../../middleware/auth';
import { prisma } from '../../models';
import { safeParseInt } from '../../utils/safe-parse';

const router = new Router();

// 创建支付订单
router.post('/create', authMiddleware, async (ctx: Context) => {
  const userId = safeParseInt(ctx.state.user.userId);
  const { planId, paymentMethod, period = 'monthly', returnUrl } = ctx.request.body as {
    planId: number;
    paymentMethod: 'alipay' | 'wechat' | 'mock';
    period?: 'monthly' | 'yearly';
    returnUrl?: string;
  };

  if (!planId) {
    throw new BadRequestError('请选择套餐');
  }

  if (!['alipay', 'wechat', 'mock'].includes(paymentMethod)) {
    throw new BadRequestError('请选择支付方式');
  }

  const result = await PaymentService.createPaymentOrder(userId, planId, paymentMethod, period, returnUrl);

  ctx.body = {
    code: 0,
    message: '订单创建成功',
    data: result
  };
});

// 模拟支付（仅开发环境）
router.post('/mock', authMiddleware, async (ctx: Context) => {
  if (process.env.NODE_ENV === 'production') {
    throw new BadRequestError('生产环境不可用');
  }

  const userId = safeParseInt(ctx.state.user.userId);
  const { orderNo } = ctx.request.body as { orderNo: string };

  if (!orderNo) {
    throw new BadRequestError('订单号不能为空');
  }

  const result = await PaymentService.mockPaymentSuccess(orderNo, userId);

  ctx.body = {
    code: 0,
    message: result.message,
    data: result
  };
});

// 支付宝异步通知回调
router.post('/alipay/notify', async (ctx: Context) => {
  const params = ctx.request.body as Record<string, string>;

  console.log('[Alipay Notify] 收到异步通知:', params);

  // 验证签名
  const signVerified = PaymentService.verifyAlipaySign(params);
  if (!signVerified) {
    console.error('[Alipay Notify] 签名验证失败');
    ctx.status = 400;
    ctx.body = 'fail';
    return;
  }

  const { out_trade_no, trade_status, trade_no } = params;

  try {
    if (trade_status === 'TRADE_SUCCESS' || trade_status === 'TRADE_FINISHED') {
      // 支付成功
      await PaymentService.handlePaymentCallback(out_trade_no, trade_no, 'success');
      console.log('[Alipay Notify] 订单支付成功:', out_trade_no);
      ctx.body = 'success';
    } else if (trade_status === 'WAIT_BUYER_PAY') {
      // 等待买家付款
      console.log('[Alipay Notify] 等待买家付款:', out_trade_no);
      ctx.body = 'success';
    } else {
      // 其他状态视为失败
      await PaymentService.handlePaymentCallback(out_trade_no, trade_no, 'failed');
      console.log('[Alipay Notify] 订单支付失败:', out_trade_no, trade_status);
      ctx.body = 'success';
    }
  } catch (error) {
    console.error('[Alipay Notify] 处理回调失败:', error);
    ctx.status = 500;
    ctx.body = 'fail';
  }
});

// 支付宝同步回调（用户从支付宝页面返回）
router.get('/alipay/return', async (ctx: Context) => {
  const params = ctx.query as Record<string, string>;

  console.log('[Alipay Return] 收到同步返回:', params);

  // 验证签名
  const signVerified = PaymentService.verifyAlipaySign(params);
  if (!signVerified) {
    console.error('[Alipay Return] 签名验证失败');
    // 重定向到支付结果页面（失败）
    const failUrl = `${process.env.ALIPAY_RETURN_URL || '/#/pages/payment-result/index'}?status=failed&error_msg=签名验证失败`;
    ctx.redirect(failUrl);
    return;
  }

  const { out_trade_no, trade_status } = params;

  // 根据支付状态重定向
  if (trade_status === 'TRADE_SUCCESS' || trade_status === 'TRADE_FINISHED') {
    // 支付成功
    const successUrl = `${process.env.ALIPAY_RETURN_URL || '/#/pages/payment-result/index'}?status=success&orderNo=${out_trade_no}&trade_status=${trade_status}`;
    ctx.redirect(successUrl);
  } else {
    // 支付未完成
    const failUrl = `${process.env.ALIPAY_RETURN_URL || '/#/pages/payment-result/index'}?status=failed&orderNo=${out_trade_no}`;
    ctx.redirect(failUrl);
  }
});

// 微信支付回调
router.post('/wechat/notify', async (ctx: Context) => {
  try {
    const body = ctx.request.body as any;
    console.log('[WeChat Notify] 收到回调:', JSON.stringify(body));

    const { out_trade_no, transaction_id, trade_state } = body;

    if (trade_state === 'SUCCESS') {
      await PaymentService.handlePaymentCallback(out_trade_no, transaction_id, 'success');
      console.log('[WeChat Notify] 订单支付成功:', out_trade_no);
    } else {
      await PaymentService.handlePaymentCallback(out_trade_no, transaction_id, 'failed');
      console.log('[WeChat Notify] 订单支付失败:', out_trade_no, trade_state);
    }

    ctx.body = { code: 'SUCCESS', message: '成功' };
  } catch (error) {
    console.error('[WeChat Notify] 处理回调失败:', error);
    ctx.status = 500;
    ctx.body = { code: 'FAIL', message: '处理失败' };
  }
});

// 查询微信支付订单状态
router.get('/wechat/query/:orderNo', authMiddleware, async (ctx: Context) => {
  const { orderNo } = ctx.params;

  const result = await PaymentService.queryWechatOrder(orderNo);

  if (!result) {
    ctx.body = {
      code: -1,
      message: '未配置微信支付或查询失败',
      data: null
    };
    return;
  }

  ctx.body = {
    code: 0,
    message: 'success',
    data: result
  };
});

// 获取订单列表
router.get('/orders', authMiddleware, async (ctx: Context) => {
  const userId = safeParseInt(ctx.state.user.userId);
  const { page = '1', pageSize = '20' } = ctx.query as { page?: string; pageSize?: string };

  const result = await PaymentService.getOrderList(
    userId,
    Number(page) || 1,
    Number(pageSize) || 20
  );

  ctx.body = {
    code: 0,
    message: 'success',
    data: result
  };
});

// 获取订单详情
router.get('/orders/:orderNo', authMiddleware, async (ctx: Context) => {
  const userId = safeParseInt(ctx.state.user.userId);
  const { orderNo } = ctx.params;

  const result = await PaymentService.getOrderDetail(orderNo, userId);

  ctx.body = {
    code: 0,
    message: 'success',
    data: result
  };
});

// 生成支付宝扫码支付二维码
router.post('/alipay/qrcode', authMiddleware, async (ctx: Context) => {
  const userId = parseInt(ctx.state.user.userId);
  const { planId } = ctx.request.body as { planId: number };

  if (!planId) {
    throw new BadRequestError('请选择套餐');
  }

  // 获取套餐信息
  const plan = await prisma.subscriptionPlan.findUnique({
    where: { id: planId }
  });

  if (!plan) {
    throw new BadRequestError('套餐不存在');
  }

  // 生成订单
  const orderNo = PaymentService.generateOrderNo();
  const amount = Number(plan.priceMonthly);

  // 创建订单记录
  await prisma.order.create({
    data: {
      userId,
      orderNo,
      planId,
      productType: 'monthly',
      amount,
      status: 'pending',
      paymentMethod: 'alipay',
    }
  });

  // 生成支付二维码链接
  const qrcodeUrl = await PaymentService.generateAlipayQrcode(orderNo, amount, plan.name);

  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      orderNo,
      amount,
      planName: plan.name,
      qrcode: qrcodeUrl
    }
  };
});

export default router;
