import { Hono } from 'hono';
import { authMiddleware } from '@d8d/auth-module-mt';
import { AppDataSource } from '@d8d/shared-utils';
import { OrderMt } from '../../entities/order.mt.entity';
import { DeliveryOrderDto } from '../../schemas/delivery.mt.schema';
import { OrderStatus } from '../../schemas/order.mt.schema';

const deliveryRoutes = new Hono();

// 发货订单
deliveryRoutes.post('/:id/delivery', authMiddleware, async (c) => {
  const orderId = parseInt(c.req.param('id'));
  const body = await c.req.json();

  // 验证请求数据
  const validatedData = DeliveryOrderDto.parse(body);

  const orderRepository = AppDataSource.getRepository(OrderMt);

  try {
    // 查找订单
    const order = await orderRepository.findOne({
      where: { id: orderId }
    });

    if (!order) {
      return c.json({
        success: false,
        message: '订单不存在'
      }, 404);
    }

    // 检查订单状态是否允许发货
    if (order.state !== OrderStatus.PENDING) {
      return c.json({
        success: false,
        message: '订单状态不允许发货'
      }, 400);
    }

    // 检查支付状态
    if (order.payState !== 2) { // 支付成功
      return c.json({
        success: false,
        message: '订单未支付成功，不能发货'
      }, 400);
    }

    // 更新订单发货信息
    order.state = OrderStatus.SHIPPED;
    order.deliveryType = validatedData.deliveryType;
    order.deliveryCompany = validatedData.deliveryCompany || null;
    order.deliveryNo = validatedData.deliveryNo || null;
    order.deliveryTime = new Date();
    order.deliveryRemark = validatedData.deliveryRemark || null;

    await orderRepository.save(order);

    return c.json({
      success: true,
      message: '发货成功',
      order: {
        id: order.id,
        orderNo: order.orderNo,
        state: order.state,
        deliveryType: order.deliveryType,
        deliveryCompany: order.deliveryCompany,
        deliveryNo: order.deliveryNo,
        deliveryTime: order.deliveryTime
      }
    });

  } catch (error) {
    console.error('发货失败:', error);
    return c.json({
      success: false,
      message: '发货失败，请重试'
    }, 500);
  }
});

// 获取发货信息
deliveryRoutes.get('/:id/delivery', authMiddleware, async (c) => {
  const orderId = parseInt(c.req.param('id'));

  const orderRepository = AppDataSource.getRepository(OrderMt);

  try {
    const order = await orderRepository.findOne({
      where: { id: orderId },
      select: ['id', 'orderNo', 'state', 'deliveryType', 'deliveryCompany', 'deliveryNo', 'deliveryTime', 'deliveryRemark']
    });

    if (!order) {
      return c.json({
        success: false,
        message: '订单不存在'
      }, 404);
    }

    return c.json({
      success: true,
      data: {
        id: order.id,
        orderNo: order.orderNo,
        state: order.state,
        deliveryType: order.deliveryType,
        deliveryCompany: order.deliveryCompany,
        deliveryNo: order.deliveryNo,
        deliveryTime: order.deliveryTime,
        deliveryRemark: order.deliveryRemark
      }
    });

  } catch (error) {
    console.error('获取发货信息失败:', error);
    return c.json({
      success: false,
      message: '获取发货信息失败'
    }, 500);
  }
});

export default deliveryRoutes;